I want to be able to compare two instances of the same class, but only the data:
it("two objects with same data should be equal", function() {
function Person(name, age) {
this.name = name;
this.age = age;
this.isOldEnoughToVote = function() { return age > 18; }
}
var matt1 = new Person('Matt', 21);
var matt2 = new Person('Matt', 21);
expect(matt1).toEqual(matt2);
});
If I compare two instances with the same data, Jasmine says they are not equal:
Tests Expected { name : 'Matt', age : 21, isOldEnoughToVote : Function } to equal { name : 'Matt', age : 21, isOldEnoughToVote : Function }.
Error: Expected { name : 'Matt', age : 21, isOldEnoughToVote : Function } to equal { name : 'Matt', age : 21, isOldEnoughToVote : Function }.I realize toEqual doesn't do this right now, but how do people get around this when testing objects? Javascript doesn't have equals/hashcode like the JVM so their is no concept of object equality vs reference equality. Jasmine it seems compares every key/value pair. Is there another matcher that automatically excludes function values?
One solution I don't love is to declare the functions outside of the class:
function isOldEnoughToVote() { return this.age > 18; }
function Person(name, age) {
this.name = name;
this.age = age;
this.isOldEnoughToVote = isOldEnoughToVote;
}
In this case, there really is only one function so comparing the same function across multiple instances will result in equality. Maybe that's better as it is less function creation? Thoughts?