Full stack developer building things to make life a little easier. Huge fan of JavaScript, React, Node.js, and testing my code. • twitter.com/ZakLaughton • zaklaughton.dev
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 renderconst{findByText}=render(<MyComponent/>);// Use the findBy function to wait up to 1000ms to find// the element that should appear after the fetchconstelementImLookingFor=awaitfindByText(/some text/)// Assert that it's in the rendered elementexpect(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.
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:
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:
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!
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:
Thanks again,
Mark