我正在尝试 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 错误不会出现,但测试永远不会关闭并且不会显示更多错误。有什么想法吗?
最佳答案
使用安装文件和setupFilesAfterEnv
Jest 可以调用“setup.js”文件来运行一些beforeAll
和afterAll
函数。由于正在进行的 Mongoose 连接使 Jest 保持打开状态,我们将使用 afterAll
Hook 关闭它们。
解决方案
- 在您的
jest.config.js
中,添加以下行:
setupFilesAfterEnv: [
'<rootDir>/tests/setup.js', // <- Feel free to place this file wherever it's convinient
],
- 使用以下代码创建一个
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 或任何其他 Node ORM 的打开连接。
关于node.js - 由于 Mongoose.model,开 Jest 没有关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51135158/