gpt4 book ai didi

javascript - 去抖动功能单元测试

转载 作者:行者123 更新时间:2023-12-02 23:41:38 25 4
gpt4 key购买 nike

我正在使用 debounce componentDidMount 内部的函数如下所示:

    ...
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);
});

单元测试失败,消息为: enter image description here

我尝试了一种可能的解决方案,例如注释代码中的解决方案,但仍然失败。

我是否需要以另一种方式模拟去抖函数?

最佳答案

在实际代码中,使用 scrolldebounce 调用 addEventListener 方法,但在测试时我们尝试使用错误的第二个参数进行测试。您可以使用 jest.mock 来模拟 debounce 方法,如下所示:

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();
});
});

关于javascript - 去抖动功能单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56044253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com