skip to Main Content

I’ve updated Testing-library and I’m struggling to find and alternative to waitForNextUpdate in this case (it is no longer available in react-testing-library v13 https://github.com/testing-library/react-testing-library/issues/1101). I’ve tried to use rerender() it seems it is not helping:

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

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

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

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

    await waitForNextUpdate(); // <--- how to wait for the hook to be executed? 

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

2

Answers


  1. In newer versions of React Testing Library, waitForNextUpdate() is no longer available. Instead, you can handle the asynchronous updates using the act function, which is also provided by @testing-library/react-hooks.

    try this 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,
     });
    
     // Wait for the asynchronous update to finish using act and waitFor
     await act(async () => {
     await waitFor(() => {
        return !result.current.loading;
     });
     });
    
     expect(result.current).toMatchObject({
       loading: false,
       stats: { ... },
    });
    });
    

    Using act ensures that the component updates are handled correctly

    Login or Signup to reply.
  2. I can find a related Github topic here and the answer of eps1lon, member of testing librariry, was:

    the next update isn’t necessarily relevant to the user. We want to discourage testing these implementation in Testing Library. waitFor has all the tools you need.

    waitFor

    When in need to wait for any period of time you can use waitFor, to wait for your expectations to pass. Returning a falsy condition is not sufficient to trigger a retry, the callback must throw an error in order to retry the condition.

    docs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search