DEV Community

loading...
Cover image for Testing react components

Testing react components

rohanbagchi profile image Rohan Bagchi ・2 min read

As usual, opinions are personal and may contain some bias.

Over the years I found a common recurring pattern wherein React component tests are done by asserting on the internal behaviour of the function rather than the actual output.

Frontend unit tests must treat the test subject, our React Component as a black box just like how an end user might.
For example, when I am filtering apartments in Airbnb, I only care about the information I see on the screen and how it reacts to the filters I apply. At no point do I need to know if the underlying React component state has updated or if the text is an h2 or bold.

2 popular ways I know of, using which we can unit test React components:

  1. Enzyme
  2. React Testing Library

TL;DR I would use React Testing Library approach for writing meaningful unit tests.


What are we testing?

Here, how we render the joke is an implementation detail. The fact that the joke gets fetched and rendered on click of the button is the behavior.

For example, later on we could render the joke inside a <p/> tag. The behavior of the component would remain unchanged and as such we should not have to touch our tests for this change.

Enzyme test

Here, you will see we are extracting text content of the <h3/> element using wrapper.find('h3').text(). So based on our contrived example above, if we were to convert the <h3/> into a <p/>, our test will break. For a larger, more complex component, the changes will increase exponentially. This makes refactors hard.

React Testing Library Test

Here, we are only testing for the behavior. So, as long as the behavior stays same, an update in how we render the joke for this case makes no difference. For larger projects with lot more complexity, passing tests across refactors will give developers confidence and help them move fast.

Full repo here

Description

Created for showing a demo of testing the same React component using Enzyme and React Testing Library Where with Enzyme, it is more around the implementation details, with React Testing Library it is around the behavior.

Link to dev.to blog post

https://dev.to/rohanbagchi/testing-react-components-fkc

How to run?

  1. npm i
  2. npm run test

This will trigger the tests and both will pass of course.

What are we testing?

import "./styles.css";
import { useState } from "react";
import { get } from "axios";
export default function App() {
  const [joke, setJoke] = useState(null);
  const [error, setError] = useState(null);
  const fetchJoke = async () => {
    try {
      const { data } = await get("https://api.icndb.com/jokes/random");
      if (data.type === "success") {
        setJoke(data?.value
Enter fullscreen mode Exit fullscreen mode

Thank you for reading this far. Let me know what you feel in comments.

Discussion (0)

pic
Editor guide