51

Getting error while trying to check for empty array. I tried using:

Case 1: By initializing as an array

expect(fixture.componentInstance.dataSource).toBe([]);

Case 2: By initializing as an array

let expectedAry = new Array;
expect(fixture.componentInstance.dataSource).toBe(expectedAry);

Both the case have the same error:

Expected [  ] to be [  ].

Arrays can also be checked by their length, the following works fine

expect(fixture.componentInstance.dataSource.length).toEqual(0); 

0 length is an option, but not sure if that is the right way to check whether an array is empty. Do we have a better option for checking whether an array is empty?

yurzui
  • 205,937
  • 32
  • 433
  • 399
Kailas
  • 7,350
  • 3
  • 47
  • 63

4 Answers4

95

toBe doesn't check the contents of the array, it only checks if the references are the same.

expect([1]).toBe([1]) will fail because the references are different.

You should use toEqual, which has some smarts to check the array contents as opposed to just doing a reference comparison.

Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
30

Use toHaveSize matcher:

expect(array).toHaveSize(0);

It's strongly recommended to use because the error messages you get with it are much better (e.g. Error: Expected array to have size 0)

Coming with Jasmine 3.6: release docs

t_dom93
  • 10,226
  • 1
  • 52
  • 38
3

Use .toHaveLength to check that an object has a .length property and it is set to a certain numeric value.

This is especially useful for checking arrays or strings size.

expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);

source https://jestjs.io/docs/expect#tohavelengthnumber

2

You can try like this -

expect(component.XYZ.length).toEqual(0);