我正在componentDidMount内部使用debounce函数,如下所示:
...
if (setNavigationSections) {
setNavigationSections(filteredFieldGroups);
window.addEventListener('scroll', debounce(50, this.getNavigationActive));
}
...
我对此有一个单元测试:
it('should add a scroll handler on mount', () => {
// const d = instance.getNavigationActive;
// const deb = debounce(50, d);
// expect(window.addEventListener).toHaveBeenCalledWith('scroll', deb);
expect(window.addEventListener).toHaveBeenCalledWith('scroll', instance.getNavigationActive);
});
我已经尝试了一种可能的解决方案,例如注释代码中的解决方案,但仍然失败。
我是否可能需要以其他方式模拟去抖功能?
答案 0 :(得分:1)
在实际代码中,addEventListener
和scroll
调用了debounce
方法,但是在测试时,我们试图用错误的第二个参数进行测试。
您可以使用jest.mock模拟去抖动方法,如下所示:
import { debounce } from 'throttle-debounce';
jest.mock('throttle-debounce', () => {
return {
debounce: jest.fn().mockReturnValue('mockDebouncedValue')
}
})
describe('your test description', () => {
it('should add a scroll handler on mount', () => {
// here debounce points to the mocked function
// since addEventListener is called with the value which is returned after calling debounce, so we check here.
expect(window.addEventListener).toHaveBeenCalledWith('scroll','mockDebouncedValue');
expect(debounce).toBeCalled();
});
});