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

新手上路,请多包涵

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

我正在为我的登录页面构建 视差 组件。

组件通过 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 测试图像是否正确设置为背景图像?

原文由 J. Hesters 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 738
2 个回答

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

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

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

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

确保安装 @testing-library/jest-dom 以获得 toHaveStyle

原文由 Giorgio Polvara - Gpx 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

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

如果您发现自己使用容器来查询呈现的元素,那么您应该重新考虑!其他查询旨在更灵活地应对将对您正在测试的组件进行的更改。避免使用容器来查询元素!

原文由 Katie McCulloch 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进