DEV Community

Robert Marshall
Robert Marshall

Posted on • Originally published at robertmarshall.dev on

3 1

Test Images in React with Jest

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" />;
Enter fullscreen mode Exit fullscreen mode

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");
  })
});
Enter fullscreen mode Exit fullscreen mode

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay