如何在角度指令中对按键事件进行单元测试

时间:2014-05-08 20:16:38

标签: angularjs events angularjs-directive jasmine

我已经创建了一个编辑指令,用于将html输入包装在一个花哨的框架中。

现在我正在创建一个单元测试来检查一旦输入输入,就会设置表单控制器的脏状态。 这是我到目前为止所得到的,但它在第二次预期失败了。

这里有什么问题?

提前致谢!

describe('dirty', function () {
    it('false', function () {
        var scope = $rootScope.$new(),
            form = $compile('<form name="form"><edit ng-model="model"></edit></form>')(scope),
            input = form.find('input');
        scope.$digest();
        expect(scope.form.$dirty).toBeFalsy();
        input.triggerHandler('keydown', { which: 65 });
        expect(scope.form.$dirty).toBeTruthy();
    });
});

修改

对于所有重要的事情,它归结为plunker(没有jQuery)......或this使用jQuery

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

ngKeySpec.js中的角度单位测试很有帮助:

it('should get called on a keydown', inject(function($rootScope, $compile) {
    element = $compile('<input ng-keydown="touched = true">')($rootScope);
    $rootScope.$digest();
    expect($rootScope.touched).toBeFalsy();

    browserTrigger(element, 'keydown');
    expect($rootScope.touched).toEqual(true);
  }));