title: Unit Testing Angular Service that uses $timeout with Jasmine's Mock Clock
body: <p>I have a function inside one of my angular services that I'd like to be called repeatedly at a regular interval.  I'd like to do this using $timeout.  It looks something like this:</p>
  
  <pre><code>var interval = 1000; // Or something
  
  var _tick = function () {
       $timeout(function () {
          doStuff();
          _tick();
      }, interval);
  };
  
  _tick();
  </code></pre>
  
  <p>I'm stumped on how to unit test this with Jasmine at the moment - How do I do this?  If I use <code>$timeout.flush()</code> then the function calls occur indefinitely.  If I use Jasmine's mock clock, <code>$timeout</code> seems to be unaffected.  Basically if I can get this working, I should be good to go:</p>
  
  <pre><code>describe("ANGULAR Manually ticking the Jasmine Mock Clock", function() {
      var timerCallback, $timeout;
  
      beforeEach(inject(function($injector) {
          $timeout = $injector.get('$timeout');
          timerCallback = jasmine.createSpy('timerCallback');
          jasmine.Clock.useMock();
      }));
  
      it("causes a timeout to be called synchronously", function() {
          $timeout(function() {
              timerCallback();
          }, 100);
          expect(timerCallback).not.toHaveBeenCalled();
          jasmine.Clock.tick(101);
          expect(timerCallback).toHaveBeenCalled();
      });
  });
  </code></pre>
  
  <p>These two variations work, but do not help me:</p>
  
  <pre><code>describe("Manually ticking the Jasmine Mock Clock", function() {
      var timerCallback;
  
      beforeEach(function() {
          timerCallback = jasmine.createSpy('timerCallback');
          jasmine.Clock.useMock();
      });
  
      it("causes a timeout to be called synchronously", function() {
          setTimeout(function() {
              timerCallback();
          }, 100);
          expect(timerCallback).not.toHaveBeenCalled();
          jasmine.Clock.tick(101);
          expect(timerCallback).toHaveBeenCalled();
      });
  });
  
  describe("ANGULAR Manually flushing $timeout", function() {
      var timerCallback, $timeout;
  
      beforeEach(inject(function($injector) {
          $timeout = $injector.get('$timeout');
          timerCallback = jasmine.createSpy('timerCallback');
      }));
  
      it("causes a timeout to be called synchronously", function() {
          $timeout(function() {
              timerCallback();
          }, 100);
          expect(timerCallback).not.toHaveBeenCalled();
          $timeout.flush();
          expect(timerCallback).toHaveBeenCalled();
      });
  });
  </code></pre>
  
  <p>Thanks in advance!</p>