'Jest did not exit one second after the test run has completed
I got the following error by running the test case:
Jest did not exit one second after the test run has completed. This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with
--detectOpenHandles
to troubleshoot this issue.
I ran the test case with --ForceExit
as well as --detectOpenHandles
. But I didn't resolve this error.
Solution 1:[1]
test("Fetch Token ", async done => {
await getToken("DEV", "myApp", token => {
console.log("AuthToken: ", authToken);
expect(authToken).toBeFalsy();
});
done();
});
2 possible reason:
- Your async request
getToken
used the wrong variable, instead ofauthToken
, it'stoken
.
test("Fetch Token ", async done => {
await getToken("DEV", "myApp", token => {
console.log("AuthToken: ", token);
expect(token).toBeFalsy();
});
done();
});
- Your async request took too long to response, try to increase jest timeout
jest.setTimeout(5000)
suggestion
When you use async-await you dont need to use done.
- with async-await
test("Fetch Token ", async done => {
const authToken = await getToken("DEV", "myApp", token => {
return token;
});
console.log("AuthToken: ", authToken);
expect(authToken).toBeFalsy();
done();
});
- without async-await
test("Fetch Token ", (done) => {
getToken("DEV", "myApp", token => {
console.log("AuthToken: ", token);
expect(token).toBeFalsy();
done();
});
});
Solution 2:[2]
- Check if there is any database/redis connection not closed.
- Check if there is any timer not cleared.
Solution 3:[3]
@johnson lai's answer has a good explanation of how to ensure the asynchronous code is handled but, without seeing any of your code, it's hard to really find a solution for you.
I just spent a couple of hours dealing with this. The true problem is that if your test executes any other code that uses asynchronous code like a database connection, server, or anything similar, you need to mock it or ensure any connection is closed.
For me, I was testing an API endpoint that involved a server with NodeJS and a pg
module database connection. Despite properly handling the asynchronous code in the test, the database and server connection isn't handled in the test and remains open after the test finishes.
The solution: I mocked the pg
module and created a variable to reference the server instance. Then I did a setup and teardown with beforeEach
and afterEach
to create the server connection and close it for each test while the database was mocked.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | johnson lai |
Solution 2 | dogzhang |
Solution 3 | SherylHohman |