title: AngularJS: how to test directive which gives focus to element?
body: <p><strong>Note: the suggested link is an answer to a question about a service, and doesn't give a clear explanation on how to solve this issue</strong></p>
  
  <p>I'm trying to setup a karma test for my simple (and working) AngularJS <code>autofocus</code> directive:</p>
  
  <pre><code>app.directive('autofocus', function ($timeout) {
    return {
      replace: false,
      link: function (scope, element, attr) {
        scope.$watch(attr.autofocus,
          function (value) {
            if (value) {
              $timeout(function () {
                element[0].focus();
                console.log('focus called');
              });
            }
          }
        );
      }
    };
  });
  </code></pre>
  
  <p>This is my current test:</p>
  
  <pre><code>describe('The autofocus directive', function () {
    var timeout;
    beforeEach(module('myApp'));
    beforeEach(inject(function($timeout) {
      timeout = $timeout;
    }));
  
    it('should set focus to first autofocus element', function () {
      var form = angular.element('&lt;form /&gt;');
      var input1 = angular.element('&lt;input type="text" name="first" /&gt;');
      var input2 = angular.element('&lt;input type="text" name="second" autofocus="true" /&gt;');
      form.append(input1);
      form.append(input2);
      spyOn(input2[0], 'focus');
      timeout.flush();
      expect(input2[0].focus).toHaveBeenCalled();
    });
  </code></pre>
  
  <p>This is the (FAILED) output from <code>karma</code>:</p>
  
  <blockquote>
    <p><em>$ node_modules/karma/bin/karma start test/karma.conf.js</em><br>
    INFO [karma]: Karma v0.12.23 server started at http:// localhost:8080/<br>
    INFO [launcher]: Starting browser PhantomJS<br>
    INFO [PhantomJS 1.9.8 (Linux)]: Connected on socket U34UATs8jZDPB74AXpqR with id 96802943<br>
    PhantomJS 1.9.8 (Linux): Executed 0 of 20 SUCCESS (0 secs / 0 secs)<br>
    PhantomJS 1.9.8 (Linux) The autofocus directive should set focus to first autofocus element FAILED<br>
                <strong>Expected spy focus to have been called.</strong><br>
    PhantomJS 1.9.8 (Linux): Executed 20 of 20 (1 FAILED) (0.156 secs / 0.146 secs)  </p>
  </blockquote>
  
  <hr>
  
  <p>Just adding</p>
  
  <pre><code>input[0].focus();
  </code></pre>
  
  <p>after <code>spyOn(input[0], 'focus')</code> the test succeeds, of course, but it's not what I want...</p>
  
  <hr>
  
  <p>The final question is: <strong><em>How do I karma-test a directive which sets focus to an element ?</em></strong></p>