MongoError:无法创建集合用户 - 数据库正在被删除

问题描述 投票:0回答:2

我有一个 REST API,并且正在为这个项目编写 TDD。我的TDD由两部分组成:路线和服务。我选择使用Jest。我有一个用于测试的 MongoDB 数据库。每次测试完成后,我都会使用

afterAll()
方法重置数据库。在此方法中,我运行
mongoose.connection.dropDatabase
函数。

当我只运行一个测试文件时没有错误,但当我运行多个测试文件时,我收到错误。错误信息:

MongoError:无法创建集合 auth-db.users - 数据库位于 被丢弃的过程。

我与您分享示例代码:

users.route.test.ts:

https://gist.github.com/mksglu/8c4c4a3ddcb0e56782725d6457d97a0e

users.service.test.ts:

https://gist.github.com/mksglu/837202c1048687ad33b4d1dee01bd29c

当我所有的测试运行时,“

sometimes
”给出错误。我写了上面的错误信息。出现此错误的原因是重置过程仍在继续。我无法解决这个问题。如果您能提供帮助,我将不胜感激。

谢谢。

node.js mongodb unit-testing tdd jestjs
2个回答
1
投票

https://jestjs.io/docs/en/cli.html#runinband

您正在寻找的是 --runInBand 命令。这使得 jest 串行运行,而不是创建运行测试的子进程的工作池


0
投票

对于我的 e2e 测试(使用 JEST、Mongoose 和 Nestjs),使用 --runInBand 并等待 connection.db.dropDatabase() 不起作用。

在下一个测试用例中,我仍然收到 “数据库正在被删除”。

作为替代方案,我所做的不是删除数据库,而是清除所有集合:

const collections = await connection.db.listCollections().toArray(); for (const collection of collections) { const collectionInDb = connection.collection(collection.name); await collectionInDb.deleteMany({}); }
    
© www.soinside.com 2019 - 2024. All rights reserved.