我正在尝试设置一个自定义 Jest 测试环境,我可以在测试开始运行之前连接到数据库一次,并在所有测试完成后断开连接。我想避免在每个测试文件中使用辅助函数beforeAll()和afterAll()钩子。下面是我当前设置的样子。当我运行测试时,它失败了,因为 readyState 为 0,代表已断开连接。我错过了什么?
开玩笑的配置文件
module.exports = {
testEnvironment: './mongo-environment'
}
Run Code Online (Sandbox Code Playgroud)
mongo-environment.js
const mongoose = require('mongoose')
const NodeEnvironment = require('jest-environment-node')
class MongoEnvironment extends NodeEnvironment {
constructor (config) {
super(config)
}
async setup () {
await this.setupMongo()
await super.setup()
}
async teardown () {
await this.teardownMongo()
await super.teardown()
}
runScript (script) {
return super.runScript(script)
}
setupMongo () {
return new Promise((resolve, reject) => {
mongoose.connect('mongodb://localhost/test')
.then(mongoose => {
const db = mongoose.connection
Promise
.all(Object.keys(db.collections).map(name => …Run Code Online (Sandbox Code Playgroud)