最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot read property of an undefined object in a IF statement in JEST - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 2

If 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;
}
发布评论

评论列表(0)

  1. 暂无评论