与孩子一起反应测试组件

时间:2016-02-08 17:37:30

标签: javascript testing reactjs

如何测试具有" children"?

的React组件

我有一个Center组件,它基本上包装了一个元素(children)

这是中心组件:

const Center = ({ children }) => (
  <div className='center'>
    <div className='center__content'>{children}</div>
  </div>
)

下面是我尝试过的代码,但是我收到了一个错误&#34;无法尝试去构造非可迭代实例&#34;

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

    })
  })
})

1 个答案:

答案 0 :(得分:3)

React组件的子级#include可以是以下两种类型之一:

  • 一个数组
  • 一个孩子(在没有孩子的情况下)

有关详细信息,请参阅React documentation

因此,您所引用的解引用语句会导致错误,因为this.props.children不是定义了this.props.children属性的Object。

我建议div检查output.props.children的样子。

您对console.log(output.props.children)的测试应该是这样的:

output.props.children

相关问题