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.
This article was originally posted (and is more up to date) at https://robertmarshall.dev/blog/test-images-in-react-with-jest/
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");
})
});
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
Top comments (0)