如何触发事件 React 测试库

How to fire an event React Testing Library

我有一些代码,在一个钩子中,用于检测浏览器是否在线/离线:

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);
});

但是,我想 运行 测试一下 returns 触发 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);
});

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

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);
});