Jest 中 如何测试 setTimeout
function fun(obj) {
setTimeout(() => {
obj.a = 1;
}, 1000);
}
test('test', () => {
const obj = { a: 2 };
fun(obj);
expect(obj).toEqual({ a: 1 }); // error
});function fun(obj) {
setTimeout(() => {
obj.a = 1;
}, 1000);
}
test('test', () => {
const obj = { a: 2 };
jest.useFakeTimers(); // 开启模拟定时器
fun(obj);
jest.runAllTimers(); // 加速,让所有的定时器都执行完毕
expect(obj).toEqual({ a: 1 });
});Last updated