In some integration tests in my Node.js, I use pg to perform some cleanup of the Postgres tests database after the test have run. I call this in the afterAll():
afterAll(() => {
const { Pool } = require('pg')
const connectionString = 'postgresql://' + PG_USER + ':' + PASSWORD + '@' + HOST + ':' + PG_PORT + '/' + DATABASE_TEST;
const pool = new Pool({
connectionString,
})
pool.query('TRUNCATE someTable RESTART IDENTITY CASCADE;', (err, res) => {
pool.end();
})
When I run Jest tests in my Node.js app, I'm getting the error:
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.
When I add --detectOpenHandles to my npm test script in package.json, I then get the following:
Jest has detected the following 1 open handle potentially keeping Jest from exiting:
● TCPWRAP
> 259 | pool.query('TRUNCATE someTable RESTART IDENTITY CASCADE;', (err, res) => {
| ^
260 |
261 | pool.end();
262 | })
If I move the connection to the database into a separate file (outside of the __tests__ folder), the Jest tests still don't exit (with the same error).
If I use a pg Client and do this, I get a similar issue with the client.connect()
client.connect()
client
.query('TRUNCATE someTable RESTART IDENTITY CASCADE;')
.then(() => client.end())
Can anyone explain what's actually going on here? Does Jest try to close after the final test, but the operation in afterAll() is preventing this? What do I need to do to allow the tests to exit? None of the solutions in other similar SO questions apply to my case.
Update
I tried the suggestion by @Estus Flask, but it still doesn't fix the issue. Using the following (which passes done as the callback function, so that the afterAll won't complete until done() is called (which I call when the pool.end() promise resolves):
afterAll( done => {
const { Pool } = require('pg')
const connectionString = 'postgresql://' + PG_USER + ':' + PASSWORD + '@' + HOST + ':' + PG_PORT + '/' + DATABASE_TEST;
const pool = new Pool({
connectionString,
})
pool.query('TRUNCATE someTable RESTART IDENTITY CASCADE;', (err, res) => {
pool.end().then(done());
})
})
});