renderHook中waitForNextUpdate的替代方案
P粉198670603
P粉198670603 2023-09-22 11:40:09
0
1
993

我已經更新了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粉198670603
P粉198670603

全部回覆(1)
P粉274161593

在較新版本的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確保元件更新被正確處理
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板