Sarah Sarah - 16 days ago 7
React JSX Question

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?

Answer

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.

Comments