2017-01-05 12 views
2

我的頂級組件需要childrenreact-router像這樣:我如何寫一個使用React.cloneElement組件的測試?

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的調用?

+0

的可能的複製[如何測試上反應成分的道具更新](http://stackoverflow.com/questions/30614454/how-to-測試-A-丙更新上反應的組分) – bman

+0

恐怕沒有。該人收到的錯誤消息中包含術語「React.cloneElement」。我的問題涉及如何測試何時使用'React.cloneElement'。 – Brandon

+0

我想你忘了通過窗口小部件的道具,它應該是這樣的:'ReactDOM.render(<應用小部件= {一些值} />,DIV)' –

回答

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) 
}) 
相關問題