Sam*_*u R 3 mongoose mongodb jestjs
我正在尝试通过使用迁移功能来实现数据库填充。代码运行完美,它将所有数据保存到数据库中,但是功能测试失败,现在我想知道为什么?
对于此特定测试,我收到“超出 5000 毫秒超时”错误。我已经为这个应用程序编写了 166 个测试,所有测试都通过了。
这是我要测试的功能:
const doMigration = async ({ model, data }) => {
await model.collection.insertMany(data)
}
Run Code Online (Sandbox Code Playgroud)
这是测试:
const { Amodel } = require('../../../models/Amodel')
const { doMigration } = require('../../../database/migrations')
describe('Database Population', () => {
it ('Should populate the database using migrations', async () => {
const data = [{ name: 'A' }, { name: 'B' }]
const model = Amodel
const migration = { name: 'Amodel', model, data }
await doMigration(migration)
const countAfter = await Amodel.count()
expect(countAfter).toBe(2)
})
})
Run Code Online (Sandbox Code Playgroud)
在此测试中,我只需导入函数、模型并创建一个迁移对象,然后将其传递给函数。
我尝试了什么?
尝试仅使用 countAfter 而不使用 doMigration 函数,它仍然会生成相同的超时错误。
尝试将此测试的时间增加到 30000,失败并错误提示 mongodb 时间超过 10000 毫秒。
这是 github 存储库:https://github.com/Elvissamir/Fullrvmovies
发生了什么事,我该如何解决这个错误?
问题在于 mongodb 连接的处理方式。测试时,应用程序在启动时创建了与数据库的连接,然后笑话测试使用了该连接,这导致了一些问题。
解决方案是仅当环境设置为测试时才在启动时连接到数据库,否则连接将由每组测试处理。
在每个集合中,我添加了 beforeAll 和 afterAll 来打开和关闭与数据库的连接。
希望它可以帮助任何发现相同问题或有类似问题的人。
| 归档时间: |
|
| 查看次数: |
3791 次 |
| 最近记录: |