How to Test Images in React

Bethany Drake
2 min readSep 7, 2020

--

React-testing-library doesn’t help us. But vanilla JavaScript gives us everything we need!

confused programmer
Photo by bruce mars on Unsplash

Situation:

In my react app, I want to test that the correct image is displayed.

Complication:

React-testing-library doesn’t provide any tools for confirming the image source.

Solution:

Vanilla JavaScript!

For example:

Imagine a component that displays a result of a test, ScoreDisplayer. If the score is a passing grade, say, above 60%, then a happy face is displayed (`Face-smile.svg`). Otherwise, a sad face is displayed (`Face-sad.svg`).

The code might look something like this:

And would result in the following component:

So how can we test this using react-testing-library?

How do we test this code? Using react-testing-library, we might use findByAltText:

Tests using react-testing-library. It makes assertions on the image alt-text.

But, this doesn’t test that we are actually displaying the right image. If a programmer attempted to refractor the code without realising a different image was used in each case, an error could occur without being picked up by the test. For example, the following code passes the react-testing-library test:

Potential refactoring of the ScoreDisplayer element. It passed the react-testing-library tests, despsite incorrectly displaying a happy face when the score is below a passing grade.

How can vanilla JavaScript help?

An alternate solution is to use a querySelector provided by vanilla JavaScript. This finds the first matching HTMLElement. We can make assertions on any aspect of this element, including the source.

Tests using vanilla javascript. It makes asserstion on the image source, not just the alt text.

There! Now we’ve directly tested what we want to test!

Photo by Bermix Studio on Unsplash

Things to note:

  • document.querySelector() returns a generic HTMLElement. Since we know the concrete type we expect it to be, we can cast as HTMLImageElement to get relevant type hints.
  • I’m still using render() from the react-testing-library to add the component to the document. There are probably other ways of doing this, too.
  • I’m not sure if this approach is encouraged or standard in the react community. All I know is it makes sense to me. Other thoughts welcome in the comments!

Documentation links:

--

--