因为 Mongoose.model 开玩笑没有关闭

Har*_*nch 5 testing unit-testing mongoose node.js jestjs

我正在尝试开玩笑地创建我的第一个测试。

user_model_test.js

const mongoose = require('mongoose')
const User = require('../user_model')


describe('user model tests', () => {
  beforeAll( async () => {
    await mongoose.connect('mongodb://localhost/supertest21')
  })
  afterAll( async () => { 
    await mongoose.connection.close()
  })

  it("has a module", () => {
    expect(User).toBeDefined()
  })
})
Run Code Online (Sandbox Code Playgroud)

用户模型.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const userSchema = new Schema({
  username: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  }
})

const User = mongoose.model('User', userSchema, 'user')

module.exports = User
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,运行时出现--detectOpenHandles此错误:

Jest has detected the following 1 open handle potentially keeping Jest from exiting:

  ?  PROMISE

      17 | })
      18 |
    > 19 | const User = mongoose.model('User', userSchema, 'user')
         |                       ^
      20 |
      21 | module.exports = User

      at Function.init (node_modules/mongoose/lib/model.js:970:16)
      at Mongoose.Object.<anonymous>.Mongoose.model (node_modules/mongoose/lib/index.js:396:11)
      at Object.<anonymous> (libs/user/user_model.js:19:23)
      at Object.<anonymous> (libs/user/__tests__/user_model_test.js:3:14)
Run Code Online (Sandbox Code Playgroud)

我知道这与 mongoose.model 初始化有关。当我将第 4 个参数传递给 mongoose.model 以跳过初始化时,promise 错误不会出现但测试永远不会关闭并且不再显示错误。有任何想法吗?

小智 -4

尝试更改await mongoose.connection.close()await mongoose.disconnect();. 为我工作。