toEqual() vs toBe()

In this lesson, we take a look into the difference between the Jasmine toEqual() and toBe() matchers. We consider a JavaScript file test.js, containing two variables a and b, and to them we assign two equal numeric values


var a = 1;
var b = 1;

or equal string values


var a = 'Hello';
var b = 'Hello';

or equal Boolean values


var a = true;
var b = true;

And in the spec file test.spec.js (inside the spec directory), we write the specs in Jasmine (below) to check the equality of a and b, using the toEqual()


describe("a", function() {
  it("is equal to b", function() {
    expect(a).toEqual(b);
  });
});

and toBe() matchers respectively


describe("a", function() {
  it("is equal to b", function() {
    expect(a).toBe(b);
  });
});

On execution, the above Jasmine specs will pass for numbers, strings and even Boolean values. So, for primitive values, both toEqual() and toBe() matchers behave the same.

But the difference can be seen in object level testing. For example, assign the array ['1'] to both a and b (array is of type object)


var a = ['1'];
var b = ['1'];

On running the specs, the second test based on the toBe() matcher will fail.

This is because the toBe() Jasmine matcher is basically the === operator (equal value and equal type) as can be found in the link https://github.com/jasmine/jasmine/blob/master/src/core/matchers/toBe.js

Therefore, the expectation


expect(a).toBe(b);

can also be written as


expect(a === b).toBe(true);