Javascript 预期 [ ] 为 [ ] Jasmine,如何检查空数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46543562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Expected [ ] to be [ ] Jasmine, how to check empty array
提问by Kailas
Getting error while trying to check for empty array. I tried using:
尝试检查空数组时出错。我尝试使用:
Case 1: By initializing as an array
案例 1:通过初始化为数组
expect(fixture.componentInstance.dataSource).toBe([]);
Case 2: By initializing as an array
案例 2:通过初始化为数组
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?
0 长度是一个选项,但不确定这是否是检查数组是否为空的正确方法。我们是否有更好的选择来检查数组是否为空?
回答by Evan Trimboli
toBedoesn't check the contents of the array, it only checks if the references are the same.
toBe不检查数组的内容,它只检查引用是否相同。
expect([1]).toBe([1])will fail because the references are different.
expect([1]).toBe([1])将失败,因为引用不同。
You should use toEqual, which has some smarts to check the array contents as opposed to just doing a reference comparison.
您应该使用toEqual,它有一些智能来检查数组内容,而不仅仅是进行引用比较。

