我有下一个去抖动功能:
export const debounce = (func: (...args: string[]) => void, wait: number) => {
let timeout: NodeJS.Timeout;
function executedFunction(...args: string[]) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
}
return executedFunction;
};
我的范围是测试这个功能:
jest.useFakeTimers();
describe('test debounce function', () => {
test('execute just once', () => {
const func = jest.fn();
const debouncedFunc:any = debounce(func, 500);
// Execute for the first time
debouncedFunc();
// Move on the timer
jest.advanceTimersByTime(250);
// try to execute a 2nd time
debouncedFunc();
// Fast-forward time
jest.runAllTimers();
expect(func).toBeCalledTimes(1);
});
})
尝试以上述方式进行测试时,我得到 TypeError: debouncedFunc is not a function
,但我不明白为什么。有人可以帮忙测试上述功能吗?
答案 0 :(得分:1)
您的去抖动功能有错误。最后一句话:
return executedFunction();
...已经安排了函数的执行——它不应该——并且它返回undefined
。它应该返回函数,而不是执行它:
return executedFunction;