Skip to content
Advertisement

Mocha test false assert timeouts

I have some problem with my async mocha tests. The assert method within a promise results in a timeout when the input evaluates to false. (with true values it works fine)

This is a simplified version of the problem. We usually do networking instead of this constructed promise.

describe('test',  () => {

    it('testcase', (done) => {

        new Promise(async (res) => {

            console.log("before");
            assert(false);
            console.log("after");

            res(null);
        }).then(() => done()).catch(() => done());

    });
});
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

Advertisement

Answer

You’d better NOT use async/await syntax on the promise constructor. It’s an anti-pattern.

assert(false) will throw an error, but this error will not be caught by the .catch() method. For more info, see https://stackoverflow.com/a/43050114/6463558

So you should remove the async from the promise constructor. Then, the error which assert(false) threw will be caught.

E.g.

import { assert } from 'chai';

describe('test', () => {
  it('testcase', (done) => {
    new Promise((res) => {
      console.log('before');
      assert(false);
      console.log('after');

      res(null);
    })
      .then(() => done())
      .catch((err) => done(err));
  });

  it('testcase - 2', (done) => {
    new Promise((res) => {
      console.log('before');
      assert(true);
      console.log('after');

      res(null);
    })
      .then(() => done())
      .catch((err) => done(err));
  });
});

test result:

  test
before
    1) testcase
before
after
    ✓ testcase - 2


  1 passing (9ms)
  1 failing

  1) test
       testcase:
     AssertionError: Unspecified AssertionError
      at /Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/66461468/index.test.ts:7:7
      at new Promise (<anonymous>)
      at Context.<anonymous> (src/stackoverflow/66461468/index.test.ts:5:5)
      at processImmediate (internal/timers.js:439:21)



npm ERR! Test failed.  See above for more details.
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement