Javascript 去盎司功能单元测试
我在componentDidMount中使用的函数如下:Javascript 去盎司功能单元测试,javascript,unit-testing,Javascript,Unit Testing,我在componentDidMount中使用的函数如下: ... if (setNavigationSections) { setNavigationSections(filteredFieldGroups); window.addEventListener('scroll', debounce(50, this.getNavigationActive)); } ... it('should add a scroll
...
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);
});
我对它进行了单元测试,如下所示:
...
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);
});
单元测试失败,消息为:
我已经尝试了一个可能的解决方案,比如注释代码中的解决方案,但仍然失败
我是否需要以另一种方式模拟去盎司函数?在实际代码中,使用
滚动和去盎司调用addEventListener
方法,但在测试时,我们尝试使用错误的第二个参数进行测试。
您可以使用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();
});
});