【问题标题】:Sending props to a React component for a Jest unit test将 props 发送到 React 组件以进行 Jest 单元测试
【发布时间】:2016-11-18 11:53:56
【问题描述】:

在组件的渲染部分,我有以下 div:

<div className="col-sm-8" >
<input ref='full_link' className="formctrl" name='full_link' type='text'
value={browser.getURL(this.props.params.id)} />
</div>

为了为这个组件编写一个测试单元,我尝试对它进行浅层渲染(const component = shallow(&lt;myComponent /&gt;);),它返回了这个错误:

TypeError: Cannot read property 'id' of undefined

所以我需要在测试中将此道具发送到我的组件。我应该如何将id 从this.props.params.id 发送到浅层渲染?

【问题讨论】:

    标签: unit-testing reactjs jestjs enzyme


    【解决方案1】:

    就像使用组件时通常做的那样传递道具:

    const component = shallow(<myComponent params={{ id: 1 }} />)
    

    不要忘记 JSX 只是一种更好的方式:

    React.createElement(MyComponent, { params: { id: 1 } });
    

    注意:您将组件命名为 myComponent,但在 JSX 中,用户定义的组件名称应以大写字母 (MyComponent) 开头,而“普通”元素(例如 div)以小写字母开头。

    【讨论】:

      猜你喜欢
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      • 2021-09-06
      • 2016-03-05
      • 2022-01-06
      • 1970-01-01
      相关资源
      最近更新 更多