【问题标题】:How to define container size for react-testing-library?如何为 react-testing-library 定义容器大小?
【发布时间】:2020-03-26 16:16:18
【问题描述】:

我已经研究过类似的问题(例如 this one),但在使用 react-testing-library 时,建议的解决方案对我不起作用。

我有一个可以接收多个孩子的组件。然后,该组件将计算自己的大小和子项的大小,以检查它能够渲染多少个子项。在我的应用程序中使用它时效果很好。

我的问题是,当使用react-testing-library 渲染这个组件时,该组件的容器被渲染为0 heightwidth;所以我的组件会明白没有可用空间来渲染任何孩子。

我试图在测试中定义一个custom container;试图强制一些样式设置widthheight;但这些都不起作用。

有没有办法“解决”这个问题?

组件(本题省略部分代码):

const ParentComponent = (props) => {
  const [visibleChildren, setVisibleChildren] = useState(0)
  const myself = useRef(null)

  useEffect(() => {
    const componentWidth = myself.current.offsetWidth;
    const childrenWidth = myself.current.children.reduce(
      // Returns the total children width
    )

    // Returns the number of children I can display
    const childrenAmount = calculateSpace()
    setVisibleChildren(childrenAmount)
  }, [myself])

  // Slice the array of children to display only the right amount
  slicedChildren = props.children.slice(0, visibleChildren)

  return (
    <div ref={myself}>
      {slicedChildren}
    </div>
  )
}

用途:

<ParentComponent>
  <Child />
  <Child />
  <Child />
</ParentComponent>

测试:

import React from 'react'
import {render} from '@testing-library/react'
import ParentComponent from '../ParentComponent'

test('Render component', () => {
  const { getAllByRole } = render(
    <ParentComponent>
      <Child />
      <Child />
      <Child />
    </ParentComponent>
  )

  expect(getAllByRole("Child").length).toEqual(3)
})

更新:

添加了这个codesandbox 示例。

【问题讨论】:

    标签: javascript reactjs jestjs jsdom react-testing-library


    【解决方案1】:

    我们可以在HTMLElement.prototype 上模拟该财产权:

    Object.defineProperties(window.HTMLElement.prototype, {
      offsetWidth: {
        get: function() { return this.tagName === 'SPAN' ? 100: 500}
      }
    });
    

    感谢https://github.com/jsdom/jsdom/issues/135#issuecomment-68191941

    看看问题,它有很长的故事(自 2011 年以来!)但仍然开放

    说实话,我看到嘲笑 offsetWidth 以使测试逻辑更可靠。我不希望从测试环境中一直计算真实样式(如偏移大小)。

    【讨论】:

    • 嗨,布鲁诺,拜托,我也面临着类似的问题。您究竟在测试代码中的哪个位置应用了上述 sn-p?谢谢。
    • 祝福你,非常感谢分享!我一直在努力解决一个类似的场景,涉及一个永远不会检测到宽度变化的网格布局。将 offsetWidth 强制为特定值对我来说是个窍门,我同意这是一种合理的方法来检查某些东西的副作用,因为目标远不及测试浏览器调整宽度的能力,而是组件如果在浏览器中已经发生了调整大小,则行为相应。
    • 嗨@Sau001,我在测试文件的beforeAll() 中添加了上面的片段。
    猜你喜欢
    • 2020-08-01
    • 2023-03-24
    • 2021-06-02
    • 2021-04-25
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    • 2019-08-29
    • 2023-03-13
    相关资源
    最近更新 更多