我需要测试指令,做一些注射服务几个电话。 下面的代码段是一个例子指令,监听活动,并重定向如果输入被按下指定的元素内的浏览器。
编辑: 我得到我可以在E2E测试陆地上涉水的感觉?
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.