问题描述
我正在编写一个小型测试,以检查是否某些代码确实写入了我的mongo数据库.我收到来自Jest的以下错误消息,该代码确实有效.
I am writing a small test for checking if some code does write into my mongo database. I am receiving the following error message from Jest, the code does indeed work.
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.
对于我的测试,我只调用函数并期望一个对象属性,该属性指定操作是否成功
For my test I am only calling the function and expecting a object property which specifies if the operation was succesfull
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文件并将某些参数保存到数据库中:
The original function parses a JSON file and saves certain pars into the database :
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 }
}
}
推荐答案
您应该使用Promises来确保仅在执行loadData
函数之后才调用expect()
.笑话异步文档
You should use Promises to make sure that expect()
is called only after loadData
function is executed.Jest Async doc
在下面修改了您的代码以使用promises
Modified your code below to use 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 })
})
})
这篇关于在5000毫秒的超时时间内未调用异步回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!