首页 > 解决方案 > 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;
}

任何帮助表示赞赏。

标签: reactjsjestjsreact-testing-libraryuse-effectreact-portal

解决方案


但是,在我的测试中,我发现 window.getComputedStyle(component) 没有返回从样式表应用的任何样式。

请注意,如果您在 JSDOM 中运行测试(即每个 Jest 测试),那么 CSS 并没有完全实现。具体来说,CSS的级联部分没有实现(https://github.com/jsdom/jsdom/pull/2690)。继承只是部分实现(displayvisibility)(https://github.com/jsdom/jsdom/issues/2160)。

我建议只在浏览器而不是 JSDOM 中运行断言计算样式的测试。代码沙盒测试未在实际浏览器环境中运行。


推荐阅读