首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何定义react-testing-library的容器大小?

如何定义react-testing-library的容器大小?
EN

Stack Overflow用户
提问于 2019-12-02 11:36:02
回答 1查看 9K关注 0票数 10

我也研究过类似的问题(比如this one),但在使用react-testing-library时,提出的解决方案对我不起作用。

我有一个可以接收多个子组件的组件。然后这个组件将计算它自己的大小和它的子组件的大小,以检查它将能够呈现多少个子组件。当我在我的应用程序中使用它时,它工作得很好。

我的问题是,在使用react-testing-library呈现此组件时,组件的容器是使用0 heightwidth呈现的;因此,我的组件将理解没有可用的空间来呈现任何子级。

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

有没有办法“修复”这个问题?

组件(在这个问题中省略了一些代码):

代码语言:javascript
复制
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>
  )
}

使用:

代码语言:javascript
复制
<ParentComponent>
  <Child />
  <Child />
  <Child />
</ParentComponent>

测试:

代码语言:javascript
复制
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示例。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-10 05:47:48

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

代码语言:javascript
复制
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是为了更可靠地测试逻辑。我不希望从测试环境中计算出真正的样式(比如偏移大小)。

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59132347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档