Difference between .toBe() and .toEqual() - Jasmine Karma testcases
Solution 1
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'sisEqual
method ).
Solution 2
In my experience, toBe
is used for comparing strings, boolean values, for example:
expect(enabled).toBe(true)
expect(user.name).toBe('Bob')
toEqual
is more suitable for comparing arrays or objects. For example:
expect(myArray).toEqual([1,2,3])
Solution 3
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
![Amir Suhail](https://i.stack.imgur.com/N4Mvx.png?s=256&g=1)
Amir Suhail
By morning I'll write testcases, by evening I'll finish the code and by night I'll sleep :P :D
Updated on June 14, 2022Comments
-
Amir Suhail about 2 years
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?
-
David Barker about 8 years
toEqual
does not do an==
check.toEqual
is comparitively similar to underscoresisEqual
method, it checks for assymetric matches between a and b to start with, it also allows you to give an array of your own custom matching functions as well as checking for inequality between values. github.com/jasmine/jasmine/blob/master/src/core/matchers/… check out theeq
function thattoEqual
uses. This allows for object value matching, array value matching etc. -
maioman about 8 years@DavidBarker you're right , I simplified the concept a bit too much...