'Expected [ ] to be [ ] Jasmine, how to check empty array

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?



Solution 1:[1]

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

Solution 2:[2]

You can try like this -

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Kanchan Tyagi