React testing library: Test styles (specifically background image) React testing library: Test styles (specifically background image) reactjs reactjs

React testing library: Test styles (specifically background image)


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 jest-dom in order to have toHaveStyle.


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!


Simple solution for testing Component css with react-testing-library. this is helpful for me it is working perfect.

test('Should attach background color if user      provide color from props', () => {render(<ProfilePic name="Any Name" color="red" data-  testid="profile"/>);//or can fetch the specific element from the component const profile = screen.getByTestId('profile');const profilePicElem = document.getElementsByClassName(  profile.className,);const style = window.getComputedStyle(profilePicElem[0]);//Assertion expect(style.backgroundColor).toBe('red');});