Alternative to waitForNextUpdate in renderHook
P粉198670603
P粉198670603 2023-09-22 11:40:09
0
1
943

I have updated Testing-library but I am having trouble finding an alternative to waitForNextUpdate in this case (no longer available in react-testing-library v13 https ://github.com/testing-library/react-testing-library/issues/1101). I tried using rerender() but that doesn't seem to help:

const mockGetSummary = getSummary as jest.MockedFunction<any>;

test('hook的初始状态', async () => {
    mockGetSummary.mockImplementation(() => ({
      setOptions: () => ({
        call: () => Promise.resolve({mycustomObject}),
      }),
    }));

    const { result, rerender } = renderHook(() => useHomePageData());

    expect(result.current).toMatchObject({
      loading: true,
      stats: null
    });

    await waitForNextUpdate(); // <--- 如何等待hook执行完毕?

    expect(result.current).toMatchObject({
      loading: false,
      stats: {...}
    });
  });

P粉198670603
P粉198670603

reply all(1)
P粉274161593

In newer versions of React Testing Library, waitForNextUpdate() is no longer available. Instead, you can use the act function to handle asynchronous updates, also provided by @testing-library/react-hooks. Try the following code:

import { renderHook, act } from '@testing-library/react-hooks';
import { waitFor } from '@testing-library/react';

const mockGetSummary = getSummary as jest.MockedFunction<any>;

test('initial state of hook', async () => {
  mockGetSummary.mockImplementation(() => ({
    setOptions: () => ({
      call: () => Promise.resolve({ mycustomObject }),
    }),
  }));

  const { result } = renderHook(() => useHomePageData());

  expect(result.current).toMatchObject({
    loading: true,
    stats: null,
  });

  // 使用act和waitFor等待异步更新完成
  await act(async () => {
    await waitFor(() => {
      return !result.current.loading;
    });
  });

  expect(result.current).toMatchObject({
    loading: false,
    stats: { ... },
  });
});
Use act to ensure component updates are handled correctly
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template