Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to inject a service in a directive unit test in AngularJS
    primarykey
    data
    text
    <p>I need to test a directive that does some calls to some injected services. The following piece of code is an example directive, that listens for events, and redirects the browser if enter is pressed inside a specified element.</p> <p>Edit: <em>I get the feeling I may be wading in E2E testing land?</em></p> <pre><code>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 }; }]); </code></pre> <p>The problem is that I have not figured out how to inject services to spy on them in directives.</p> <p>My proposed solution looks like this: <em>It does not work, as expected, because I have not managed to inject a <code>$locacion</code> service successfully to spy on.</em></p> <pre><code>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('&lt;input type="text" goto-on-enter&gt;'); 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'); })); </code></pre> <p><strong>This yields</strong></p> <pre><code>Expected spy path to have been called with [ 'http://www.google.com' ] but it was never called. </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload