How do you mock directives to enable unit testing of higher level directive?

前端 未结 7 1814
故里飘歌
故里飘歌 2020-12-04 09:05

In our app we have several layers of nested directives. I\'m trying to write some unit tests for the top level directives. I\'ve mocked in stuff that the directive itself ne

相关标签:
7条回答
  • 2020-12-04 09:41

    Directives are just factories, so the best way to do this is to mock the factory of the directive in using the module function, typically in the beforeEach block. Assuming you have a directive named do-something used by a directive called do-something-else you'd mock it as such:

    beforeEach(module('yourapp/test', function($provide){
      $provide.factory('doSomethingDirective', function(){ return {}; });
    }));
    
    // Or using the shorthand sytax
    beforeEach(module('yourapp/test', { doSomethingDirective: {} ));
    

    Then the directive will be overridden when the template is compiled in your test

    inject(function($compile, $rootScope){
      $compile('<do-something-else></do-something-else>', $rootScope.$new());
    });
    

    Note that you need to add the 'Directive' suffix to the name because the compiler does this internally: https://github.com/angular/angular.js/blob/821ed310a75719765448e8b15e3a56f0389107a5/src/ng/compile.js#L530

    0 讨论(0)
提交回复
热议问题