Test Images in React with Jest
This post contain affiliate links to Udemy courses, meaning when you click the links and make a purchase, I receive a small commission. I only recommend courses that I believe support the content, and it helps maintain the site.
I was recently asked how to test that an image is displayed in a React component. This short piece outlines a solution using Jest and a small touch of React Testing Library.
With images, there are two things we can test for. That the image src
has been populated correctly, and the image alt
tag has been populated correctly.
The Example
We have a small component that renders an image depending on what argument is passed in.
// This is the component we will test.
export const ImageComponent = ({ size }) => (
<img
src={`https://www.example.com/image-${size}.png`}
alt={`The image alt tag for the ${size} image`}
/>
);
// This is where it is rendered in the app.
export default () => <ImageComponent size="big" />;
How To Test Images in React with Jest
The tests need to be able to confirm that when the argument changes, the image that is rendered within the component is correct. Using Jest alongside React we can check for the correct alt
and src
values.
The Jest test would be as follows:
import { render } from '@testing-library/react';
import { ImageComponent } from './';
describe('The image component', () => {
test('alt contains correct value', () => {
render(<ImageComponent size="large"/>)
const testImage = document.querySelector("img") as HTMLImageElement;
expect(testImage.alt).toContain("The image alt tag for the large image");
})
test('src contains correct value', () => {
render(<ImageComponent size="large"/>)
const testImage = document.querySelector("img") as HTMLImageElement;
expect(testImage.alt).toContain("https://www.example.com/image-large.png");
})
});
Take a look at the article on testing with Jest and React Testing Library for a basic overview of unit testing.
For more React and Jest hints and tips take a look at the React Category, and Jest Testing Category!
Hopefully this helped you, and if you have any questions you can reach me at: @robertmars