AngularJS - 具有 jquery 功能的单元测试指令

AngularJS - Unit Test Directive with jquery function

我有一个如下所示的指令:

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

我试着用这个做单元测试:

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

当我运行指令正常时,我得到输出newDirective Content:abc。但是当我 运行 单元测试时,我得到日志输出 newDirective Content:undefined.

如何让 jquery 函数在单元测试中工作?

我建议你(如果你有控制权)你不使用 jQuery 在

内获得 html
<div id="sub">abc</div> 

并改为使用 jQlite 搜索 DOM。

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

您还可能希望重构您的规范,以便 html 的编译发生在 it 函数之外 - 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);
    });

});

如果真的想在指令中使用 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);

通过添加 element.appendTo(document.body);,您将在单元测试中获得 jQuery 功能。

您可以将元素作为第二个参数传递:

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

或者您可以将元素作为 $() 参数传递并使用其他方法:

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