I have koa server with mongo connection and use supertest to mock server and send requests, jest as test framework.
const app = new Koa()
...
export default app.listen(PORT, (err) => {
if (err) console.log(err)
if (!IS_TEST) {
console.log(`Server running on port: ${PORT}`)
}
})
After success finish test or fail server connection steel works, how close koa server connection after test ?
Test example:
import supertest from 'supertest'
import mongoose from 'mongoose'
import server from '../../../app/server'
import User from '../../../app/models/user'
const r = supertest.agent(server.listen())
afterEach(async (done) => {
await mongoose.connection.db.dropDatabase()
done()
})
describe('Authorization', () => {
describe('POST /signup', () => {
const userData = {
email: '[email protected]',
password: 111111,
}
test('success create user', (done) => {
r
.post(`/api/auth/signup`)
.send(userData)
.expect(200)
.expect({
data: {
email: userData.email,
},
})
.end(done)
})
test('fail of user create, password required', (done) => {
const userData = {
email: '[email protected]',
}
r
.post(`/api/auth/signup`)
.send(userData)
.expect(400)
.expect({
errors: {
password: 'Password required',
},
})
.end(done)
})
})
})
You might already know but Supertest is designed to shutdown the server after calling .end()
in a test. As proof you can see the declaration for this functionality in the supertest lib code.
An alternative to calling end() is to force shutdown of both the database connection and the server in the jest afterEach()
or afterAll()
jest teardown hooks:
afterAll(() => {
mongoose.connection.close();
server.close();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With