reactjs - React-testing-library 不从样式表渲染计算样式
问题描述
基本场景是这样的:我有一个width: 100%
在样式表中定义的组件。因此它应该保留其父组件的宽度。我想计算我的组件的宽度并将其应用于我的子组件,因为我正在通过渲染它createPortal
并且我希望它们具有相同的宽度。这在浏览器中有效。但是,在我的测试中,我发现它window.getComputedStyle(component)
没有返回从样式表应用的任何样式。
正如建议的那样,我可以模拟 javascript 窗口,但这实际上与我希望做的相反,我认为。我想验证浏览器中存在的行为,它window.getComputedStyle()
返回所有应用的样式,而不仅仅是内联样式。
我已经将一个简单的示例放入代码盒中:https ://codesandbox.io/s/goofy-wilson-6v4dp
也在这里:
function App() {
return (
<div className="App">
<WidthComponent />
</div>
)
}
function WidthComponent() {
const myInput = useRef();
const [inputWidth, setInputWidth] = useState(0);
useEffect(() => {
console.log("in handleLoad");
const width = myInput.current ? myInput.current.offsetWidth : 0;
setInputWidth(width);
}, [myInput]);
return (
<div className="inherited-width" ref={myInput}>
<div style={{ width: inputWidth }} className="child-element">
Hello
</div>
</div>
);
}
// test
test("width is inherited", () => {
const { rerender } = render(
<div style={{ width: "452px" }}>
<WidthComponent />
</div>
);
const element = document.getElementsByClassName("child-element").item(0);
rerender(
<div style={{ width: "452px" }}>
<WidthComponent />
</div>
);
expect(window.getComputedStyle(element).width).toBe("452px");
});
.App {
font-family: sans-serif;
text-align: center;
width: 500px;
}
.inherited-width {
width: inherit;
}
任何帮助表示赞赏。
解决方案
但是,在我的测试中,我发现 window.getComputedStyle(component) 没有返回从样式表应用的任何样式。
请注意,如果您在 JSDOM 中运行测试(即每个 Jest 测试),那么 CSS 并没有完全实现。具体来说,CSS的级联部分没有实现(https://github.com/jsdom/jsdom/pull/2690)。继承只是部分实现(display
和visibility
)(https://github.com/jsdom/jsdom/issues/2160)。
我建议只在浏览器而不是 JSDOM 中运行断言计算样式的测试。代码沙盒测试未在实际浏览器环境中运行。
推荐阅读
- python - 我不断收到此错误“引发异常('修订格式必须是 XYZ[-tag]')异常:修订格式必须是 XYZ[-tag]”
- vue.js - Nuxt Content - 从 firebase 加载后显示内容
- sharepoint-2013 - Sharepoint 2013 中缺少目标受众
- c - C - Vigenere 加密
- python - 诗歌安装 opencv-contrib-python 失败
- c - 奇怪的问题,在尝试从文档而不是空格扫描数据时,程序在 C 中读取新行
- docker - Docker 构建错误:无法连接到 unix:///var/run/docker.sock 上的 Docker 守护程序。docker 守护进程是否正在运行?
- solidity - 在工厂合同中创建合同不起作用
- dwolla - ACH / eCheck 付款处理,无需验证客户和资金来源
- reactjs - 使用 React 获取 api 时方法名称错误中发现无效字符