title: Angular + Karma: Testing async functions
body: <p>I have an angular service that does some async stuff (based on timers).  One of the things you can do with a timer is define a 'handler' that fires when the timer expires (as in this pseudo-code):</p>
  
  <pre><code>flag = false;
  timer = new Timer(1000); // ms
  timer.handler = function () { flag = true };
  </code></pre>
  
  <p>In this trivial case, the timer would set flag to true after 1 second.  How do I unit test this with Angular/Karma/Jasmine?</p>
  
  <p>From reading the docs, I would have expected this to work:</p>
  
  <pre><code>... 
  flag = false;
  timer = new Timer(1000);
  timer.handler = function () { flag = true };
  expect(flag).toBe(false);
  sleep(2)
  expect(flag).toBe(true);
  ...
  </code></pre>
  
  <p>Rather than being morally upright, that test decided to fail with this:</p>
  
  <pre><code>ReferenceError: Can't find variable: sleep
  </code></pre>
  
  <p>After some reading, apparently I can't use angular-scenario with Jasmine.  Ok, I'm cool with that.  </p>
  
  <p><strong>UPDATE</strong> :  <em>Per the comments, I tested my "working" settimeout method.  It doesn't ever get called.</em></p>
  
  <p><del>So this works:</del></p>
  
  <pre><code>... 
  flag = false;
  timer = new Timer(1000);
  timer.handler = function () { flag = true };
  expect(flag).toBe(false);
  setTimeout(function () { expect(flag).toBe(true) }, 2000);
  ...
  </code></pre>
  
  <p><del>But feels a little weird.</del></p>
  
  <p>Question:  <strong>Is there a better way?</strong></p>
  
  <p><em>Fun Trivia:  Yep, I know about $timeout.  I have Very Good Reasons(TM) for doing the things I did deep in the code mines, away from the light of day =)</em></p>