How can I test a React ponent that has "children"?
I have a Center ponent, which basically wraps an element (children)
This is the Center ponent:
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')
})
})
})
How can I test a React ponent that has "children"?
I have a Center ponent, which basically wraps an element (children)
This is the Center ponent:
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')
})
})
})
Share
Improve this question
asked Feb 8, 2016 at 17:37
randomKekrandomKek
1,1283 gold badges18 silver badges34 bronze badges
1 Answer
Reset to default 5A React ponent's children this.props.children
can be one of two types:
- an array
- a single child (in the instance that there is no child)
See the React documentation for more information
Therefore the de-referencing statement you have is causing an error as this.props.children is not an Object with a div
attribute defined.
I'd advise inspecting what output.props.children
looks like by doing console.log(output.props.children)
.
Your tests on output.props.children
should be something like:
expect(this.props.children.type).to.equal('p'); // The child element you passed into your Center ponent.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745345833a4623537.html
评论列表(0条)