I\'m using JEST for unit testing my express routes.
While running the yarn test
all my test case are getting passed, but I\'m getting an error
For me it was a different issue I was using supertest to test routes itself so I had to close the connection to the server itself.
afterAll(done => {
server.close();
done();
});
If this is not the case for you this issue might have something for you
I was having the same issue but in my package.json file i added "test": "jest --detectOpenHandles"
and ran npm test --detectOpenHandles
. I didn't get the error message this time. Maybe you can try doing that.
This worked for me
const mongoose = require('mongoose');
afterAll(async(done) => {
// Closing the DB connection allows Jest to exit successfully.
try {
await mongoose.connection.close();
done()
} catch (error) {
console.log(error);
done()
}
// done()
})
My problem was solved by this code:
beforeAll(done => {
done()
})
afterAll(done => {
// Closing the DB connection allows Jest to exit successfully.
mongoose.connection.close()
done()
})
On my side, I just separate app.listen()
from my app.
So with express, your app finish with an export.
// index.js
module.exports = app;
And just create another file to listen the port.
// server.js
const app = require('./index')
app.listen(...)
And if you import just the index (app index.js
) in your tests, it should work with no extra config.
Of course your need to adjust the start of your express app. It should use now server.js
.