【发布时间】:2020-03-26 16:16:18
【问题描述】:
我已经研究过类似的问题(例如 this one),但在使用 react-testing-library 时,建议的解决方案对我不起作用。
我有一个可以接收多个孩子的组件。然后,该组件将计算自己的大小和子项的大小,以检查它能够渲染多少个子项。在我的应用程序中使用它时效果很好。
我的问题是,当使用react-testing-library 渲染这个组件时,该组件的容器被渲染为0 height 和width;所以我的组件会明白没有可用空间来渲染任何孩子。
我试图在测试中定义一个custom container;试图强制一些样式设置width 和height;但这些都不起作用。
有没有办法“解决”这个问题?
组件(本题省略部分代码):
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