I am using Jasmine karma test case for a while and found tests failing sometime because of using .toBe() instead of .toEqual(). What is the difference between .toBe() and .toEqual() and when you use these?
toBe()
comparison is strict (ex.: obj1 === obj2
)
if comparing two objects the identity of the objects is taken in consideration.
while toEqual()
takes only value of the entries in consideration ( it compares object like underscore's isEqual
method ).
here is an example that explains the difference between both of them
describe("Included matchers:", function() {
it("The 'toBe' matcher compares with ===", function() {
var a = 12;
var b = a;
expect(a).toBe(b);
expect(a).not.toBe(null);
});
describe("The 'toEqual' matcher", function() {
it("works for simple literals and variables", function() {
var a = 12;
expect(a).toEqual(12);
});
it("should work for objects", function() {
var foo = {
a: 12,
b: 34
};
var bar = {
a: 12,
b: 34
};
expect(foo).toEqual(bar);
});
});
});
you can find more details about other Matchers in the official website
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