Jest:Mongoose和koa服务器没有关闭连接

时间:2018-04-02 11:07:42

标签: javascript node.js mongoose koa supertest

当调用afterAll函数后,我调用close服务器和mongoose的方法,在控制台输出中Mongodb连接关闭,但是当我看到连接数时我mongo cli它一样,测试结束但成功但是节点没有关闭脚本可能有什么问题?

之前:enter image description here

enter image description here

关闭mongoose连接后

enter image description here

虽然我没有暂停执行ctrl-c

的脚本

我有猫鼬连接:

import mongoose from 'mongoose'
import { MONGO_URI } from '../config'

mongoose.Promise = Promise

export default {
  connect () {
    return new Promise((resolve, reject) => {
      mongoose.connect(MONGO_URI)

      const connection = mongoose.connection

      connection.on('error', reject)
      connection.on('open', (data) => {
        resolve(connection)
      })
      connection.on('close', () => {
        console.log('Mongodb connection closed')
      })
    })
  }
}

应用程式:

import Koa from 'koa'

const app = new Koa()

...

export default app

测试:

import r from 'supertest'
import mongodb from 'db/mongodb'
import app from 'app'
import CategoryModel from 'modules/categories/models/category'

describe('Categories routes', () => {
  let mongoConnection
  let server

  beforeAll(async () => {
    mongoConnection = await mongodb.connect()
    server = await app.listen()
  })

  afterAll(async () => {
    await mongoConnection.close()
    await server.close()
  })

  afterEach(async () => {
    await mongoConnection.dropDatabase()
  })

  describe('/GET', () => {
    it('records exist', async () => {
      const { body } = await r(server).get('/api/categories')

      expect(body).toHaveProperty('data')
      expect(body.data).toHaveLength(2)
    })
  })
})

0 个答案:

没有答案