I ran across to this error while I was writing test code with Jest, being stunned by repeated long error messages in console ending with this test failure report.
While there might be several other reasons why this error might occur, in my case it was very simple - mishandled async error.
All you have to do is to check if you have any Promise not handled asynchronously.
Error reproduced
// user.controller.spec.ts
it('should throw Error if invalid user type.', () => {
const result = controller.signup(signupForm, { type: 'invalid' });
expect(result).rejects.toThrowError();
});
// user.controller.ts
async signup(form, query) {
if (is<UserType>(query.type)) {
throw new BadRequestException();
}
return true;
}
method signup
throws an error asynchronously, and this is not handled in test code. For some reason, Jest considers test has gone wrong and retries it again in its other workers.
This error, can be suppressed if --maxWorker flag is set to 1 when running the test. However, this does not solve the problem from the ground, and one way to deal this issue is looking at async handling.
Solution
In the case above, only two words are added.
aysnc
and await
to where it should be.
it('should throw Error if invalid user type.', async () => {
const result = controller.signup(signupForm, { type: 'invalid' });
await expect(result).rejects.toThrowError();
});
P.S.
However, it's quite weird as this error does not always appear in similar situations. Seems like it is affected by other test cases.
Top comments (0)