AngularJS:指令限制:'E'阻止在Jasmine单元测试中调用元素click()事件

时间:2013-12-18 23:02:32

标签: javascript unit-testing angularjs jasmine

以下是一些指令和单元测试。

这是第一个指令:

directive('myTestDirective', function() {
    return {
        link: function(scope, element, attrs) {
            element.on("click", function(e) {
            scope.clicked = true;
            console.log("clicked");
        }
    }
});

单元测试:

describe('my test directive', function() {
    beforeEach(function() {
        .....
        inject($compile, $rootScope) {
            scope = $rootScope.$new();
            html = '<div my-test-directive></div>';
            elem = angular.element(html);
            compiled = $compile(elem);
            compiled(scope);
            scope.$digest();
        }
    });
    it('should set clicked to true when click() is called', function() {
        elem[0].click();
        expect(scope.clicked).toBe(true);
    });
});

运行上述单元测试时,测试通过并将clicked记录到控制台。

但是,请考虑添加restrict: E的此指令:

directive('myDirective', function() {
    return {
        restrict: 'E',
        link: function(scope, element, attrs) {
            element.on("click", function(e) {
            scope.clicked = true;
            console.log("clicked");
        }
    }
});

单元测试:

describe('my directive', function() {
    beforeEach(function() {
        .....
        inject($compile, $rootScope) {
            scope = $rootScope.$new();
            html = '<my-directive></my-directive>';
            elem = angular.element(html);
            compiled = $compile(elem);
            compiled(scope);
            scope.$digest();
        }
    });
    it('should set clicked to true when click() is called', function() {
        elem[0].click();
        expect(scope.clicked).toBe(true);
    });
});

此测试失败。 clicked未记录到控制台。从调试中我可以看到绑定指令的click()绑定的函数没有被执行。

如何继续使用restrict : 'E',同时仍保留在单元测试中模拟点击次数的功能?

更新:感谢Michal的plunkr,我有它的工作。

我将inject()函数更改为:

inject(function($compile, $rootScope, $document) {
    scope = $rootScope.$new();
    html = '<my-test-directive-element></my-test-directive-element>';
    elem = angular.element(html);
    $compile(elem)(scope);
    scope.$digest();
});

在此之后,单击使用restrict属性并限制元素工作。

Plukr在这里: http://plnkr.co/edit/fgcKrYUEyCJAyqc4jj7P

1 个答案:

答案 0 :(得分:2)

使用jqLit​​e('click')并不是非常Angular-ish,我认为它不会被Angular摘要周期处理(因此无论你在该回调中添加到你的作用域,都不会在你的回调中呈现DOM,除非你手动完成)。您应该更喜欢在您的内部使用内置的ng-click指令,因此html代码变为:

<my-directive ng-click="onClick()"></my-directive>

和你的指令:

directive('myDirective', function() {
  return {
    restrict: 'E',
    link: function(scope, element, attrs) {
      scope.onClick = function() {
        scope.clicked = true;
        console.log("clicked");
      }
    }
  }
});