Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using setTimeout() pause a Mocha test

Tags:

mocha.js

I'm using Mocha to write tests for a Node API. In one test, I need to execute 2 actions and compare the timestamp of each and ensure that they are different. To do that, I need to reliably pause the test execution for at least a second. I was trying to use setTimeout to pause the Mocha execution before the second call to ping, but it's not happening.

it( 'should insert then update the timestamp.', function( done ) {
  Do.ping( 'arg1', function( err, result ) {
    should.not.exist( err );

    setTimeout( Do.ping( 'arg1', function( err, result ) {
      // Test that the timestamp of the first ping is before the timestamp
      // of the second ping (among other things)
      done();
    }), 1000 );
  });
});

Anyone see what I've borked here? Alternatively, is there a better (i.e. more Mocha-ish) way to do what I'm trying to do?

like image 370
Rob Wilkerson Avatar asked Jul 26 '13 18:07

Rob Wilkerson


1 Answers

I ended up using Sinon's fake timer API and it's been working great. Instantiate and reset the fake timer in beforeEach() and afterEach(), respectively. Within the actual test, just advance the clock in whatever way you need:

clock.tick( 180000 ); // Advances the JS clock 3 minutes (180 seconds)
like image 166
Rob Wilkerson Avatar answered Sep 16 '22 23:09

Rob Wilkerson