Wanderdüne
Wanderdüne

Reputation: 38

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?

Upvotes: 0

Views: 1393

Answers (1)

Tome Pejoski
Tome Pejoski

Reputation: 1582

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.

Upvotes: 3

Related Questions