title: Spy on setTimeout and clearTimeout in Karma and Jasmine
body: <p>I cannot seem to be able to spy on <code>setTimeout</code> and <code>clearTimeout</code> in my Jasmine tests, which are being run through Karma. </p>
  
  <p>I have tried variations on all of this</p>
  
  <pre><code>spyOn(window, 'setTimeout').and.callFake(()=&gt;{});
  spyOn(global, 'setTimeout').and.callFake(()=&gt;{});
  spyOn(window, 'clearTimeout').and.callThrough();
  
  clock = jasmine.clock();
  clock.install();
  spyOn(clock, 'setTimeout').and.callThrough();
  
  runMyCode();
  
  expect(window.setTimeout).toHaveBeenCalled(); // no
  expect(global.setTimeout).toHaveBeenCalled(); // nope
  expect(window.clearTimeout).toHaveBeenCalled(); // no again
  expect(clock.setTimeout).toHaveBeenCalled(); // and no
  </code></pre>
  
  <p>In every case, I can confirm that <code>setTimeout</code> and <code>clearTimeout</code> have been invoked in <code>runMyCode</code>, but instead I always get <code>Expected spy setTimeout to have been called.</code></p>
  
  <p>For <code>window</code>, clearly this is because the test and the runner (the Karma window) are in different frames (so why should I expect anything different). But because of this, I can't see any way to confirm that these global functions have been invoked.</p>
  
  <p>I know that I can use <code>jasmine.clock()</code> to confirm that timeout/interval callbacks have been invoked, but it looks like I can't watch <code>setTimeout</code> itself. And confirming that <code>clearTimeout</code> has been called simply isn't possible.</p>
  
  <p>At this point, the only thing I can think of is to add a separate layer of abstraction to wrap <code>setTimeout</code> and <code>clearTimeout</code> or to inject the functions as dependencies, which I've done before, but I think is weird.</p>