gpt4 book ai didi

javascript - 你如何模拟 useDebounce ?

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

所有模拟尝试都会产生错误:

import useDebounce from 'use-debounce'
jest.mock('use-debounce')

TypeError: (0 , _useDebounce.useDebounce) is not a function or its return value is not iterable

尝试仅针对该模拟也失败:

jest.mock('use-debounce',() => {
return {
useDebounce: jest.fn(value => [value])
}
})

也给出了同样的错误。使用模拟计时器也不起作用。

最佳答案

编辑:这是因为您混淆了导入。 According to npm它确实被用作命名导入

import { useDebounce } from 'use-debounce';

所以,只要你像☝️那样导入它,然后你就可以按照你说的方式 mock 它:

jest.mock('use-debounce',() => {
return {
useDebounce: jest.fn(value => [value])
}
})

首选 fake timers

请记住,我强烈鼓励使用模拟的替代方法,即使用 fake timers .

import { ComponentThatUsesUseDebounce } from './something';


jest.useFakeTimers(); // <- must appear in your test file


describe('...',() => {

it('should call a debounce function',() => {
const thing = render(<ComponentThatUsesUseDebounce/>);
fireEvent.click(thing.something);
jest.runAllTimers(); // or runOnlyPendingTimers() or advanceTimersByTime(n)

expect(something).toHaveBeenCalled();
});

});

原始答案

useDebounce 不是命名导出,它是默认 导出:

Mocking esmodules

jest.mock('use-debounce',() => {
return {
__esModule: true,
default: jest.fn(value => [value])
}
})

关于javascript - 你如何模拟 useDebounce ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67511217/

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