Testing Object.hasOwnProperty

Viewed 2829

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.

2 Answers

This worked for me:

const parentObj = {
   defaultProp: 'test'
}

const object = Object.create(parentObj, {
    prop: {
       value: 'test',
       enumerable: true
    }
}

The defaultProp property should return false in the hasOwnProperty check

Related