【发布时间】:2018-08-26 14:29:57
【问题描述】:
我正在尝试设置一个自定义的 Jest 测试环境,在该环境中我可以在测试开始运行之前连接到数据库一次,并在所有测试完成后断开与它的连接。我想避免在每个测试文件中的 beforeAll() 和 afterAll() 挂钩中使用辅助函数。下面是我当前设置的样子。当我运行测试时,由于 readyState 为 0(代表断开连接)而失败。我错过了什么?
jest.config.js
module.exports = {
testEnvironment: './mongo-environment'
}
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 => db.dropCollection(name)))
.then(resolve)
.catch(reject)
})
.catch(reject)
})
}
teardownMongo () {
return mongoose.disconnect()
}
}
module.exports = MongoEnvironment
example.spec.js
const mongoose = require('mongoose')
describe('test', () => {
it('connection', () => {
expect(mongoose.connection.readyState).toBe(1)
})
})
【问题讨论】:
-
我一直在看同样的东西,但我认为它不会起作用。 Jest 通过重置全局环境在“沙箱”中运行每个测试套件,以防止副作用污染其他测试。我还没有找到确切的原因,但结果是你在
mongo-environment.js和example.spec.js中获得了新的Mongoose 单例。他们无法共享连接。