jest: Jest did not exit one second after the test run has completed.
Iām getting this message every time iām using any libraries that depend on promises.
š Bug Report
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.
To Reproduce
I have a function that need to make a request to external api, and in the same method just save in the database without waiting for a response.
I donāt want to wait until the saving process is done, but iām forced to change the behaviour of my application to get it tested through jest., or i need to close the connection, stop the server for my code to work.
Expected behavior
Excecpted jest to stop and return to my console.
Link to repl or repo (highly encouraged)
test("it should create new order", async () => {
const response = await server.inject({
method: "POST",
url: "/api/orders",
payload: JSON.stringify({
customer: {
email: "asd@gmail.com",
phone: "20 51 75 95",
city: "Aarhus",
zip: "8000",
first_name: "jamal",
last_name: "soueidan"
},
properties: [
{
name: "custom engraving",
value: "Happy Birthday Mom!"
}
]
})
});
expect(response.statusCode).toBe(200);
});
I had to make those changes to get jest working with my api server and mongodb. https://github.com/jamalsoueidan/giv-et-tilbud/commit/d8f326b6294f88d1f12136042d4adfdc83328201
Run npx envinfo --preset jest
System:
OS: Windows 10
CPU: x64 Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz
Binaries:
npm: 6.4.1 - C:\Program Files\nodejs\npm.CMD
About this issue
- Original URL
- State: open
- Created 6 years ago
- Reactions: 32
- Comments: 51 (1 by maintainers)
Commits related to this issue
- fix: Jest did not exit after all the test ran https://github.com/jestjs/jest/issues/7287#issuecomment-476824726 — committed to gzamaury/fcc-exercisetracker by gzamaury a year ago
@lucasfcosta Every time Iāve tried using
--detectOpenHandles
in my test code in a few different applications over the years it has never provided me with any useful output. It just sits there waiting for everything to wrap up but without printing the warning that suggests to use the argument in the first place. Is there some trick to getting useful output from that argument that I am unaware of?I was getting the same error in one of my integration tests. In it, I was using a Sequelize Model to setup the database to a known state in
beforeAll
orbeforeEach
. The fix was to callclose
on the Sequelize instance connected to the Model in theafterAll
callback. Hope this helps someone else.EDITED:
And by popular request, here is effectively what Iāve done:
@Shrikant9 @AnitaMartinez
I added an example.
Try putting ādoneā inside the callback from the test function as so:
Additionally, if a connection is being kept open, this will also stop the test from completing, so closing any open connection would be recommended as well.
Is there any other way to debug?
--detectOpenHandles
is not showing any output. ThanksI was getting the same error in one of my integration tests. In it, I use
mongo
. The fix was to call close on themongoose.connection
. Hope this helps someone else.Iāve been having this problem too
I ended up using https://www.npmjs.com/package/why-is-node-running logging in beforeAll
turns out that since I was using jest.resetModules, I had to reimport the module that was using a pg connection and close it there too.
I have run into the same issue with
globalSetup
andglobalTeardown
hooks, but I canāt find any processes left unattended. I addeddone()
to the end of all the tests, and I am stopping my server during teardown.jest --runInBand --detectOpenHandles
doesnāt print anything to the console.Facing same issue tried closing sequelize connection , no luck there. Even though the issue might not be with jest but its main problem is it doesnāt display which processes are active
--detectOpenHandles
doesnāt print anything š On the top if we use --forceExit it shows message to use--detectOpenHandles
Irony šHello everyone,
Please correct me if Iām wrong but this seems like an issue which is not on Jestās side.
If you want the tests to exit even when there are external resources being held I think you should use
--forceExit
. TheforceExit
flag is specifically designed for this case and therefore is an indication that tests not exiting when itās not present is indeed an expected behaviour and not a bug.As the author mentioned, itās possible to use
--detectOpenHandles
for debugging this (and this is also mentioned in the docs btw).Given the arguments above, perhaps this issue could be closed?
I was having this problem with Knex and using global setup and teardown files on Jest.
My solution was:
Hope it helps anybody facing this kind of problem.
Had this problem with tests that used firebase. This fixed it:
For anyone running into this using
sequelize
, I had to do this:That fixed the issue.
Itās extremely disappointing that after almost 3 years there seems to have been zero effort to resolve this issue and make detection of unresolved promises any easier. Ideally node itself would make this an easier issue to debug. I donāt know how many days Iāve lost over the years trying to debug these kinds of issues.
Another possible reason I faced ā not closed Redis connection.
Iām testing Jest with mongoose and supertest, add
testEnvironment: 'node'
fixed this issue for me.If youāve multiple test files, I use global setup and teardown. For example in
jest.config.js
I defined:In
setupTests
I connect to the db and return a function which returns a promise. Similarly inteardownTests
I close the db connection and return a function which returns a promise.I had tests that were checking auto generated http server and socket.io connections. The tests were running fine on my windows machine, but failing for not exiting on my Jenkins server.
I was closing both the socket.io server and http server correctly at the end of the test, but I was not closing the clients. Once I added the cleanup for the clients, the tests exited successfully on their own on both my dev machine and CI server.
The tests would work without closing the clients if I used
--forceExit
, but at the end of the day, the real problem was improper cleanup.I also found that
--detectOpenHandles
did not produce any output.Iām also having this problem. To give some context, I am using SuperTest to do some e2e testing with
MongoMemoryServer
. My setup and teardown looks like this:Nothing out of the ordinary that would suggest that Iām following the documentation wrong. I started troubleshooting by looking at
Activity Monitor
on MacOS. It seems that there are twonode
processes that are still running whilst jest is running. However, as soon as I cancel / quit the test run, the processes also quit.Iām going to investigate further by sampling the node processes and see exactly what spawns them. I will update here with my findings.
EDIT: Related issue #1456 - it looks like itās an underlying NodeJS issue. tl;dr - add the
--forceExit
flag to your test script inpackage.json
Same here. I get no output from
--detectOpenHandles
.My jest.config.js:
My test case:
Thank you ExoMemphiz, but this callback, from where should I reachit?
Itās too deep inside the server.
I moved to Ava, it works out of the box š
After losing hope to
detechOpenHandles
and--runInBand
and their combination, I have finally managed to solve it without using them. I was having a similar problem while mockingioredis
.Now, Previously I was simply mocking (
jest.mock('../path/redis.ts')
) the Redis client file (redis.ts
) which was not working.To solve this, I have changed the way to mock the client library as per the requirement. In a helper, I was using this libraryās
hmset
function, and for the unit test of the helper I needed to mock the same.The following way of mocking has worked successfully.
You can include more functions (
hdel
,hmget
, etc) ofRedis client
as per the requirement.I hope this helps š
@BigsonLvrocha thank you for that idea re:
why-is-node-running
! In my case that tool showed me thatredux-state-sync
was being initialized in tests, which has an infinite loop to listen for Redux updates in it.--detectOpenHandles
did not output anything for me, either.āwatchAll=false in ci environment
Well well, my danish brother š
The problem is that Iām using mongoose to save something async when I call this api, and I cannot reach this code to figure out when itās finished saving the document inside mongo.
The code above actually wait for the response only, and it works, but jest complain about the mongoose save, it still in progress saving behind the scene.
I tried to disconnect mongoose, and close each connection, but it doesnāt work.
I was able to fix the issue for me in this way. š„³
I first ran my test package.json script with the additional command of
ps -e | grep node
. Like this:$ yarn run test && ps -e | grep node
So I could see which node processes are running after jest process has been finished. In my case two intellij language node processes and my microsoft teams desktop client were running. (remark: microsoft teams desktop client is running as a react native app on node js on your local machine)
To verify if my assumption is correct I closed intelliJ and my MS Teams Client and started the same script in my terminal. It worked fine. I didnt get the warning anymore.
To be double assure I startet my MS Teams Client again and startet the test script in my terminal again. I got the warning again.
Conclusion: It seems that jest is considering other node processes as application processes. This shouldnāt be the case. I hope this helps to give a hint to fix this issue š
I have a similar problem with a database connection with knex. After call connection.destroy() on afterAll(), the message has gone.
What if Iām not calling a database ? What if Iām calling an external resource of which I have no control ? How do I ācloseā ?
Hello! It seems like you havenāt yet disconnect to the database. Iāve been try
mongoose.disconnect()
inafterAll()
function and it donāt show message like that anymore.My solution wonāt work for everyone, but if you scoured the web for as long as I did trying to figure out how to close that damn handle that was left open, this might help. In my ecosystem, we are running a Parse Server as middleware with an Express server, but this could apply to anyone who needs to run a separate server with the tests but is unable to close some socket or port at the end. I believe the issue causing the dreaded āJest did not exit one secondā¦ā error for us was a result of Parseās MongoDB adapter not closing correctly.
So to get around this issue, I abstracted the server initialization completely out of the jest test suite and created a special npm script to run it in an entirely separate process.
NPM Script (package.json):
listen_on_port_5000.sh
So how does this work?
npm start
runs which is the normal command we would run to start our server with Express and Parse.start
script in the background and start a separate process running a shell script (listen_on_port_5000.sh
) to wait for the server to boot up.jest
command (all while the Express server is up and running).kill
script to close the server running on port 5000.Hi, I was getting the same error, with @dhurlburtusa tip, my code was @AnitaMartinez, Iām new in TypeScript, so Iām pretty sure this can be done in a better way:
The
dbConnection
Promise is the function that actually connects to the database instance.