Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Object.hasOwnProperty

I have a code implementation that iterates over an object's properties.

for (const prop in obj) {
    propsMap[prop] = prop;
}

But as is states, my IDE (WebStorm) adviced me to add a property check using obj.hasOwnProperty(prop) to avoid iterating over inexistant properties:

for (const prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        propsMap[prop] = prop;
    }
}

The problem is that the current tests always come with obj.hasOwnProperty(prop) being true and the coverage is not the best I could get and I don't know what could happen if obj does not actually have the property prop.

like image 947
Supamiu Avatar asked Sep 12 '25 10:09

Supamiu


1 Answers

To test this you could create object that inherits something from its prototype

const obj = Object.create({name: 'inherited'})

name will falsyfy obj.hasOwnProperty('name') check.

But there are better options to copy object. For example Object.assign

Object.assign(propsMap, obj)

Also you should keep in mind that obj.hasOwnProperty check is error prone. For example

const obj = {hasOwnProperty: null} // hasOwnProperty is not a function
const obj = Object.create(null) // obj wont inherit hasOwnProperty 

so atleast replace it with

const hasOwnProperty = {}.hasOwnProperty

for(const name in obj) {
  if(hasOwnProperty.call(obj, name)) {

  }
like image 117
Yury Tarabanko Avatar answered Sep 14 '25 00:09

Yury Tarabanko