Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert the width of an image using React Testing Library

Say I have a simple image based component:

// ./Figure.js

const Figure = ({src}) => (
    <img
        src={src}
        width="100%"
    />
);

I want to test that its width is 100%.

My test:

// ./Figure.test.js

import Figure from './Figure'
import { render, screen } from '@testing-library/react'

describe('Figure', () => {
    const setup = () => {
        return render(
            <Figure
                src="https://src.com"
            />
        )
    }

    it('has the right width', () => {
        setup()

        const image = screen.getByAltText('alt')

        expect(image.src).toBe('https://src.com/')
        expect(image.width).toBe("100%")
    })
})

However, that gives me an error:

  ● Figure › renders

    expect(received).toBe(expected) // Object.is equality

    Expected: "100%"
    Received: 0

Question: How can I assert the width of an image using React Testing Library without using snapshots?

like image 330
bluprince13 Avatar asked Oct 21 '25 04:10

bluprince13


2 Answers

The most direct answer is to specify the 100% width definition as a CSS style rather than use the width attribute. The HTML Standard indicates that width and height are meant to be "valid non-negative integers" representing the pixel dimensions of the resource; what you actually want is an image to fit its container, which is a CSS concern.

By doing this, you can now use getComputedStyle() in your test to validate what you specified and that it's not overridden by anything else.

// ./Figure.js
const Figure = ({src}) => (
    <img
        src={src}
        style="width: 100%;"
    />
);

// ./Figure.test.js
it('has the right width', () => {
    setup()

    const image = screen.getByAltText('alt')

    expect(image.src).toBe('https://src.com/')
    expect(getComputedStyle(image).width).toBe("100%")
})

The extended answer is that Jest uses jsdom under the hood, which is essentially a mock browser written in javascript. It's meant to behave very similarly to a browser but is not exactly the same in order to be useful for testing.

I don't personally know all the boundaries of jsdom, though I do recall having issues testing anything related to dimensions or positioning. As a result, I tend to either not test those things explicitly (I prefer testing behaviour over presentation) or test them in a true headless browser, using for example either of jest-electron-runner or Taiko.

like image 188
Auroratide Avatar answered Oct 22 '25 19:10

Auroratide


I had the same issue and like this worked fine for me:

expect(image).toHaveAttribute("width", "100%")
like image 30
Shadow Avatar answered Oct 22 '25 18:10

Shadow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!