相关疑难解决方法(0)

如何在AngularJS中的指令测试中触发ng-change

我有以下AngularJS指令创建一个input元素.输入具有ng-change运行doIt()功能的属性.在我的指令单元测试中,我想检查doIt用户更改输入时是否调用函数.但测试没有通过.虽然它在手动测试时可以在浏览器中使用.

指示:

...
template: "<input ng-model='myModel' ng-change='doIt()' type='text'>" 
Run Code Online (Sandbox Code Playgroud)

测试:

el.find('input').trigger('change') // Dos not trigger ng-change
Run Code Online (Sandbox Code Playgroud)

现场演示(ng-change):http://plnkr.co/edit/0yaUP6IQk7EIneRmphbW?p = preview


现在,如果我手动绑定change事件而不是使用ng-change属性,则测试通过.

template: "<input ng-model='myModel' type='text'>",
link: function(scope, element, attrs) {
  element.bind('change', function(event) {
    scope.doIt();
  });
}
Run Code Online (Sandbox Code Playgroud)

现场演示(手动绑定):http://plnkr.co/edit/dizuRaTFn4Ay1t41jL1K?p = preview


有没有办法使用ng-change并使其可测试?谢谢.

angularjs angularjs-directive

19
推荐指数
1
解决办法
4万
查看次数

单元测试角度右键单击指令

我想为AngularJS指令编写一个Jasmine单元测试.该指令只是将contextmenu事件处理函数绑定到该元素:

var myDirectives = angular.module('myApp.directives', []);

myDirectives.directive('myRightClick', ['$parse', function ($parse) {
    return function (scope, element, attrs) {
        var fn = $parse(attrs.myRightClick);
        element.bind('contextmenu', function (event) {
            scope.$apply(function () {
                event.preventDefault();
                fn(scope, { $event: event });
            });
        });
    };
}]);

<div my-right-click="myFunction"></div>
Run Code Online (Sandbox Code Playgroud)

单元测试:

describe('Unit Test Directives', function () {
    var $compile;
    var $rootScope;

    beforeEach(module('myClientApp.directives'));

    beforeEach(inject(function (_$compile_, _$rootScope_) {
        $compile = _$compile_;
        $rootScope = _$rootScope_;
    }));

    it('should wire a contextmenu event binding for the element', function () {
        // Compile a piece of …
Run Code Online (Sandbox Code Playgroud)

unit-testing jasmine angularjs angularjs-directive

5
推荐指数
2
解决办法
3016
查看次数