Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Unit Test Directive with jquery function

I have a directive that looks like this:

angular.directive('newDirective', ['$compile', function($compile){
    return {
        link: function(scope, element, attr, controller) {
            console.log("newDirective Content:"+$("#sub").html());
        }
    };
}]);

I tried to do unit test with this:

describe('newDirective Test',function(){
    beforeEach(module('app'));

    it('Temporary test jquery function', inject(function($compile,$rootScope) {
        var element = $compile('<div new-directive><div id="sub">abc</div></div>')($rootScope);
    }));
});

When I run the directive normally, I get the output newDirective Content:abc. But when I run unit test, I get log output newDirective Content:undefined.

How can I get jquery function to work in unit test?

like image 253
user1995781 Avatar asked Apr 08 '15 02:04

user1995781


2 Answers

If really want to use jQuery function in directive, this is how it can be done in unit test:

var scope = $rootScope.$new();
var element = angular.element('<div new-directive><div id="sub">abc</div></div>');
element.appendTo(document.body);
element = $compile(element)(scope);

By adding element.appendTo(document.body);, you will get jQuery function work in unit test.

like image 139
user1995781 Avatar answered Nov 07 '22 12:11

user1995781


I suggest that you (if you have control) that you don't use jQuery get the html within

<div id="sub">abc</div> 

and instead use jQlite to search the DOM.

testApp.directive('newDirective', ['$compile', function($compile){
    return {
        link: function(scope, element, attr, controller) {
            console.log("newDirective Content:"+element.find('#sub').html());
        }
    };
}]);

You also may then wish to re-factor your spec so that the compilation of the html takes place outside the it function - jsfiddle demo.

describe('newDirective Test',function(){
    beforeEach(module('testApp'));

    var element, scope;

    beforeEach(inject(function($rootScope, $compile) {
        element = angular.element('<div new-directive><div id="sub">abc</div></div>');
        scope = $rootScope;
        $compile(element)(scope);
        scope.$digest();
    }));

    it("should contain a div tag", function() {
        expect(element.find('div').length).toEqual(1);
    });

});
like image 5
Nicholas Murray Avatar answered Nov 07 '22 14:11

Nicholas Murray