ng-model未按预期更新keydown事件

时间:2015-05-05 20:28:50

标签: jquery angularjs unit-testing jasmine

我正在尝试编写单元测试来测试我的指令。当我调用keydown事件时,ng-model没有更新。如何从单元测试中更改ng-model?

我的spec文件如下:

describe('validNumber', function () {

       var scope, elem, compiled, html, usageScenarioModel, preventDefault, mockedEvent;


    var triggerKeyDown = function (element, keyCode) {
        mockedEvent = angular.element.Event('keydown');
        mockedEvent.which = keyCode;
        preventDefault = spy(mockedEvent, 'preventDefault');
        element.trigger(mockedEvent);
    };

    beforeEach(function(){
        html = '<input type="number" valid-number ng-model="model.values[0].percentage"/>';

        inject(function($compile, $rootScope, _model_){
            model = _model_;
            scope = $rootScope.$new();
            elem = angular.element(html);
            scope.model = _model_;
            scope.model.values =  [{percentage:0}]};
            compiled = $compile(elem);
            compiled(scope);
            scope.$digest();
        })
    });

     it('should disable user to type non-numerical value into field', function(){
        triggerKeyDown(elem, 76); //76 is l
        verify(preventDefault);
    });

    it('should enable user to type numerical value into field', function(){
        triggerKeyDown(elem, 50); //76 is l
        verify(preventDefault);
    });

});

validNumber指令只允许将数字输入数字框。

module.exports = function () {

        function arrayContains(array, value){
            for(var i = 0; i < array.length; i++){
                if(array[i] === value){
                    return i;
                }
            }
            return -1;
        }

        return function(scope, element) {
           var keyCode =   [8,9,37,39,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105,110];
           element.bind("keydown", function(event) {
           if(arrayContains(keyCode, event.which) == -1){
               event.preventDefault();
           }
        });
    };
};

更新我更新了测试以验证是否调用了preventDefault方法。但是这不起作用。两个测试通过,第二个应该失败。我还调试了代码并正确执行。有没有人知道为什么没有按预期验证方法调用?

0 个答案:

没有答案