如何使用react-testing-library测试React组件的CSS属性? [英] How can I test css properties for a React component using react-testing-library?
问题描述
react-testing-library背后的哲学对我来说很有意义,但是我正在努力将其应用于CSS属性.
The philosophy behind the react-testing-library makes sense to me, but I am struggling to apply it to css properties.
例如,假设我有一个简单的切换组件,该组件在单击时会显示不同的背景色:
For example, let's say I have a simple toggle component that shows a different background color when clicked:
import React, { useState } from "react";
import "./Toggle.css";
const Toggle = () => {
const [ selected, setSelected ] = useState(false);
return (
<div className={selected ? "on" : "off"} onClick={() => setSelected(!selected)}>
{selected ? "On" : "Off"}
</div>
);
}
export default Toggle;
.on {
background-color: green;
}
.off {
background-color: red;
}
我应该如何测试此组件?我编写了以下测试,该测试适用于嵌入式组件样式,但是在使用css类时失败,如上所示.
How should I test this component? I wrote the following test, which works for inline component styles, but fails when using css classes as shown above.
import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import Toggle from "./Toggle";
const backgroundColor = (element) => window.getComputedStyle(element).backgroundColor;
describe("Toggle", () => {
it("updates the background color when clicked", () => {
render(<Toggle />);
fireEvent.click(screen.getByText("Off"));
expect(backgroundColor(screen.getByText("On"))).toBe("green");
});
});
推荐答案
因此,这不是单元或集成测试框架所要做的.他们只测试逻辑.
So that's not what unit or integration test frameworks do. They only test logic.
如果要测试样式,则需要像Selenium这样的端到端/快照测试框架.
If you want to test styling then you need an end-to-end/snapshot testing framework like Selenium.
这篇关于如何使用react-testing-library测试React组件的CSS属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!