我有一个具有setTimeout的函数sum
,我想使用Jest测试此函数,但是我不确定如何模拟setTimeout,因此它不会延迟100000 ms组。我曾经使用过jest.useFakeTimers();
和jest.runOnlyPendingTimers();
,但没有运气来进行测试,有人可以建议我修复并提高我的模拟知识吗?
错误:
Comparing two different types of values. Expected number but received undefined.
JS
function sum(x, y) {
let start;
setTimeout(() => {
start = x + y;
return start;
}, 100000);
}
规范
describe('Utility: Sum', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
it('should return 2', () => {
const result = sum(1, 1);
expect(result).toEqual(2);
jest.runOnlyPendingTimers();
});
});
答案 0 :(得分:0)
您的函数sum
将始终返回undefined
结帐es6 promise
和how to use async in jest
将功能更改为:
async function sum(x, y) {
return new Promise(resolve =>{
setTimeout(() => {
resolve(x+y);
}, 100000)})
}