Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close server and db connect after tests

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)
    })
  })
})
like image 243
Khotey Vitaliy Avatar asked Sep 20 '17 17:09

Khotey Vitaliy


1 Answers

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();
});
like image 60
internetross Avatar answered Nov 02 '22 09:11

internetross