Search code examples
reactjstypescriptunit-testingjestjsreact-testing-library

React testing library: Test styles (specifically background image)


I'm building a React app with TypeScript. I do my component tests with react-testing-library.

I'm buildilng a parallax component for my landing page.

The component is passed the image via props and sets it via JSS as a background image:

<div
  className={parallaxClasses}
  style={{
    backgroundImage: "url(" + image + ")",
    ...this.state
  }}
>
  {children}
</div>

Here is the unit test that I wrote:

import React from "react";
import { cleanup, render } from "react-testing-library";
import Parallax, { OwnProps } from "./Parallax";
afterEach(cleanup);

const createTestProps = (props?: object): OwnProps => ({
  children: null,
  filter: "primary",
  image: require("../../assets/images/bridge.jpg"),
  ...props
});

describe("Parallax", () => {
  const props = createTestProps();
  const { getByText } = render(<Parallax {...props} />);
  describe("rendering", () => {
    test("it renders the image", () => {
      expect(getByText(props.image)).toBeDefined();
    });
  });
});

But it fails saying:

● Parallax › rendering › it renders the image

    Unable to find an element with the text: bridge.jpg. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

    <body>
      <div>
        <div
          class="Parallax-parallax-3 Parallax-primaryColor-4"
          style="background-image: url(bridge.jpg); transform: translate3d(0,0px,0);"
        />
      </div>
    </body>

      16 |   describe("rendering", () => {
      17 |     test("it renders the image", () => {
    > 18 |       expect(getByText(props.image)).toBeDefined();
         |              ^
      19 |     });
      20 |   });
      21 | });

      at getElementError (node_modules/dom-testing-library/dist/query-helpers.js:30:10)
      at getAllByText (node_modules/dom-testing-library/dist/queries.js:336:45)
      at firstResultOrNull (node_modules/dom-testing-library/dist/query-helpers.js:38:30)
      at getByText (node_modules/dom-testing-library/dist/queries.js:346:42)
      at Object.getByText (src/components/Parallax/Parallax.test.tsx:18:14)

How can I test that the image is being set as a background image correctly with Jest and react-testing-library?


Solution

  • 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.