【发布时间】:2020-09-01 18:41:28
【问题描述】:
我开始为我的 NestJS API 编写 e2e 测试,我想使用一个测试数据库。 我在测试模块中导入了 MongooseModule,它正确地使用了预期的测试数据库。
然后,我想在测试之前清除集合并重新插入固定装置。 为此,我想使用 NestJS 使用的 Mongoose 实例。 但是我没有成功,最后创建了第二个连接(在 beforeAll 钩子中)
我还没有找到任何解决方案来避免这种情况。
代码如下:
describe('Color', () => {
let app: INestApplication
let db: Connection
beforeAll(async () => {
db = await mongoose.createConnection(process.env.MONGO_TEST_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
db.model('Color', ColorSchema)
})
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [
MongooseModule.forRoot(process.env.MONGO_TEST_URL, {
useCreateIndex: true,
useFindAndModify: false
}),
AppModule
]
}).compile()
await db.model('Color').deleteMany({})
await db.model('Color').insertMany(ColorFixtures)
app = moduleFixture.createNestApplication()
await app.init()
})
afterAll(async () => {
await db.close()
await app.close()
})
it('/ (GET)', () => {
return request(app.getHttpServer())
.post('/graphql')
.send({
operationName: 'findAll',
query: 'query findAll { colors { id name } }',
variables: {}
})
.expect(200)
.expect({})
})
})
有什么想法吗?
【问题讨论】: