我尝试设置自定义Jest测试环境,在测试开始运行之前我可以连接到数据库一次,并在所有测试完成后断开连接。我想避免在每个测试文件中的beforeAll()
和afterAll()
钩子中使用辅助函数。以下是我当前设置的样子。当我运行测试时,由于readyState为0表示断开连接,因此失败。我错过了什么?
jest.config.js
module.exports = {
testEnvironment: './mongo-environment'
}
蒙戈-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)
})
})