5

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?

Amir Suhail
  • 1,284
  • 3
  • 12
  • 31

3 Answers3

4
  • 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 ).

maioman
  • 18,154
  • 4
  • 36
  • 42
  • `toEqual` does not do an `==` check. `toEqual` is comparitively similar to underscores `isEqual` 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. https://github.com/jasmine/jasmine/blob/master/src/core/matchers/matchersUtil.js check out the `eq` function that `toEqual` uses. This allows for object value matching, array value matching etc. – David Barker May 04 '16 at 10:12
  • @DavidBarker you're right , I simplified the concept a bit too much... – maioman May 04 '16 at 10:23
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

Mohamed NAOUALI
  • 2,092
  • 1
  • 23
  • 29
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])
filype
  • 8,034
  • 10
  • 40
  • 66