问题描述
我正在测试函数 parent()
,该函数调用返回的函数 slomo()
.我想检查 .then()
中的代码是否正在执行.
I am testing a function parent()
that calls a function slomo()
that returns a promise. I want to check that the code within the .then()
is being executed.
function slomo() {
return new Promise(function (resolve, reject) {
resolve('good')
reject('bad')
})
}
child = jest.fn()
function parent() {
slomo()
.then((result) => {
child()
})
}
// TEST
it('runs child', () => {
parent()
expect(child).toHaveBeenCalledTimes(1)
})
结果是:
我已确认通过 console.log
调用了子功能,但是在测试完成后 AFTER 已记录该子功能.
我尝试通过并在测试内调用 done
,但这不能解决问题.
也许上面的代码是反模式,需要重写才能进行测试?
I have confirmed the child function IS being called via console.log
, but it is being logged AFTER the test has completed.
I have tried passing and calling done
inside the test but that did not correct the issue.
Maybe the above code is an anti-pattern and needs to be rewritten so that it can be tested?
非常感谢您能给我的帮助!
Any help you can give me is greatly appreciated!
推荐答案
您正确地发现了问题的根本原因,即测试早于异步代码完成,因此测试应正确跟踪异步.但是似乎您丢失了承诺b/c,但您没有将其退还,所以:
You correctly found the root case of the problem, that test finishes earlier then async code, so test should track async correctly. But seems to you lost the promise b/c you don't return it, so:
function parent() {
return slomo() // <<<--- add return
.then((result) => {
child()
})
}
接下来,您只需添加完成
:
it('runs child', (done) => { // <<<< --- add done
parent().then(() => {
expect(child).toHaveBeenCalledTimes(1)
done(); // <<<< -- done should be called after all
})
});
或只返回承诺:
it('runs child', () => {
return parent().then(() => { // <<<--- return
expect(child).toHaveBeenCalledTimes(1);
})
})
希望有帮助.
这篇关于如何测试嵌入式异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!