注入されたサービスを呼び出すディレクティブをテストする必要があります。次のコードは、イベントをリッスンし、指定された要素内で 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
};
}]);
問題は、ディレクティブでサービスをスパイするためにサービスを注入する方法を理解していないことです。
私が提案したソリューションは次のよう
になります。スパイするサービスをうまく注入できなかったため、期待どおりに機能しません。$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.