使用 Chai 断言比较两个对象

Moh*_*een 11 mocha.js node.js chai

我有两个混合订单数组

const actualResult = [
  {
    start: '30',
    end: '50',
    locations: ['loc1', 'loc2'],
  },
  {
    start: '20',
    end: '40',
    locations: ['loc3', 'loc4'],
  },
];

const expectedResult = [
  {
    start: '20',
    end: '40',
    locations: ['loc4', 'loc3'],
  },
  {
    start: '30',
    end: '50',
    locations: ['loc2', 'loc1'],
  },
];
Run Code Online (Sandbox Code Playgroud)

我编写了下面的代码来使用 chai 断言来比较它们

describe('test1', function () {
  it('expect test', function () {
    expect(actualResult).to.have.length(expectedResult.length);
    for (b of expectedResult) {
      var found = false;
      for (d of actualResult) {
        if (b.start == d.start && b.end == d.end) {
          expect(b.locations).to.have.deep.members(d.locations);
          found = true;
        }
      }
      expect(found).to.be.true;
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

效果很好,但我有兴趣知道是否有任何直接的柴断言可以在一行中执行,例如

expect(actualResult).to.have.all.nested.members(expectedResult);
Run Code Online (Sandbox Code Playgroud)

或更好的建议。

sli*_*wp2 10

您可以使用deep-equal-in-any-order插件。

\n
\n

Chai 插件可将对象和数组与任意顺序的数组(包括嵌套数组)进行深度相等匹配。

\n
\n
\n

它的工作方式与 类似,deep.equal但它不检查数组的顺序(在任何级别的嵌套对象和数组)。数组元素可以是任何 JS 实体(boolean、null、number、string、object、array\xe2\x80\xa6)。

\n
\n

例如

\n
const deepEqualInAnyOrder = require(\'deep-equal-in-any-order\');\nconst chai = require(\'chai\');\n\nchai.use(deepEqualInAnyOrder);\n\nconst { expect } = chai;\n\ndescribe(\'\', () => {\n  it(\'should pass\', () => {\n    const actualResult = [\n      {\n        start: \'30\',\n        end: \'50\',\n        locations: [\'loc1\', \'loc2\'],\n      },\n      {\n        start: \'20\',\n        end: \'40\',\n        locations: [\'loc3\', \'loc4\'],\n      },\n    ];\n\n    const expectedResult = [\n      {\n        start: \'20\',\n        end: \'40\',\n        locations: [\'loc4\', \'loc3\'],\n      },\n      {\n        start: \'30\',\n        end: \'50\',\n        locations: [\'loc2\', \'loc1\'],\n      },\n    ];\n\n    expect(actualResult).to.deep.equalInAnyOrder(expectedResult);\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

测试结果:

\n
  59308311\n    \xe2\x9c\x93 should pass\n\n\n  1 passing (23ms)\n
Run Code Online (Sandbox Code Playgroud)\n