admin管理员组

文章数量:1435858

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
Add a ment  | 

1 Answer 1

Reset to default 5

A 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.

本文标签: javascriptReact test component with childrenStack Overflow