Ken*_*nne 26 unit-testing jasmine angularjs angularjs-directive
我需要测试一个指令来执行一些注入服务的调用.下面的代码是一个示例指令,用于侦听事件,如果在指定元素内按下enter,则重定向浏览器.
编辑:我觉得我可能会在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
};
}]);
Run Code Online (Sandbox Code Playgroud)
问题是我还没有弄清楚如何注入服务来监视它们的指令.
我提出的解决方案看起来像这样:
它没有按预期工作,因为我没有设法$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');
}));
Run Code Online (Sandbox Code Playgroud)
这产生了
Expected spy path to have been called with [ 'http://www.google.com' ] but it was never called.
Run Code Online (Sandbox Code Playgroud)
Ken*_*nne 35
要装饰,存根,提供模拟或覆盖任何给定的服务,您可以使用该$provide服务.
$provide.value,$provide.decorator等文档这里.
然后你可以做这样的事情:
var $location;
beforeEach(function() {
module('studentportalenApp', function($provide) {
$provide.decorator('$location', function($delegate) {
$delegate.path = jasmine.createSpy();
return $delegate;
});
});
inject(function(_$location_) {
$location = _$location_;
});
});
Run Code Online (Sandbox Code Playgroud)
...
it('should visit the link in scope.redirectUrl 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);
$rootScope.$digest();
expect($location.path).toHaveBeenCalledWith('http://www.google.com');
}));
Run Code Online (Sandbox Code Playgroud)