React testing library: Test styles (specifically background image)

in addition to toHaveStyle JsDOM Matcher, you can use also style property which is available to the current dom element

Element DOM API

expect(getByTestId('background').style.backgroundImage).toEqual(`url(${props.image})`)

also, you can use another jestDOM matcher

toHaveAttribute Matcher

expect(getByTestId('background')).toHaveAttribute('style',`background-image: url(${props.image})`)

If you want to avoid adding data-testid to your component, you can use container from react-testing-library.

const {container} = render(<Parallax {...props})/>
expect(container.firstChild).toHaveStyle(`background-image: url(${props.image})`)

This solution makes sense for your component test, since you are testing the background-image of the root node. However, keep in mind this note from the docs:

If you find yourself using container to query for rendered elements then you should reconsider! The other queries are designed to be more resiliant to changes that will be made to the component you're testing. Avoid using container to query for elements!


getByText won't find the image or its CSS. What it does is to look for a DOM node with the text you specified.

In your case, I would add a data-testid parameter to your background (<div data-testid="background">) and find the component using getByTestId.

After that you can test like this:

expect(getByTestId('background')).toHaveStyle(`background-image: url(${props.image})`)

Make sure you install @testing-library/jest-dom in order to have toHaveStyle.