数组内部严格相等

Strict equal inside of array

我想检查两个数组是否以相同的顺序包含相同的元素(不是深度等于)。

var a = { id: 1 }
var b = { id: 2 }
var c = { id: 3 }

var arr = [a, b, c]

expect(arr).to.______([a, b, c])               // true

expect(arr).to.______([a, c, b])               // false: different order
expect(arr).to.______([a, b])                  // false: missing element
expect(arr).to.______([a, b, c, { id: 4 }])    // false: extra element
expect(arr).to.______([a, b, { id: 3 }])       // false: different object reference

当然可以写

assert.strictEqual(arr.length, expected.length, "length");
for (let q = 0; q < arr.length; ++q) assert.strictEqual(arr[q], expected[q], `[${q}]`);

但我认为应该已经有一些方法了。

你可以使用 .ordered in conjunction with .members,像这样:

By default, members are compared using strict (===) equality. Add .deep earlier in the chain to use deep equality instead.

const expect = chai.expect;

const a = 1;
const b = 2;
const c = 3;

const input = [a, b, c];

expect(input).to.have.ordered.members([a, b, c]);
expect(input).to.not.have.ordered.members([b, a, c]);
expect(input).to.not.have.ordered.members([a, c, b]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.min.js"></script>