【问题标题】:AngularJS - Unit Test Directive with jquery functionAngularJS - 带有 jquery 功能的单元测试指令
【发布时间】:2015-06-12 19:50:48
【问题描述】:

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

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 函数在单元测试中工作?

【问题讨论】:

  • 有谁知道如何完成这项工作?这对我继续进行单元测试非常重要。 TQ。

标签: jquery angularjs unit-testing jasmine karma-jasmine


【解决方案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函数在单元测试中的工作。

【讨论】:

  • 非常聪明。干得好。
【解决方案2】:

我建议你(如果你有控制权的话)不要使用 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());
        }
    };
}]);

您还可能希望重新考虑您的规范,以便在 it 函数之外进行 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);
    });

});

【讨论】:

    【解决方案3】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-07-12
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 2014-01-29
      • 1970-01-01
      • 2014-05-23
      相关资源
      最近更新 更多