我需要测试一个对某些注入服务进行调用的指令。
以下代码是一个示例指令,它侦听事件,并在指定元素内按下 Enter 键时重定向浏览器。
Edit: 我感觉我可能正在涉足端到端测试领域?
angular.module('fooApp')
.directive('gotoOnEnter', ['$location', function ($location) {
var _linkFn = function link(scope, element, attrs) {
element.off('keypress').on('keypress', function(e) {
if(e.keyCode === 13)
{
$location.path(scope.redirectUrl);
}
});
}
return {
restrict: 'A',
link: _linkFn
};
}]);
问题是我还没有弄清楚如何在指令中注入服务来监视它们。
我提出的解决方案如下所示:正如预期的那样,它不起作用,因为我没有成功注入$locacion
服务成功监视。
describe('Directive: gotoOnEnter', function () {
beforeEach(module('fooApp'));
var element;
it('should visit the link in scope.url when enter is pressed', inject(function ($rootScope, $compile, $location) {
element = angular.element('<input type="text" goto-on-enter>');
element = $compile(element)($rootScope);
$rootScope.redirectUrl = 'http://www.google.com';
$rootScope.$digest();
var e = jQuery.Event('keypress');
e.keyCode = 13;
element.trigger(e);
spyOn($location, 'path');
expect($location.path).toHaveBeenCalledWith('http://www.google.com');
}));
这产生
Expected spy path to have been called with [ 'http://www.google.com' ] but it was never called.