我正在编写一个小型测试,以检查是否某些代码确实写入了我的mongo数据库。我收到来自Jest的以下错误消息,该代码确实有效。
Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error: Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
对于我的测试,我只调用函数并期望一个对象属性,该属性指定操作是否成功
const {clearDataBase, loadData} = require('../src/utils/dataloader')
beforeEach(clearDataBase)
test('Should write all data into database', () => {
jest.setTimeout(30000);
const result = loadData()
expect(result.status).toBe(201)
})
原始函数解析JSON文件并将某些参数保存到数据库中:
const loadData = () => {
try{
request(url, async (err, res, body) => {
const data = JSON.parse(body)
// ... Loads a lot of data, removed for this post only!
})
return { error: undefined, status: 201 }
} catch(e){
return { error: e, status: undefined }
}
}
答案 0 :(得分:0)
您应该使用Promises来确保仅在执行expect()
函数之后调用loadData
。
Jest Async doc
在下面修改您的代码以使用promises
const {clearDataBase, loadData} = require('../src/utils/dataloader')
beforeEach(clearDataBase)
test('Should write all data into database', () => {
jest.setTimeout(30000);
loadData().then(result => expect(result.status).toBe(201));
})
const loadData = () => new Promise((resolve, reject) => {
return request(url, async (err, res, body) => {
if (err) return reject({error: err})
const data = JSON.parse(body)
// ... Loads alot of data, removed for this post only!
return resolve({ error: undefined, status: 201 })
})
})