DEV Community

Raphael Chaula
Raphael Chaula

Posted on

23 3

A simple image test in React

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.

Logo

import { FunctionComponent } from 'react';

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

export default Logo;
Enter fullscreen mode Exit fullscreen mode

Logo.test

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

describe('Logo', () => {
  test('Logo must have src = "/logo.svg" and alt = "Logo"', () => {
    render(<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!

Top comments (8)

Collapse
 
iddimsangi profile image
iddimsangi

Thanks so much, its very clear and helpful

Collapse
 
harlyon profile image
Harrison Ekpobimi

nice

Collapse
 
italosantana profile image
Ítalo Santana

Thank you so much!!!!!!

Collapse
 
jackherizsmith profile image
Jack

very helpful thank you!

Collapse
 
olzhas11dev profile image
Olzhas

thanks man a lot

Collapse
 
bernardoow profile image
Bernardo Gomes

Good tip !! Thanks for sharing !!

Collapse
 
karthikdiscoveries profile image
Karthik BT

Very simple and clear

Collapse
 
tadjerounimohamedadel profile image
Adel Mohamed Tadjerouni

we can add another expect with toBevisible()
thanks

Visualizing Promises and Async/Await 🤓

async await

☝️ Check out this all-time classic DEV post on visualizing Promises and Async/Await 🤓

👋 Kindness is contagious

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

Okay