简体   繁体   中英

link function of AngularJS directive never called in Jasmine test

I don't understand why the link function of my directive never gets called in an Jasmine test. I made a simple example.

Here is my directive (TestDirective.js):

 'use strict'; angular.module('comp-one').directive('test',function(){ return{ restrict:'E', templateUrl:'components/comp-one/html/TestTemplate.html', scope:true, link:function(scope){ scope.test='xxx'; } }; }); 

And this is the Testcase:

 'use strict'; describe('testDirective',function(){ var $compile, $rootScope, element; beforeEach(module('comp-one')); beforeEach(module('templates')); beforeEach(inject(function(_$rootScope_,_$compile_){ $compile = _$compile_; $rootScope = _$rootScope_; })); it('xxx', function(){ var html = '<test></test>'; element = $compile(html)($rootScope); $rootScope.$digest(); expect( $rootScope.test ).toBe('xxx'); }); }); 

The tests failed, because the link function never gets called and so the xxx variable ist undefined. I expected that the link function is excecuted by the "$compile(html)($rootScope);" statement. When I set an breakpoint into the link function and run the application (not the test) in a browser the link function is called.

I'm running the Tests with Karma, wich also finds the file as I can see in the console output:

Processing "D:/JWS/test/workspace/bla/app/components/comp-one/scripts/TestDirective.js".

Edit:

Okay, I found out that the test runs successful when I set the scope to false. But is there a way to test the link function with an isolated scope?

The link function is called. You will find the value on the element's scope, not on the $rootScope .

Use element.isolateScope().test instead of $rootScope.test in the expect part.

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