【发布时间】:2022-01-13 12:25:51
【问题描述】:
我的钩子是;
function useInterval() {
const ref: MutableRefObject<NodeJS.Timer | null > = useRef(null);
function set(callback: () => void, delay: number) {
ref.current = setInterval(callback, delay)
}
function clear() {
if (ref.current) {
clearInterval(ref.current)
ref.current = null
}
}
return { set, clear }
}
我的测试是;
it("set: This should be called 10 times", () => {
var callback = jest.fn();
jest.useFakeTimers()
const { result } = renderHook(() => hooks.useInterval())
act(() => {
result.current.set(() => { callback }, 100)
jest.advanceTimersByTime(1000);
})
expect(callback).toHaveBeenCalledTimes(10);
jest.useRealTimers()
})
renderHook() 和act() 来自"@testing-library/react-hooks": "^7.0.2"
我不断得到的结果是来自我的expect() 电话的0。我似乎无法弄清楚为什么。
如果我只使用setInterval() expect() 得到正确的值
it("setInterval", () => {
var callback = jest.fn();
jest.useFakeTimers()
setInterval(callback, 100)
jest.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalledTimes(10);
jest.useRealTimers()
})
我已经尝试以我能想到的所有可能的逻辑方式重新排列这些行。
我注意到无论有没有act(),我都会得到相同的结果,奇怪的是。
将timers: "fake" 或其任何变体(现代/旧版)添加到jest.config.ts 似乎没有任何效果。
显然,testing-library/react-hooks 以某种方式从jest.useFakeTimers() 中掩盖了setInterval(),但我不明白如何实现,因此无法实现我正在寻找的结果。
我的一部分认为我的钩子没有被jest.useFakeTimers() 击中,因为假计时器没有被全局替换,但我不知道该怎么做。
另外,我正在使用 Typescript。并不是说我认为这有什么不同。
【问题讨论】:
-
那行不通
标签: javascript reactjs react-hooks jestjs react-testing-library