我也研究过类似的问题(比如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示例。
发布于 2019-12-10 05:47:48
我们可以在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是为了更可靠地测试逻辑。我不希望从测试环境中计算出真正的样式(比如偏移大小)。
https://stackoverflow.com/questions/59132347
复制相似问题