Difference between .toBe() and .toEqual() - Jasmine Karma testcases

11,160

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's isEqual 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

Share:
11,160
Amir Suhail
Author by

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, 2022

Comments

  • Amir Suhail
    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
    David Barker about 8 years
    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. github.com/jasmine/jasmine/blob/master/src/core/matchers/… check out the eq function that toEqual uses. This allows for object value matching, array value matching etc.
  • maioman
    maioman about 8 years
    @DavidBarker you're right , I simplified the concept a bit too much...