8

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?

1
  • Do anyone knows how to get this done? This is very important for me to continue with unit test. TQ. Commented Apr 9, 2015 at 1:53

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Very clever. Nice job.
4

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);
    });

});

Comments

0

You can pass the element as the second argument:

$('#your-id', element);

Or you can just pass the element as the $() argument and use other methods:

$(element).find('#your-id');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.