简体   繁体   中英

How to mock nested directive in Angular 1.x (Unit testing)

Hey I have problem with mock my directive. Look at this code:

 <dir-one data="data">
<div ng-repeat="e in data">
  <div ng-repeat="e2 in e">
   <dir-two prop="e2.some" prop2="e2.some">  <!-- i want to mock this directive -->
   </dir-two>
 </div>
</dir-one>

Not I want to mock this template to jasmine and reproduce dir-two click event.

I tryed something like this :

var tpl = `<dir-one data="data">
<div ng-repeat="e in data">
  <div ng-repeat="e2 in e">
   <dir-two prop="e2.some" prop2="e2.some">  <!-- i want to mock this directive -->
   </dir-two>
 </div>
</dir-one>`

    var newScope = $rootScope.$new();
    newScope.DATA = // some data;

    el= angular.element(tpl);
    $compile(el)(newScope);
    $rootScope.$digest();
    catchController = el.controller('dirTwoController'); // undefined
    catchController2 = el.controller('dirOneController'); // no error, catch object

There is a problem, becouse I cant reproduce dirTwoController using this mock, just dirOneController corectly showing output.

Any ideas for solve this problem ?

Thanks !

One way to do this would be to use $provide to mock the directive implementation. This could be done in beforeEach before the parent directive is compiled.

beforeEach(module(function ($provide) {
    $provide.factory('dirTwoDirective', function() { 
        return {
            // Implementation of directive here
        }; 
    });
}));

Note how the word Directive has been added to the end of the directive name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM