ran*_*Kek 2 javascript testing reactjs
如何测试具有“子项”的 React 组件?
我有一个 Center 组件,它基本上包装了一个元素(子元素)
这是中心组件:
const Center = ({ children }) => (
<div className='center'>
<div className='center__content'>{children}</div>
</div>
)
Run Code Online (Sandbox Code Playgroud)
下面是我尝试过的代码,但出现错误“无效的解构不可迭代实例的尝试”
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')
})
})
})
Run Code Online (Sandbox Code Playgroud)
React 组件的子组件this.props.children可以是以下两种类型之一:
有关更多信息,请参阅React 文档
因此,您拥有的取消引用语句会导致错误,因为 this.props.children 不是具有div定义属性的对象。
我建议output.props.children通过执行console.log(output.props.children).
你的测试output.props.children应该是这样的:
expect(this.props.children.type).to.equal('p'); // The child element you passed into your Center component.
| 归档时间: |
|
| 查看次数: |
2918 次 |
| 最近记录: |