【问题标题】:Jest not closing because of Mongoose.model因为 Mongoose.model 而开玩笑没有关闭
【发布时间】:2018-12-10 14:55:14
【问题描述】:

我正在尝试用 jest 创建我的第一个测试。

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()
  })
})

user_model.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

当我运行测试时,使用--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)

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

【问题讨论】:

  • 你解决了吗?

标签: node.js unit-testing testing mongoose jestjs


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    使用安装文件和setupFilesAfterEnv

    Jest 可以调用“setup.js”文件来运行一些beforeAllafterAll 函数。由于 Mongoose 的持续连接使 Jest 保持打开状态,我们将使用 afterAll 挂钩关闭它们。

    解决方案

    1. 在您的jest.config.js 中,添加以下行:
    setupFilesAfterEnv: [
      '<rootDir>/tests/setup.js', // <- Feel free to place this file wherever it's convinient
    ],
    
    
    1. 使用以下代码创建一个setup.js 文件:
    import { getMongoDBInstance } from '../src/bin/server.ts';
    
    afterAll(async () => {
      const mongoDB = getMongoDBInstance();
    
      await mongoDB.connection.close();
    });
    

    这里,getMongoDBInstance 是一个函数,它返回我在服务器启动时实例化的 Mongoose 实例。

    let mongoDB;
    
    async function initServer() {
      ...
      await mongoose.connect(uristring, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      });
    
      mongoDB = mongoose;
      ...
    }
    
    export const getMongoDBInstance = () => mongoDB;
    
    

    现在在所有测试运行之后,Jest 将调用此函数并关闭所有 MongoDB 连接!您可以按照相同的方法解决与 knex 或任何其他节点 ORM 的开放连接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-18
      • 2019-07-31
      • 2021-03-23
      • 2018-11-24
      • 2017-11-28
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      相关资源
      最近更新 更多