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

2019-02-08 14:11发布

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?

1条回答
乱世女痞
2楼-- · 2019-02-08 14:55

toBe is an explicit reference check.

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.

查看更多
登录 后发表回答