I'm using supertest
with jest
to test a small KOA API that uses mongoose
. Here is the test code:
const app = require('./app')
const request = require('supertest')
test('respond with json', async () => {
return request(app.callback())
.get('myurl')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
})
If I run jest
with npm test
I got this error (tests passes but Jest does not exit successfuly):
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.
According to this answer, I need to close the mongoose
connection.
So I tried this:
const app = require('./app')
const request = require('supertest')
const mongoose = require('mongoose')
test('respond with json', async () => {
return request(app.callback())
.get('myurl')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
})
afterAll(() => mongoose.disconnect())
... but it does not seems to work, because I have a new error:
console.error node_modules/jest-jasmine2/build/jasmine/Env.js:157
Unhandled error
console.error node_modules/jest-jasmine2/build/jasmine/Env.js:158
Error [ERR_UNHANDLED_ERROR]: Unhandled error. (MongoError: topology was destroyed)
at Function.emit (events.js:171:17)
at done (/x/node_modules/mongoose/lib/model.js:1076:13)
at /x/node_modules/mongoose/lib/model.js:1118:16
at /x/node_modules/mongoose/lib/utils.js:447:16
at err (/x/node_modules/mongodb/lib/utils.js:415:14)
at session.endSession (/x/node_modules/mongodb/lib/utils.js:399:27)
at ClientSession.endSession (/x/node_modules/mongodb-core/lib/sessions.js:72:41)
at executeCallback (/x/node_modules/mongodb/lib/utils.js:397:17)
at err (/x/node_modules/mongodb/lib/utils.js:415:14)
at executeCallback (/x/node_modules/mongodb/lib/utils.js:404:25)
...
And I still have this message:
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 don't understand why I have these errors and how I can avoid it.
I can edit my answer if required!