测试传递给Redux HOC的强制PropType

dou*_*ald 5 integration-testing reactjs jestjs redux react-redux

我想编写一个测试,确保反应组件传递一个propType.isRequired必须具有子组件的prop .

如果未提供道具,我希望此测试失败,如果是,则通过.我正在使用jest-prop-type-error我的测试中抛出错误.

鉴于以下两个组成部分:

Parent.js

const Parent = ({ renderReduxChild , childTitle }) => 
    { return renderReduxChild ? <ReduxChild title={childTitle} /> : <NonReduxChild />}
Run Code Online (Sandbox Code Playgroud)

ReduxChild.js

const ReduxChild = ({ title }) => <div>{title}</div>

ReduxChild.propTypes = { title: PropTypes.string.isRequired }

export default connect(mapStateToProps, mapStateToProps)(ReduxChild)
Run Code Online (Sandbox Code Playgroud)

我想确保我的Parent组件通过childTitleprop而不需要写一个明确的测试说:

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()
})
Run Code Online (Sandbox Code Playgroud)

请注意以下事项:

  • 如果孩子是不是connectED分量,我可以not通过childTitleParent和测试将失败.因为它是一个连接组件,如果我没有通过childTitle测试通过(即使它是必需的ReduxChild)
  • 我知道这非常接近于测试功能PropTypes,但它有点微妙的不同之处在于我想检查它Parent是否Child正确使用,而不是ReduxChild在未传递prop时抛出PropTypes错误.我希望测试在构建时失败,当dev删除所需的prop时,而不是在运行代码时运行时.

编辑:

为了进一步说明这个问题,如果我有第二个孩子组成部分NonReduxChild,并给它一个propTypeisRequired,并有测试Parent这使得NonReduxChild无需提供道具我会在构建/测试时所引发的错误.与ReduxChild我没有.

NonReduxChild.js

const NonReduxChild = ({ text }) = <div>{text}</div>
NonReduxChild.propTypes = { text: PropTypes.string.isRequired }
Run Code Online (Sandbox Code Playgroud)

测试输出

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 |
Run Code Online (Sandbox Code Playgroud)

正如你从测试输出中看到的那样,当我没有提供一个必需的道具时,NonReduxChild我得到了一个测试失败,很好地捕获了NonReduxChild可能无法提供所需的其他组件的使用,PropTypes我不会从ReduxChild我必须得到同样的失败编写一个特定的测试(我不希望在具有数百个组件的代码库中进行测试).

Ste*_*han 0

我相信您遇到的问题是 PropTypes 只是记录警告,这实际上不会导致测试失败。

如果 prop 对于组件的操作至关重要,并且您决定不编写测试来断言 props 存在,那么如果该 prop 不存在,您总是可以让组件抛出错误。这将导致测试失败。