My component has:
class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchTerm:
typeof this.props.match.params.searchTerm !== "undefined"
? this.props.match.params.searchTerm
: ""
};
}
and the test is:
test("Search should render correct amount of shows", () => {
const component = shallow(<Search shows={preload.shows} />);
expect(component.find(ShowCard).length).toEqual(preload.shows.length);
});
I get
TypeError: Cannot read property 'params' of undefined
How can I fix that or how to set query params in my test?
It seems like when outside the test, the Search
component receives the match
props correctly.
You could pass it as props when shallow rendering it in the test:
test("Search should render correct amount of shows", () => {
const match = { params: { searchTerm: 'foo' } }
const component = shallow(<Search shows={preload.shows} match={match}/>);
expect(component.find(ShowCard).length).toEqual(preload.shows.length);
});
And in that case, you're not changing the component under test in a bad way, your test case just found a bug, which is good and should be aimed in tests, and you improved the component by implementing a default props, making it more robust.
you should defined a location first in your it/test.
it('App init', async () => {
const location = {
...window.location,
search: '?scope=3&elementId=25924',
};
Object.defineProperty(window, 'location', {
writable: true,
value: location,
})
……
})
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