I have a simple if-else statement as
if(this.props.params.id){
//do something
}
Now, this works fine in the browser. If there is an id in the params it enters the if clause and doesn't if there is no id.
Now while writing test with jest, when the id is not defined it throws an error: "Cannot read property 'id' of undefined" Why is this happening, shouldnt it treat it as false? It works fine in the browser, just in the testing it throws an error.
I have a simple if-else statement as
if(this.props.params.id){
//do something
}
Now, this works fine in the browser. If there is an id in the params it enters the if clause and doesn't if there is no id.
Now while writing test with jest, when the id is not defined it throws an error: "Cannot read property 'id' of undefined" Why is this happening, shouldnt it treat it as false? It works fine in the browser, just in the testing it throws an error.
Share Improve this question edited Jun 8, 2016 at 10:01 BioGeek 23k23 gold badges90 silver badges154 bronze badges asked Feb 19, 2016 at 4:37 Pratish ShresthaPratish Shrestha 1,9224 gold badges18 silver badges26 bronze badges3 Answers
Reset to default 2If id itself is undefined, then your test works as expected (although there are much better ways of writing it)
The problem you are getting is from this.props.params being undefined. In that case, you are trying to access a property of something that doesn't exist.
To solve for this, you need to check if both params AND id are defined.
You can do that like this:
if (typeof this.props.params !== 'undefined' && this.props.params.id !== 'undefined') {
//do something
}
Its much better to use typeof for checking for undefined variables, as it is possible for your if statement to fail if the variable evaluates to false.
Before you can check:
if (bar.foo) {
// do something
}
You first have to check for:
if (bar) {
if (bar.foo) {
// do something
}
}
Or in one statement...
if (bar && bar.foo) {
// do something
}
Try:
if(this.props.params){
var id = this.props.params.id;
}