DEV Community

Cover image for Make a reusable test with React Testing Library
Alex
Alex

Posted on • Originally published at buaiscia.github.io

2

Make a reusable test with React Testing Library

Photo by Sigmund on Unsplash

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 }
Enter fullscreen mode Exit fullscreen mode

Then we can import it in our suites:

  const renderCustomPage = () => {
    render(
      <CustomPage />,
      { wrapper: MemoryRouter },
    )
  }

  describe('our test suite', () => {
    ...our tests

    testPageFooterWithColor(renderCustomPage, 'white')
  })
Enter fullscreen mode Exit fullscreen mode

Thank you for reading! Let's connect on Twitter or Mastodon!

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay