我正在使用 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 许可协议
getByText
找不到图像或其 CSS。它的作用是查找带有您指定的文本的 DOM 节点。在您的情况下,我会在您的背景中添加一个
data-testid
参数(<div data-testid="background">
)并使用getByTestId
找到该组件。之后,您可以像这样进行测试:
确保安装
@testing-library/jest-dom
以获得toHaveStyle
。