How to Test Images in React
React-testing-library doesn’t help us. But vanilla JavaScript gives us everything we need!
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
:
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:
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.
There! Now we’ve directly tested what we want to test!
Things to note:
document.querySelector()
returns a generic HTMLElement. Since we know the concrete type we expect it to be, we can castas 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!