搜索

首页  >  问答  >  正文

renderHook中waitForNextUpdate的替代方案

我已经更新了Testing-library,但我在这种情况下很难找到waitForNextUpdate的替代方法(在react-testing-library v13中不再可用https://github.com/testing-library/react-testing-library/issues/1101)。我尝试使用rerender(),但似乎没有帮助:

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粉198670603P粉198670603435 天前954

全部回复(1)我来回复

  • P粉274161593

    P粉2741615932023-09-23 10:57:40

    在较新版本的React Testing Library中,waitForNextUpdate()不再可用。相反,您可以使用act函数来处理异步更新,该函数也由@testing-library/react-hooks提供。 尝试以下代码:

    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: { ... },
      });
    });
    使用act确保组件更新被正确处理

    回复
    0
  • 取消回复