首页 > 解决方案 > 测试传递给 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()
})

请注意以下事项:

编辑:

为了进一步说明这个问题,如果我有第二个子组件NonReduxChild并给它一个propTypewhichisRequired并有一个测试,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编写一个特定的测试(我不想在包含数百个组件的代码库中这样做)。

标签: reactjsreduxreact-reduxintegration-testingjestjs

解决方案


我认为您可以将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);`
})

推荐阅读