Testing React components with render props 🤔

August 10, 2020

My current journey in React is taking me down and an interesting and challenging time so I’m learning quite a bit about how to test with Jest and Testing Library.

One of the challenges I came across recently was how to test for render props in my tests. I had a component that rendered some HTML and it would render more content with a prop being present. How in the heck to test for that? Do I have to mess about with the components? The tests? 😖

For some of you it might be a straight forward to figure that out but for me I had dive deep into testing so here’s what I learned.

Using Testing library you can call a component with its default values and it should render whatever it would normally do.

Lets go through an example:

Here we have an App component that just renders some text.

// index.js
<App />;

// app.js component
export default function App() {
  return (
    <div className="App">
      <p>Hello world!</p>
    </div>
  )
}

Fairly simple. Lets write a test for this.

// app.test.js
import React from "react"
import App from "./App"
import { render } from "@testing-library/react"

it("Renders app component with `Hello world!` as text", () => {
  const { getByText } = render(<App />)
  getByText("Hello world!")
})

So let’s update the component to render something else based on a prop being passed.

// index.js
<App showMeta />;

// app.js component
export default function App({ showMeta }) {
  return (
    <div className="App">
      <p>Hello world!</p>
      {showMeta && <p>I am meta</p>}
    </div>
  )
}

The only thing we’ve done here is to pass down a prop of showMeta. We destructure the prop in app.js and then use it by conditionally checking for it. This then renders the I am meta text. So lets update our test for this.

// app.test.js
import React from "react"
import App from "./App"
import { render } from "@testing-library/react"

it("Renders app component with `Hello world!` as text", () => {
  const { getByText, rerender } = render(<App />)
  getByText("Hello world!")

  rerender(<App showMeta />)
  getByText("I am meta")
})

The key here is the rerender utility function returned by testing library when the component is mounted. Essentially we call the component again using the rerender function which includes the prop and assert against that. Fairly simple and thats the key here.

You just rerender the component with the props you need assert against it.


Profile picture

Written by Qasim Alyas