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?
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.
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);
    });
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With