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 similiar to chai's instanceof). 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.
Lets 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.
the 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 you want deep validation like @speculees, here's an answer using
deep-keys
(disclosure: I'm sort of a maintainer of this small package)or with
chai
:If you are using underscoreJs then you can simply use _.isEqual function and it compares all keys and values at each and every level of hierarchy like below example.
If all the keys and values for those keys are same in both the objects then it will return true, otherwise return false.
If you want to check if both objects have the same properties name, you can do this:
In this way you are sure to check only iterable and accessible properties of both the objects.
EDIT - 2013.04.26:
The previous function can be rewritten in the following way:
In this way we check that both the objects have the same number of properties (otherwise the objects haven't the same properties, and we must return a logical false) then, if the number matches, we go to check if they have the same properties.
Bonus
A possible enhancement could be to introduce also a type checking to enforce the match on every property.
2 Here a short ES6 variadic version:
A little performance test (MacBook Pro - 2,8 GHz Intel Core i7, Node 5.5.0):
Results:
Here is my attempt at validating JSON properties. I used @casey-foster 's approach, but added recursion for deeper validation. The third parameter in function is optional and only used for testing.
You can serialize simple data to check for equality:
This will give you something like
As a function...
EDIT
If you're using chai like you say, check out http://chaijs.com/api/bdd/#equal-section
EDIT 2
If you just want to check keys...
should do it.