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.
JavaScript
x
16
16
1
describe('test', () => {
2
3
it('testcase', (done) => {
4
5
new Promise(async (res) => {
6
7
console.log("before");
8
assert(false);
9
console.log("after");
10
11
res(null);
12
}).then(() => done()).catch(() => done());
13
14
});
15
});
16
JavaScript
1
2
1
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
2
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.
JavaScript
1
28
28
1
import { assert } from 'chai';
2
3
describe('test', () => {
4
it('testcase', (done) => {
5
new Promise((res) => {
6
console.log('before');
7
assert(false);
8
console.log('after');
9
10
res(null);
11
})
12
.then(() => done())
13
.catch((err) => done(err));
14
});
15
16
it('testcase - 2', (done) => {
17
new Promise((res) => {
18
console.log('before');
19
assert(true);
20
console.log('after');
21
22
res(null);
23
})
24
.then(() => done())
25
.catch((err) => done(err));
26
});
27
});
28
test result:
JavaScript
1
23
23
1
test
2
before
3
1) testcase
4
before
5
after
6
✓ testcase - 2
7
8
9
1 passing (9ms)
10
1 failing
11
12
1) test
13
testcase:
14
AssertionError: Unspecified AssertionError
15
at /Users/dulin/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/66461468/index.test.ts:7:7
16
at new Promise (<anonymous>)
17
at Context.<anonymous> (src/stackoverflow/66461468/index.test.ts:5:5)
18
at processImmediate (internal/timers.js:439:21)
19
20
21
22
npm ERR! Test failed. See above for more details.
23