I am using node, mocha, and chai for my application. I want to test that my returned results data property is the same "type of object" as one of my model objects (Very similar to chai's instance). I just want to confirm that the two objects have the same sets of property names. I am specifically not interested in the actual values of the properties.
Let's say I have the model Person like below. I want to check that my results.data has all the same properties as the expected model does. So in this case, Person which has a firstName and lastName.
So if results.data.lastName
and results.data.firstName
both exist, then it should return true. If either one doesn't exist, it should return false. A bonus would be if results.data has any additional properties like results.data.surname, then it would return false because surname doesn't exist in Person.
This model
function Person(data) { var self = this; self.firstName = "unknown"; self.lastName = "unknown"; if (typeof data != "undefined") { self.firstName = data.firstName; self.lastName = data.lastName; } }
If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal.
You cannot. Property keys are unique. Follow TravisJ 's advice. You might want to look up the term 'multimap', too.
The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.
You can serialize simple data to check for equality:
data1 = {firstName: 'John', lastName: 'Smith'}; data2 = {firstName: 'Jane', lastName: 'Smith'}; JSON.stringify(data1) === JSON.stringify(data2)
This will give you something like
'{firstName:"John",lastName:"Smith"}' === '{firstName:"Jane",lastName:"Smith"}'
As a function...
function compare(a, b) { return JSON.stringify(a) === JSON.stringify(b); } compare(data1, data2);
If you're using chai like you say, check out http://chaijs.com/api/bdd/#equal-section
If you just want to check keys...
function compareKeys(a, b) { var aKeys = Object.keys(a).sort(); var bKeys = Object.keys(b).sort(); return JSON.stringify(aKeys) === JSON.stringify(bKeys); }
should do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With