我正在尝试为 debounce 函数编写单元测试。我很难考虑。
这是代码:
function debouncer(func, wait, immediate) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
timeout = null;
if (!immediate)
func.apply(this, args);
}, wait);
if (immediate && !timeout)
func.apply(this, args);
};
}
我应该如何开始?
最佳答案
实际上,您不需要使用 Sinon 来测试去抖动。 Jest 可以在 JavaScript 代码中模拟所有计时器。
查看以下代码(它是 TypeScript,但您可以轻松地将其转换为 JavaScript):
import * as _ from 'lodash';
// Tell Jest to mock all timeout functions
jest.useFakeTimers();
describe('debounce', () => {
let func: jest.Mock;
let debouncedFunc: Function;
beforeEach(() => {
func = jest.fn();
debouncedFunc = _.debounce(func, 1000);
});
test('execute just once', () => {
for (let i = 0; i < 100; i++) {
debouncedFunc();
}
// Fast-forward time
jest.runAllTimers();
expect(func).toBeCalledTimes(1);
});
});
更多信息: Timer Mocks
关于javascript - 去抖功能的开 Jest 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52224447/