Last Updated: February 25, 2016
·
734
· 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); };
})();

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside