reactjs – 测试传递给Redux HOC的强制PropType
我想编写一个测试,确保一个react组件将propType.isRequired传递给一个子组件.
如果未提供道具,我希望此测试失败,如果是,则通过.我正在使用jest-prop-type-error在我的测试中抛出错误. 鉴于以下两个组成部分: Parent.js const Parent = ({ renderReduxChild,childTitle }) => { return renderReduxChild ? <ReduxChild title={childTitle} /> : <NonReduxChild />} ReduxChild.js const ReduxChild = ({ title }) => <div>{title}</div> ReduxChild.propTypes = { title: PropTypes.string.isRequired } export default connect(mapStateToProps,mapStateToProps)(ReduxChild) 我想确保我的父组件传递childTitle prop,而不需要编写一个显式测试,该测试说: Parent.test.js it('should send the required "title" prop to ReduxChild',() => { const wrapper = shallow(<Parent renderReduxChild={true} childTitle={'expectedTitle'} />) expect(wrapper.props().title).toBeDefined() }) 请注意以下事项: >如果child不是连接组件,我无法将childTitle传递给Parent,测试将失败.由于它是一个连接组件,如果我没有传递childTitle,则测试通过(即使它在ReduxChild中是必需的) 编辑: 为了进一步说明这个问题,如果我有一个第二个子组件NonReduxChild并给它一个propType,它是isRequired并且有一个Parent的测试,它在没有提供prop的情况下呈现NonReduxChild,我会在构建/测试时抛出一个错误.我不喜欢ReduxChild. NonReduxChild.js const NonReduxChild = ({ text }) = <div>{text}</div> NonReduxChild.propTypes = { text: PropTypes.string.isRequired } 测试输出 FAIL test/components/Parent.test.js (8.782s) ● <Parent /> ? when rendering the component ? if renderReduxChild is false it should render <NonReduxChild /> Warning: Failed prop type: The prop `title` is marked as required in `NonReduxChild`,but its value is `undefined`. in NonReduxChild 28 | render() { 29 | const { renderReduxChild,childTitle } = this.state > 30 | return renderReduxChild ? <ReduxChild title={childTitle } /> : <NonReduxChild /> | ^ 31 | } 32 | } 33 | 正如您从测试输出中看到的那样,当我没有为NonReduxChild提供必需的支持时,我得到了一个测试失败,它很好地捕获了可能无法提供所需PropTypes的其他组件的NonReduxChild的使用我不会从ReduxChild我必须编写一个特定的测试(我不希望在具有数百个组件的代码库中做). 解决方法
我相信您遇到的问题是PropTypes只记录警告,这实际上不会导致测试失败.
如果prop对组件的操作至关重要,并且您没有编写测试来声明道具存在,那么如果该prop不存在,您可以始终让组件抛出错误.这将导致测试失败. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |