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

use*_*781 7 jquery unit-testing jasmine angularjs karma-jasmine

我有一个看起来像这样的指令:

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

我试着用这个进行单元测试:

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);
    }));
});
Run Code Online (Sandbox Code Playgroud)

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

如何在单元测试中使用jquery函数?

use*_*781 8

如果真的想在指令中使用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);
Run Code Online (Sandbox Code Playgroud)

通过添加element.appendTo(document.body);,您将获得单元测试中的jQuery函数.


Nic*_*ray 5

我建议您(如果您有控制权)不要使用 jQuery 获取其中的 html

<div id="sub">abc</div> 
Run Code Online (Sandbox Code Playgroud)

而是使用jQlite来搜索 DOM。

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

然后,您还可能希望重构您的规范,以便 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);
    });

});
Run Code Online (Sandbox Code Playgroud)