7

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: 'test@test.com',
      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: 'test@test.com',
      }

      r
        .post(`/api/auth/signup`)
        .send(userData)
        .expect(400)
        .expect({
          errors: {
            password: 'Password required',
          },
        })
        .end(done)
    })
  })
})
Khotey Vitaliy
  • 509
  • 1
  • 6
  • 18

1 Answers1

4

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();
});
internetross
  • 143
  • 2
  • 10