reactjs - 如何触发事件 React 测试库

标签 reactjs jestjs react-hooks react-testing-library react-hooks-testing-library

我在一个钩子(Hook)中有一些代码来检测浏览器是否在线/离线:

export function useConnectivity() {
  const [isOnline, setNetwork] = useState(window.navigator.onLine);
  const updateNetwork = () => {
    setNetwork(window.navigator.onLine);
  };
  useEffect(() => {
    window.addEventListener('offline', updateNetwork);
    window.addEventListener('online', updateNetwork);
    return () => {
      window.removeEventListener('offline', updateNetwork);
      window.removeEventListener('online', updateNetwork);
    };
  });
  return isOnline;
}

我有这个基本测试:

test('hook should detect offline state', () => {
  let internetState = jest.spyOn(window.navigator, 'onLine', 'get');
  internetState.mockReturnValue(false);

  const { result } = renderHook(() => useConnectivity());
  expect(result.current.valueOf()).toBe(false);
});

但是,我想运行一个测试,看看它是否在 offline 事件被触发时返回正确的值,而不仅仅是在渲染返回值的模拟之后。解决这个问题的最佳方法是什么?到目前为止我得到的是:

test('hook should detect offline state then online state', async () => {
  const { result, waitForNextUpdate } = renderHook(() => useConnectivity());

  act(() => {
    const goOffline = new window.Event('offline');
    window.dispatchEvent(goOffline);
  });

  await waitForNextUpdate();
  
  expect(result.current).toBe(false);
});

最佳答案

我不确定“最佳”,但这是一种方法:在测试中途更改模拟响应,并调整一些异步代码:

test('hook should detect online state then offline state', async () => {
  const onLineSpy = jest.spyOn(window.navigator, 'onLine', 'get');

  // Pretend we're initially online:
  onLineSpy.mockReturnValue(true);

  const { result, waitForNextUpdate } = renderHook(() => useConnectivity());

  await act(async () => {
    const goOffline = new window.Event('offline');

    // Pretend we're offline:
    onLineSpy.mockReturnValue(false);

    window.dispatchEvent(goOffline);

    await waitForNextUpdate();
  });

  expect(result.current).toBe(false);
});

关于reactjs - 如何触发事件 React 测试库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64308913/

相关文章:

javascript - React-Redux 应用程序 : How to make that in this field on my page only some part of data displayed?

reactjs - Webpack:在多个条目文件中发现重复内容

coffeescript - ReactJS 从子进程更新状态

javascript - React Native 在获取数据完成后从 Promise 中获取值

reactjs - Visual Studio 2019 测试资源管理器中的 Jest 单元测试

reactjs - 将 HOC 与 React Hooks 一起使用仍然有意义吗?

javascript - Jest - 一个函数模拟多个测试文件的文件

node.js - 用 Electron 而不是 Node 运行 Jest

javascript - 如何在Reactjs中保存输入字段?

javascript - 如何在循环中有条件地调用 RTK 查询钩子(Hook),尽管我们不能在 useEffect 中使用它