[英]React test component with children
How can I test a React component that has "children"? 如何测试具有“子级”的React组件?
I have a Center component, which basically wraps an element (children) 我有一个Center组件,该组件基本上包装了一个元素(子元素)
This is the Center component: 这是中心组件:
const Center = ({ children }) => (
<div className='center'>
<div className='center__content'>{children}</div>
</div>
)
Below is the code I have tried, but I got an error "Invalid attempt at destructure non-iterable instance" 以下是我尝试过的代码,但出现错误“在无效的不可迭代实例中进行无效尝试”
function setup () {
const props = {}
const renderer = TestUtils.createRenderer()
renderer.render(<Center {...props}><p>Hi</p></Center>)
const output = renderer.getRenderOutput()
return {
props,
output
}
}
describe('(Components)', () => {
describe('Center', () => {
it('should render correctly', () => {
const { output } = setup()
expect(output.type).to.equal('div')
expect(output.props.className).to.equal('center')
const [ div ] = output.props.children // Error triggered here, how do I access this 'center__content' ?
expect(div.props.className).to.equal('center__content')
})
})
})
A React component's children this.props.children
can be one of two types: React组件的子项
this.props.children
可以是以下两种类型之一:
See the React documentation for more information 查看React文档以获取更多信息
Therefore the de-referencing statement you have is causing an error as this.props.children is not an Object with a div
attribute defined. 因此,您拥有的取消引用语句会导致错误,因为this.props.children不是已定义
div
属性的对象。
I'd advise inspecting what output.props.children
looks like by doing console.log(output.props.children)
. 我建议通过执行
console.log(output.props.children)
检查output.props.children
外观。
Your tests on output.props.children
should be something like: 您对
output.props.children
测试应类似于:
expect(this.props.children.type).to.equal('p'); // The child element you passed into your Center component.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.