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;
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');
});
});
Then run yarn test
or npm run test
Results of your tests will be displayed on console
Top comments (8)
Thanks so much, its very clear and helpful
nice
Very simple and clear
thanks man a lot
Good tip !! Thanks for sharing !!
Thank you so much!!!!!!
very helpful thank you!
we can add another expect with toBevisible()
thanks