Alternatif untuk waitForNextUpdate dalam renderHook
P粉198670603
P粉198670603 2023-09-22 11:40:09
0
1
944

Saya telah mengemas kini perpustakaan Pengujian tetapi saya sukar mencarinya dalam kes ini waitForNextUpdate的替代方法(在react-testing-library v13中不再可用https://github.com/testing-library/react-testing-library/issues/1101)。我尝试使用rerender() tetapi ia nampaknya tidak membantu:

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

membalas semua(1)
P粉274161593

Dalam versi Perpustakaan Pengujian React yang lebih baharu, waitForNextUpdate()不再可用。相反,您可以使用act函数来处理异步更新,该函数也由@testing-library/react-hooks tersedia. Cuba kod berikut:

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: { ... },
  });
});
Gunakan act untuk memastikan kemas kini komponen dikendalikan dengan betul
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan