我试图了解如何正确地对我们拥有的自定义去抖动方法进行单元测试:
// function we want to test
function debounce(func, wait = 100) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, wait);
};
}
这是失败的 Jest 单元测试:
describe('DebounceExample', () => {
beforeAll(jest.useFakeTimers);
afterAll(jest.useRealTimers);
it('should debounce', () => {
// given
const data = 'Chuck Norris is faster than you think';
const debounceTime = 5000;
const callback = jest.fn();
const debouncedFunction = debounce(callback, debounceTime);
// when
debouncedFunction(data);
// then
expect(callback).not.toHaveBeenCalled();
// when
jest.runAllTimers(); // jest.advanceTimersByTime(debounceTime);
// then
expect(callback).toHaveBeenCalled();
});
});
失败:
Error: expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0 Jest
我也在这里尝试过解决方案:https ://stackoverflow.com/a/52638566/704681没有成功
解决方法:到目前为止我能够测试它的唯一方法:
it('should denounce - workaround', (done) => {
// given
const data = 'Chuck Norris is faster than you think';
const debounceTime = 5000;
const callback = jest.fn((param) => {
// then
expect(param).toEqual(data);
done();
});
const debouncedFunction = debounce(callback, debounceTime);
// when
debouncedFunction(data);
// then
expect(callback).not.toHaveBeenCalled();
// when (see 'then' inside callback implementation)
jest.runAllTimers(); // jest.advanceTimersByTime(debounceTime);
});