randomKek February 2016

React test component with children

How can I test a React component that has "children"?

I have a Center component, which basically wraps an element (children)

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')

    })
  })
})

Answers


GordyD February 2016

A React component'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 component.

Post Status

Asked in February 2016
Viewed 2,022 times
Voted 11
Answered 1 times

Search




Leave an answer