reactjs - 如何测试对 React 钩子(Hook)的依赖

标签 reactjs unit-testing jestjs react-hooks

我正在尝试使用 @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允许控制渲染实例,这包括 unmountrerender .
附加值,如 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/

相关文章:

javascript - 开 Jest mock 一个模块

javascript - 单选按钮无法返回不同状态

javascript - react 多个echarts调整大小不起作用

ios - XCode 错误 'YogaKit.modulemap' 未找到

javascript - 在 Jest 中模拟按钮点击

javascript - 如何使用 Jest 模拟 https.get

javascript - 辅助函数reactjs

javascript - 如何在单元测试中处理嵌套异步操作

python - 使用 url_for 函数为 Flask 测试客户端生成 URL

unit-testing - 在 Angular 2.1.0 Webpack 上设置单元测试代码覆盖率