reactjs - 测试传递给 Redux HOC 的强制 PropType
问题描述
我想编写一个测试,以确保反应组件将一个必须propType.isRequired
传递给子组件的道具。
如果未提供道具,我希望此测试失败,如果提供,则通过。我jest-prop-type-error
习惯在我的测试中抛出错误。
给定以下两个组件:
父.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)
我想确保我的Parent
组件在childTitle
不需要编写显式测试的情况下通过道具:
父.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 不是
connect
ed 组件,我可以not
通过childTitle
toParent
并且测试将失败。由于它是一个连接组件,如果我没有通过childTitle
测试通过(即使它是必需的ReduxChild
) - 我知道这非常接近于测试 的功能
PropTypes
,但它的细微差别在于我想检查它是否正确Parent
使用,而不是在 prop 未通过时引发 PropTypes 错误。我希望测试在开发人员删除所需道具时在构建时失败,而不是在我运行代码时在运行时失败。Child
ReduxChild
编辑:
为了进一步说明这个问题,如果我有第二个子组件NonReduxChild
并给它一个propType
whichisRequired
并有一个测试,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
我得到一个测试失败,它很好地捕捉了NonReduxChild
其他可能不提供所需组件的使用情况,我不会因为我必须PropTypes
得到同样的失败ReduxChild
编写一个特定的测试(我不想在包含数百个组件的代码库中这样做)。
解决方案
我认为您可以将title定义为 prop 并且您可以调用它,而不是"childTitle"
. 试试这个..它可能工作
it('should send the required "title" prop to ReduxChild', () => {
`var wrapper = shallow(<Parent renderReduxChild={true} title={"expectedTitle"} />);`
expect(wrapper.props().title).toBeDefined()
`console.log("",childTitle);`
})
推荐阅读
- python-3.x - 如何“修复”使用 Pandas read_sql_query 进行 sql 查询后返回的对象类型
- c# - 如何按总人数和总价值在工人之间平均分配工作?
- c# - (已解决)如何在函数中创建可用于所有其他函数的变量?
- windows - 如何从以管理员身份运行的更新程序/脚本更新 Windows 任务计划程序任务
- python - 如何将一个模块内的类中的 pyqtSignal 连接到另一个模块内的类中的 pyqtSlot?
- github - 删除分支并搞砸备份..需要恢复或跳下桥
- node.js - nodejs如何处理trycatch中的函数错误
- ios - SwiftUI:单一目标中的 iPhone、iPad、Mac
- firebase - Firebase 功能在部署后不起作用(MAC - 操作系统)
- mongodb - 更新 MongoDB 中的实体时,避免单次执行中的多个事务