将 props 发送到 React 组件以进行 Jest 单元测试

Sending props to a React component for a Jest unit test

在组件的渲染部分我有以下 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(<myComponent />);),但它 returns 出现此错误:

TypeError: Cannot read property 'id' of undefined

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

像使用组件时一样传递 props:

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

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

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

注意:你调用你的组件 myComponent 但在 JSX 中用户定义的组件名称应该以大写字母开头 (MyComponent),而 "normal" 元素(例如 div)以小写字母开头。