An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
Make a reusable test with React Testing Library
It can happen to have very similar tests across our suites. In one of my recent examples, I had to test if the UI of the footer of the pages in the application was correctly rendered, depending on a prop change.
The footer consists only of a box with inside an SVG icon and a text. But those are white when we have a dark background, and dark gray when the background is white.
The logic is already in place, and the simple test steps would be:
- render the page (component)
- get the elements to check
- check that the elements have the correct style.
The next -and boring- step would be placing this test inside each page test suite, and check for the color individually.
Instead, we can make a reusable test, like a normal function.
We can put it in some shared.js file so it can be picked up anytime.
import { screen, waitFor } from '@testing-library/react'const testPageFooterWithColor = (renderPage, expectedColor) => { test('it checks that the footer is present and has the correct color', async () => { renderPage() const footerText = screen.getByText('our footer text') await waitFor(() => { expect(footerText).toBeInTheDocument() }) expect(footerText).toHaveStyle({ color: expectedColor }) })}export { testPageFooterWithColor }
Then we can import it in our suites:
const renderCustomPage = () => { render( <CustomPage />, { wrapper: MemoryRouter }, ) } describe('our test suite', () => { ...our tests testPageFooterWithColor(renderCustomPage, 'white') })
Thank you for reading! Let's connect on Twitter or Mastodon!
Original Link: https://dev.to/buaiscia/make-a-reusable-test-with-react-testing-library-272m
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To