Get #Amazon #Prime for this #holiday #amazonprime #christmas #2019

How to set timeout for #mocha async tests?

You can check out the following ways to set mocha test timeout if you want to increase or decrease the duration before your mocha tests timeout.

Mocha Homepage
Mocha Homepage

1)
it('test long async', (done) => {
  this.timeout(500);
  blogService.checkBlog()
    .then((response) => {
      assert.isObject(response);
    ...
      done();
    })
    .catch((err) => {
      done(err);
    });
});

2)

it('test long async', (done) => {
  setTimeout(done, 300);
  blogService.checkBlog()

    .then((response) => {
      assert.isObject(response);
    ...
      done();
    })
    .catch((err) => {
      done(err);
    });
});

3) If you use async and await

it(’test long async', async () => {
  // this.timeout(15000); // not gonna work
  const response = await blogService.checkBlog();
  ...
}).timeout('15s');

4) Using timeout flag: --timeout / -t to set timeout for all your test suites.

mocha ./tests/*.js --timeout 3s

5) If you need some async setup before running any of your test suites, you can add a delay flag to your mocha test command and write your mocha tests as following. Check out Mocha Delayed Root Suite document.

mocha ./tests/*.js --delay 3s


setTimeout(function() {
  // setup
  describe('blogService', function() {
    // ...
  });
  run();
}, 5000);

Thank you for reading!

Jun