Checking equality of objects in Jasmine

Jasmine has built-in toBe and toEqual . If I have an object like this:

 function Money(amount, currency){ this.amount = amount; this.currency = currency; this.sum = function (money){ return new Money(200, "USD"); } } 

and try to compare new Money(200, "USD") and the result of the sum, these built-in matches will not work properly. I managed to implement a workaround based on the user equals method and user match, but this seems to work a lot.

What is the standard way to compare objects in Jasmine?

+78
javascript jasmine bdd
May 6 '13 at 2:45
source share
4 answers

I searched the same and found an existing way to do this without any custom codes or patterns. Use toEqual() .

+159
Jul 05 '13 at 8:45
source share

If you want to compare partial objects, you might think:

 describe("jasmine.objectContaining", function() { var foo; beforeEach(function() { foo = { a: 1, b: 2, bar: "baz" }; }); it("matches objects with the expect key/value pairs", function() { expect(foo).toEqual(jasmine.objectContaining({ bar: "baz" })); }); }); 

Wed jasmine.imtqy.com/partial-matching

+55
Feb 11 '15 at 7:50
source share

Its expected behavior, since the two instances of the object in JavaScript do not match.

 function Money(amount, currency){ this.amount = amount; this.currency = currency; this.sum = function (money){ return new Money(200, "USD"); } } var a = new Money(200, "USD") var b = a.sum(); console.log(a == b) //false console.log(a === b) //false 

For a clean test, you should write your own interlocutor that compares amount and currency :

 beforeEach(function() { this.addMatchers({ sameAmountOfMoney: function(expected) { return this.actual.currency == expected.currency && this.actual.amount == expected.amount; } }); }); 
+3
May 6 '13 at 19:36
source share

Your problem is veracity. You are trying to compare two different instances of an object that is true for correct equality (a == b) but does not correspond to strict equality (a === b). The comparator that uses jasmine is jasmine.Env.equals_ () , which seeks strict equality.

To accomplish what you need without changing your code, you can use regular equality by checking the truth with something like the following:

 expect(money1.sum() == money2.sum()).toBeTruthy(); 
-3
May 9 '13 at 5:46
source share



All Articles