简体   繁体   English

AngularJS - 带有jquery函数的单元测试指令

[英]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 . 当我正常运行指令时,我得到输出newDirective Content:abc But when I run unit test, I get log output newDirective Content:undefined . 但是当我运行单元测试时,我得到日志输出newDirective Content:undefined

How can I get jquery function to work in unit test? 如何在单元测试中使用jquery函数?

If really want to use jQuery function in directive, this is how it can be done in unit test: 如果真的想在指令中使用jQuery函数,这就是它在单元测试中的表现:

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); 通过添加element.appendTo(document.body); , you will get jQuery function work in unit test. ,您将在单元测试中获得jQuery函数。

I suggest that you (if you have control) that you don't use jQuery get the html within 我建议你(如果你有控制权)你不使用jQuery获取html

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

and instead use jQlite to search the DOM. 而是使用jQlite搜索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 . 您也可能希望重新考虑您的规范,以便html的编译发生在它的函数之外 - 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);
    });

});

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM