我正在尝试使用 @testing-library/react-hooks
测试自定义 Hook 但我无法测试依赖关系。让我们使用 useEffect
举个例子:
import { renderHook } from '@testing-library/react-hooks';
import { useEffect } from 'react';
test('test dependency', () => {
const callback = jest.fn((value: number) => {});
let currentValue = 5;
renderHook(() => useEffect(() => callback(currentValue), [currentValue]));
expect(callback).toBeCalledTimes(1);
expect(callback).toHaveBeenLastCalledWith(5);
renderHook(() => useEffect(() => callback(currentValue), [currentValue]));
expect(callback).toBeCalledTimes(1); // error here: called 2 times in reality
expect(callback).toHaveBeenLastCalledWith(5);
currentValue = 6;
renderHook(() => useEffect(() => callback(currentValue), [currentValue]));
expect(callback).toBeCalledTimes(2);
expect(callback).toHaveBeenLastCalledWith(6);
});
预期行为:useEffect
不会使用相同的依赖列表再次调用。实际行为:
useEffect
每次都被调用,可能是因为上下文被破坏并在weeb renderHook
之间重新创建.我还尝试将渲染方法放入这样的常量中:
const myHook = () => useEffect(() => callback(currentValue), [currentValue]);
renderHook(myHook);
但没有运气。有什么方法可以测试依赖列表是否正常工作?
最佳答案
预计renderHook
每次调用都会挂载,相反的做法会阻止它与不相关的钩子(Hook)一起使用。
与 React 测试库一样 render
, the result允许控制渲染实例,这包括 unmount
和 rerender
.
附加值,如 currentValue
可以像在组件中一样传递,即 props 对象。
所以它可能应该是:
let { rerender, unmount } = renderHook(
({ val }) => useEffect(() => callback(val), [val]),
{ initialProps: { val: 5 } }
);
expect(callback).toBeCalledTimes(1);
expect(callback).toHaveBeenLastCalledWith(5);
rerender({ val: 5 });
expect(callback).toBeCalledTimes(1);
expect(callback).toHaveBeenLastCalledWith(5);
rerender({ val: 6 });
expect(callback).toBeCalledTimes(2);
expect(callback).toHaveBeenLastCalledWith(6);
请注意,代码测试了 React 自己的 useEffect
所以它没有实际用途。
关于reactjs - 如何测试对 React 钩子(Hook)的依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64222700/