Jasmine JavaScript Testing - toBe vs toEqual


Arrays can be compared in 2 ways −

  • They refer to the same array object in memory.

  • They may refer to different objects but their contents are all equal.

Example

For case 1, jasmine provides the toBe method. This checks for reference. For example,

describe("Array Equality", () => {
   it("should check for array reference equility", () => {
      let arr = [1, 2, 3];
      let arr2 = arr
      // Runs successfully
      expect(arr).toBe(arr2);
      // Fails as references are not equal
      expect(arr).toBe([1, 2, 3]);
   });
});

Output

This will give the output −

1) Array Equality should check for array equility
Message:
   Expected [ 1, 2, 3 ] to be [ 1, 2, 3 ]. Tip: To check for deep equality, use .toEqual() instead of .toBe().

Example

For case 2 we can use the toEqual method and deep compare the arrays. For example,

describe("Array Equality", () => {
   it("should check for array reference equility", () => {
      let arr = [1, 2, 3];
      let arr2 = arr;
      // Runs successfully
      expect(arr).toEqual(arr2);
      // Runs successfully
      expect(arr).toEqual([1, 2, 3]);
   });
});

Output

This will give the output −

1 spec, 0 failures

Updated on: 02-Dec-2019

515 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements