如何为使用React.cloneElement的组件编写测试?

时间:2017-01-05 03:15:57

标签: javascript reactjs jestjs

我的顶级组件从children获取react-router,如下所示:

class App extends Component {
  render() {
    return (
      <div>
         {React.cloneElement(children, this.props.widgets)}
      </div>
    )
  }
}

我正在尝试使用jest编写一个简单的测试,如下所示:

it('renders without crashing', () => {
  const div = document.createElement('div')
  ReactDOM.render(<App />, div)
})

但是,此测试失败并出现以下错误:

 FAIL  src/App.test.js
  ● renders without crashing

    TypeError: Cannot read property 'props' of undefined

      at Object.<anonymous>.ReactElement.cloneElement (node_modules/react/lib/ReactElement.js:271:34)
      at Object.cloneElement (node_modules/react/lib/ReactElementValidator.js:216:48)
      at App.render (src/App.js:50:57)
      at node_modules/react-dom/lib/ReactCompositeComponent.js:796:21
      at measureLifeCyclePerf (node_modules/react-dom/lib/ReactCompositeComponent.js:75:12)
      at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (node_modules/react-dom/lib/ReactCompositeComponent.js:795:25)
      at ReactCompositeComponentWrapper._renderValidatedComponent (node_modules/react-dom/lib/ReactCompositeComponent.js:822:32)
      at ReactCompositeComponentWrapper.performInitialMount (node_modules/react-dom/lib/ReactCompositeComponent.js:362:30)
      at ReactCompositeComponentWrapper.mountComponent (node_modules/react-dom/lib/ReactCompositeComponent.js:258:21)
      at Object.mountComponent (node_modules/react-dom/lib/ReactReconciler.js:46:35)
      at ReactCompositeComponentWrapper.performInitialMount (node_modules/react-dom/lib/ReactCompositeComponent.js:371:34)
      at ReactCompositeComponentWrapper.mountComponent (node_modules/react-dom/lib/ReactCompositeComponent.js:258:21)
      at Object.mountComponent (node_modules/react-dom/lib/ReactReconciler.js:46:35)
      at mountComponentIntoNode (node_modules/react-dom/lib/ReactMount.js:104:32)
      at ReactReconcileTransaction.perform (node_modules/react-dom/lib/Transaction.js:140:20)
      at batchedMountComponentIntoNode (node_modules/react-dom/lib/ReactMount.js:126:15)
      at ReactDefaultBatchingStrategyTransaction.perform (node_modules/react-dom/lib/Transaction.js:140:20)
      at Object.batchedUpdates (node_modules/react-dom/lib/ReactDefaultBatchingStrategy.js:62:26)

有没有办法模仿cloneElement?或者以忽略对cloneElement

的调用的方式测试组件

1 个答案:

答案 0 :(得分:0)

您的问题是children未定义,因为没有路由器可以提供子组件。

通过创建测试子组件来修复它:

class TestComponent extends Component {
  render() { return (<div className="test" />) }
}

it('renders without crashing', () => {
  const div = document.createElement('div')
  ReactDOM.render(<App><TestComponent /></App>, div)
})