DEV Community


A simple image test in React

raphaelchaula profile image Raphael Chaula ・1 min read

There isn't much to test in images, when I write a test for an image element (img) in React apps, I just check if img element exists and if img src and its alt is correct.

Here is how.


import { FunctionComponent } from 'react';

const Logo: FunctionComponent = () => {
  return (
    <img src="/logo.svg" alt="Logo"  />

export default Logo;
Enter fullscreen mode Exit fullscreen mode


import { render, screen } from '@testing-library/react';
import Logo from './logo';

describe('Logo', () => {
  test('Logo must have src = "/logo.svg" and alt = "Logo"', () => {
    const logo = screen.getByRole('img');
    expect(logo).toHaveAttribute('src', '/logo.svg');
    expect(logo).toHaveAttribute('alt', 'Logo');
Enter fullscreen mode Exit fullscreen mode

Then run yarn test or npm run test
Results of your tests will be displayed on console

Happy Hacking!

Discussion (0)

Editor guide