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

Leave a Comment