Last Updated: February 25, 2016
·
402
· pose

Creating a done function for Javascript unit testing

You want to make a test timeout if a callback is not called (similar to mocha's done function) but you are not using any framework. How can you achieve that?

// When test will timeout
var TEST_TIMEOUT_MS = 3000;

var done = (function () {
  // Create a timer that will fail on timeout
  var timer = setTimeout(function () {
    assert.ok(false, 'Test timeout');
  }, TEST_TIMEOUT_MS);

  // return done that will clear the timer and
  // avoid the timeout if called.
  return function () { clearTimeout(timer); };
})();