首页 > 解决方案 > 比较数组时出现 Chai 断言错误

问题描述

在使用 Chai 时,我在尝试断言结果应该等于数组时遇到了一个奇怪的错误。

代码示例

   describe("compare array", function() {
        it("should return an empty array", function() {
            const result = getEmptyList(); // just a silly example
            expect(result).to.equal([]);
        });
   });

结果

  × compare array
    PhantomJS 2.1.1 (Windows 8.0.0)
  expected [ find: [Function] ] to equal [ find: [Function] ]
  AssertionError@C:/Code/example/node_modules/chai/chai.js:9449:24
  assert@C:/Code/example/node_modules/chai/chai.js:239:31
  assertEqual@C:/Code/example/node_modules/chai/chai.js:1387:18
  methodWrapper@C:/Code/example/node_modules/chai/chai.js:7824:30
  test/unit/utils/example.js:5:32

当我希望结果的长度为零时,它可以正常工作。任何人都可以分享一些关于为什么会发生这种情况的见解。为什么[ find: [Function] ]突然之间是预期的,而不是[]预期的?

我使用 Karma 作为我的测试运行器。

标签: javascriptunit-testingphantomjskarma-runnerchai

解决方案


由于一个数组永远不会===出现在另一个数组中,因此对于数组,您需要以下deep限定符equals

expect(result).to.deep.equal([]);
// --------------^^^^^

从文档:

导致链中所有.equal, .include, .members, .keys, 和.property断言使用深度相等而不是严格 ( ===) 相等。


推荐阅读