我有一个 rateLimit
函数(它只是 this code 的修改版本):
function rateLimit(func, wait) {
var timeout;
return function () {
var context = this;
var args = arguments;
var later = function () {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
此功能在我的应用程序中运行良好,所以我相当确定实现是好的。但是,以下测试失败:
jest.useFakeTimers();
test('rateLimit', () => {
const action = jest.fn();
const doAction = rateLimit(action, 100);
doAction(); // This should increment the call count
doAction(); // This shouldn't, because 100ms hasn't elapsed yet
jest.advanceTimersByTime(101);
doAction(); // This should increment the count again
expect(action).toHaveBeenCalledTimes(2);
});
出现错误:
Expected mock function to have been called two times, but it was called one time.
Here is a runnable version of this code on repl.it .
我在这里做错了什么?
最佳答案
您的速率限制器使用 trailing
方法,当新调用进入时,它会取消当前正在进行的任何调用...直到等待时间到期,此时函数被调用。
您只需要再次提前计时器以便再次调用该函数:
jest.useFakeTimers();
test('rateLimit', () => {
const action = jest.fn();
const doAction = rateLimit(action, 100);
doAction(); // This should increment the call count
doAction(); // This shouldn't, because 100ms hasn't elapsed yet
jest.advanceTimersByTime(101);
doAction(); // This should increment the count again
jest.advanceTimersByTime(101); // <= advance the timers again
expect(action).toHaveBeenCalledTimes(2); // Success!
});
关于javascript - 测试使用 setTimeout 和 Jest : why is this test failing? 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55371237/