React测试库:测试样式(特别是背景图片)

时间:2018-11-02 13:04:02

标签: reactjs typescript unit-testing jestjs react-testing-library

我正在用TypeScript构建一个React应用。我使用react-testing-library进行组件测试。

我正在为目标网页构建一个parallax组件。

组件通过props传递图像,并通过JSS将其设置为背景图像:

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

这是我写的单元测试:

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();
    });
  });
});

但是没有说:

● 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)

如何使用Jest和react-testing-library测试图像是否已正确设置为背景图像?

3 个答案:

答案 0 :(得分:2)

getByText找不到图像或其CSS。它的作用是查找具有您指定的文本的DOM节点。

在您的情况下,我将向您的背景(data-testid)添加一个<div data-testid="background">参数,并使用getByTestId查找该组件。

之后,您可以像这样进行测试:

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

确保安装jest-dom才能拥有toHaveStyle

答案 1 :(得分:0)

如果要避免将data-testid添加到组件中,可以使用react-testing-library中的container

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

此解决方案对于组件测试很有意义,因为您正在测试根节点的背景图像。但是,请记住以下文档中的注释: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!

答案 2 :(得分:0)

使用 react-testing-library 测试组件 css 的简单解决方案。这对我很有帮助,它完美无缺。

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');
});