Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending props to a React component for a Jest unit test

In the render part of a component I have the following 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>

To write a test unit for this component, I tried to shallow render it (const component = shallow(<myComponent />);) and it returns this error:

TypeError: Cannot read property 'id' of undefined

So I need to send this props to my component in the test. How should I send id from this.props.params.id to the shallow render?

like image 347
Birish Avatar asked Nov 18 '16 11:11

Birish


People also ask

How do you mock props in Jest React?

To mock a React component, the most straightforward approach is to use the jest. mock function. You mock the file that exports the component and replace it with a custom implementation. Since a component is basically a function, the mock should also return a function.


1 Answers

Just pass the props as you would normally do when using the component:

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

Don't forget JSX is just a fancier way to do:

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

Note: you called your component myComponent but in JSX user-defined component names should begin with a capital letter (MyComponent), while "normal" elements (such as divs) start with a lowercase letter.

like image 108
fabio.sussetto Avatar answered Nov 03 '22 22:11

fabio.sussetto