DEV Community

Discussion on: The only 3 steps you need to mock an API call in Jest

Collapse
 
zaklaughton profile image
Zak Laughton • Edited

Definitely! My first recommendation is to use React Testing Library on top of Jest. React Testing Library is quickly becoming the React testing standard due to its ease of use and opinionated approach.

If you're using React Testing Library, you can use a findBy query (docs), which waits up to 1000ms for an item to appear on the page.

It would look something like this:

import * from '@testing-library/react';

it('renders the fetched data', async () => {
    // Render the component with react testing library and
    // get the findByText() function to search the render
    const { findByText } = render(<MyComponent />);

    // Use the findBy function to wait up to 1000ms to find
    // the element that should appear after the fetch
    const elementImLookingFor = await findByText(/some text/)

    // Assert that it's in the rendered element
    expect(elementImLookingFor).toBeInTheDocument();
});

If you're not using React Testing Library, you can also manually use a 1000ms setTimeout() after rendering the element to wait a moment for it to finish fetching/loading before making your assertions.

I hope this helps!

Collapse
 
markskinsley profile image
Mark Skinsley

Hi Zak,

Thanks very much for the steer; React Testing Library seems to be the way to go for this sort of thing.

I think one issue I had was some of my packages were missing / out-of-date which was throwing some errors. In the end, after updating packages and importing @testing-library/jest-dom, I used this which seems to be working:

test('Data after re-render', async () => {
     render();
     expect(screen.queryByText(/test/)).toBeNull();
     expect(await screen.findByText(/test/)).toBeInTheDocument();
});

Thanks again,
Mark