Monthly Archives: May 2013

Solving setTimeout-problem using QUnit and SinonJS

Recently had a problem testing setTimout-callbacks when using the QUnit javascript testing framework and also adding SinonJS to the mix for faking xmlHttp-requests. Could not get the callback to fire. After a long time trying different examples using QUnit and SinonJS I finally got my facepalm moment and solved it.

When adding the Sinon javascript and sinon-qunit script the QUnit script has a config section that enables useFakeTimers by default, so the clock wouldn’t tick/advance by default.

If you really want to use setTimeout the QUnit way (start/stop-functions), then your tests will have to wait until timeout elapses

A better way is to use sinon’s fake timers. a trivial example:

test("test with useFakeTimers", function () {
  this.sandbox.useFakeTimers();

  setTimeout(function () {
    ok(true, "timeout sucessfully called");
  }, 150);

  this.sandbox.clock.tick(200);
});

and if you have useFakeTimers = true in your sinon-qunit-javascript you can even remove this.sandbox.useFakeTimers()

note: as of february 2010 the source at github has changed to have useFakeTimers disabled by default.