2016-11-18 34 views
0

有沒有一種簡單/直接的方式重新使用React.PropTypes內置到React.PropTypes編程測試和其他代碼?在測試和代碼的其他部分重用react的PropTypes?

例如,如果我有:

ButtonX.propTypes = { 
    className: React.PropTypes.string 
}; 

如果我加載按鈕具有一數值的類名,反應將在控制檯發出警告。

我想重新使用代碼的所有邏輯,以及這樣做:

validateButtonUsingReactPropTypes({ className: 'my-class' }) 

有越來越存取權限的內部的一個已知的乾淨呢?

+0

只是提醒''propTypes'沒有在生產中使用,所以在測試生產時不要依賴它們。 –

回答

1

查看文檔Test Utilities中的文章......它認爲它將提供一些關於如何訪問用於測試的驗證器的示例。

使用renderIntoDocument的示例,基於React GitHub存儲庫中ReactJSXElementValidator-test.js的代碼。

// arrange 
RequiredPropComponent = class extends React.Component { 
    render() { 
    return <span>{this.props.prop}</span>; 
    } 
}; 
RequiredPropComponent.displayName = 'RequiredPropComponent'; 
RequiredPropComponent.propTypes = {prop: React.PropTypes.string.isRequired}; 

// act 
ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop={null} />); 

// assert 
let testPassed = console.error.calls.count() == 0 

可以很明顯的將這一進一些很好的測試工具,但這只是原始的電話。