这是我需要进行单元测试的代码。
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和单元测试真的很陌生。请帮助。
为了提供更高的覆盖率,您的测试应该是这样的。
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');
});
});
如果你有什么问题,请给我留言,我会尽力解释给你听。