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

J. *_*ers 7 unit-testing typescript reactjs jestjs react-testing-library

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

我正在为目标网页构建视差组件。

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

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

这是我编写的单元测试:

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();
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

但是它没有说:

? 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)
Run Code Online (Sandbox Code Playgroud)

如何通过Jest和react-testing-library测试将图像正确设置为背景图像?

小智 10

如果您想避免将 data-testid 添加到您的组件中,您可以使用react-testing-library 中的容器

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

此解决方案对您的组件测试很有意义,因为您正在测试根节点的背景图像。但是,请记住文档中的此注释:

如果您发现自己使用容器来查询渲染元素,那么您应该重新考虑!其他查询旨在更适应将对您正在测试的组件所做的更改。避免使用容器来查询元素!


Gio*_*Gpx 7

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

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

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

expect(getByTestId('background')).toHaveStyle(`background-image: url(${props.image})`)
Run Code Online (Sandbox Code Playgroud)

确保安装jest-dom后才能安装toHaveStyle

  • 这对我不起作用,即使安装了 jest-dom,我也会收到“TypeError: Expect(...).toHaveValue is not a function”。难道是因为我正在测试样式组件? (2认同)
  • 明白了,必须将“import '@testing-library/jest-dom/extend-expect'”添加到测试文件中。在这里找到它https://spectrum.chat/testingjavascript/help/where-do-i-set-up-jest-dom-extend-expect~ea744f78-a306-465a-a599-4abad4bc1857 (2认同)

sam*_*war 7

除此之外toHaveStyle JsDOM Matcher,您还可以使用style当前 dom 元素可用的属性

元素 DOM API

expect(getByTestId('background').style.backgroundImage).toEqual(`url(${props.image})`)
Run Code Online (Sandbox Code Playgroud)

另外,您可以使用另一个 jestDOM 匹配器

toHaveAttribute匹配器

expect(getByTestId('background')).toHaveAttribute('style',`background-image: url(${props.image})`)
Run Code Online (Sandbox Code Playgroud)