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

Bir*_*ish 2 unit-testing reactjs jestjs enzyme

在组件的渲染部分中,我有以下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>
Run Code Online (Sandbox Code Playgroud)

要为此组件编写测试单元,我尝试浅显示它(const component = shallow(<myComponent />);)并返回此错误:

TypeError: Cannot read property 'id' of undefined
Run Code Online (Sandbox Code Playgroud)

所以我需要在测试中将这个道具发送给我的组件.我应该如何发送idthis.props.params.id浅度呈现?

fab*_*tto 6

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

const component = shallow(<myComponent params={{ id: 1 }} />)
Run Code Online (Sandbox Code Playgroud)

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

React.createElement(MyComponent, { params: { id: 1 } });
Run Code Online (Sandbox Code Playgroud)

注意:您调用了组件,myComponent但在JSX中,用户定义的组件名称应以大写字母(MyComponent)开头,而"普通"元素(如div)以小写字母开头.