title: Using Mocha, Chai and Sinon to test a delayed action
body: <p>I want to create a unit test for an asynchronous process. I have created a bare-bones mock up of the situation, using a timeout to delay an alert. (The real process will be the loading of a JS file on the fly).</p>
  
  <p>I'm just beginning with Mocha, Chai and Sinon. I've created a folder called <code>vendor</code> alongside my HTML file. This contains the latest versions of mocha.css, mocha.js, chai.js and sinon.js.</p>
  
  <p>The code below works fine if I comment out the <code>setTimeout()</code> call. How should I alter it so that the <code>sinon.assert...</code> calls will wait for the delayed action to occur?</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;head&gt;
    &lt;title&gt;Delayed alert test&lt;/title&gt;
  &lt;/head&gt;
  
  &lt;body&gt;
  &lt;div id="mocha"&gt;&lt;p&gt;&lt;a href="."&gt;Index&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;
  &lt;div id="messages"&gt;&lt;/div&gt;
  &lt;div id="fixtures"&gt;&lt;/div&gt;
  &lt;link rel="stylesheet" type="text/css" href="vendor/mocha.css" /&gt;
  &lt;script src="vendor/mocha.js"&gt;&lt;/script&gt;
  &lt;script src="vendor/chai.js"&gt;&lt;/script&gt;
  &lt;script src="vendor/sinon.js"&gt;&lt;/script&gt;
  
  &lt;script&gt;
  mocha.setup('bdd')
  
  var spy = sinon.spy(window, 'alert')
  
  describe("Test", function() {
    describe("#alert", function() {
      it("should show an alert", function(done) {
        this.timeout(5000)
  
        setTimeout(function () { // Works if these 2 lines...
          alert ("Once")
          alert ("Twice")
        }, 2000)                 // are commented out
        sinon.assert.called(spy)
        sinon.assert.calledTwice(spy)
        sinon.assert.calledWithExactly(spy, "Once")
        sinon.assert.calledWithExactly(spy, "Twice")
        done()
      });
    });
  })
  
  mocha.run();
  &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>