我正在尝试使用setTimeout进行简单的异步/等待测试,但是运行它时却什么也没发生:
const testing = async () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('result');
}, 500);
});
}
jest.useFakeTimers()
it('tests async await', async () => {
const r = await testing();
expect(r).toBe('result');
jest.runAllTimers();
});
我可以像Jasmine一样使用真正的setTimeout,但在Jest中看来您必须使用伪造的。所以我确实包括了jest.useFakeTimers()
和jest.runAllTimers()
,但这并不能解决问题。
测试被卡住,无法完成。知道可能是什么问题吗?
答案 0 :(得分:1)
尝试以下操作:
it('tests async await', async () => {
jest.useFakeTimers();
testing = async () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('result');
}, 500);
});
};
const asyncResult = testing();
jest.runAllTimers();
const r = await asyncResult;
expect(r).toBe('result');
});