admin管理员组文章数量:1406144
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;
}
本文标签: javascriptCannot read property of an undefined object in a IF statement in JESTStack Overflow
版权声明:本文标题:javascript - Cannot read property of an undefined object in a IF statement in JEST - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744977972a2635636.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论