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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With