如何为keydown绑定指令编写单元测试?

时间:2015-09-19 13:24:41

标签: angularjs unit-testing angularjs-directive

这是我进行单元测试所需的代码。

todomvc.directive('todoEscape', function () {
    var ESCAPE_KEY = 27;
    return function (scope, elem, attrs) {
        elem.bind('keydown', **function (event) {
            if (event.keyCode === ESCAPE_KEY) {
                scope.$apply(attrs.todoEscape);**
            }
        });

        scope.$on('$destroy', function () {
            elem.unbind('keydown');
        });
    };
});

但**上面的部分始终没有涵盖。报道显示

陈述:75%,分支机构:0,功能:75%,线路:75%

以下是我的测试代码

'use strict';
beforeEach(module('todomvc'));

describe('todoEscape directive', function () {
  var scope, compile;

  beforeEach(inject(function ($rootScope, $compile) {
      scope = $rootScope.$new();
      compile = $compile;
  }));

  beforeEach(function() {
      var elem = angular.element('<input todo-escape="escape">');
      compile(elem)(scope);
      spyOn(element, 'bind').and.returnValue('keydown');
      var event = document.createEvent("Events");
      event.initEvent('keydown');
      event.keyCode = 27;
      element.triggerHandler(event);
  });

  it('should call callback function when the event happens', function() {
      expect(scope.escape()).toHaveBeenCalled();
  });

  it('deregisters on scope $destroy', function() {
      scope.$destroy();
      expect(scope.escape()).not.toHaveBeenCalled();
  });
});

我是AngularJS和单元测试的新手。请帮忙。

1 个答案:

答案 0 :(得分:2)

这是您的测试应该如何提供更高的覆盖率。

describe('todoEscape directive', function () {
  var scope, compile, element;

  beforeEach(inject(function ($rootScope, $compile) {
      scope = $rootScope.$new();
      scope.escapeCallback = jasmine.createSpy('escapeCallback');
      compile = $compile;
  }));

  beforeEach(function() {
      var elem = angular.element('<input todo-escape="escapeCallback">');
      element = compile(elem)(scope);
  });

  it('should call callback function on escape', function() {
    // given
    var givenEvent = { keyCode: 27 };

    // when
    element.triggerHandler('keydown', givenEvent);
    scope.$digest();

    // then
    expect(scope.escapeCallback).toHaveBeenCalled();
  });

  it('should not call escape callback when other key is down', function () {
    // given
    var givenEvent = { keyCode: 123 };
    scope.$digest();

    // when
    element.triggerHandler('keydown', givenEvent);

    // then
    expect(scope.escapeCallback).not.toHaveBeenCalled();
  });

  it('should unbind keydown event when scope is destroyed', function() {
    // given
    spyOn(element, 'unbind');

    // when
    scope.$destroy();

    // then
    expect(element.unbind).toHaveBeenCalledWith('keydown');
  });
});

如果您有任何疑问,请给我发表评论,我会尽力向您解释。