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粉2741615932023-09-23 10:57:40
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