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 e 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
.
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 e 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
.
-
"what could happen if obj does not actually have the property prop". the object might inherit from another object via prototype. in this case those properties will be iterated but not "own". If you don't inherit from other object and just create your object with maybe
var obj = {...}
, thenhasOwnProperty
check is useless. – dfsq Commented Aug 10, 2017 at 6:34 -
The object can e from anywhere because this is in a library I'm creating (it's typescript originally, but this is not a typescript-related issue so I didn't tag it as typescript). I think that the test isn't useless here, but I would like to know how I can create an object so that
obj.hasOwnProperty(prop)
will befalse
. – Supamiu Commented Aug 10, 2017 at 6:38 -
How about
Object.keys(obj).forEach(prop => { propsMap[prop] = prop })
? Getting coverage on that would be much easier – Phil Commented Aug 10, 2017 at 6:44
2 Answers
Reset to default 7To 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)) {
}
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