Should.js:检查两个数组是否包含相同的字符串

Should.js: check if two arrays contain same strings

我有两个数组:

var a = ['a', 'as', 'sa'];
var b = ['sa', 'a', 'as'];

shouldJS 有什么特别的东西可以测试这两个数组是否有相同的项目?任何类似

should(a).be.xyz(b)

那可以考他们吗?在这里,xyz 是我要找的。

一个简单但可能足够的解决方案是在比较数组之前对它们进行排序:

should(a.sort()).be.eql(b.sort())

请注意 sort() works in-place,改变原始数组。

您可以使用 shouldAssertion.add 功能来实现这一点。例如:

var a = ['a', 'as', 'sa'];
var b = ['sa', 'a', 'as'];

should.Assertion.add('haveSameItems', function(other) {
  this.params = { operator: 'to be have same items' };

  this.obj.forEach(item => {
    //both arrays should at least contain the same items
    other.should.containEql(item);
  });
  // both arrays need to have the same number of items
  this.obj.length.should.be.equal(other.length);
});

//passes
a.should.haveSameItems(b);

b.push('d');

// now it fails
a.should.haveSameItems(b);

Michael 代码的略微改进版本:

should.Assertion.add("haveSameItems", function (other) {
    this.params = { operator: "to be have same items" };

    const a = this.obj.slice(0);
    const b = other.slice(0);

    function deepSort(objA, objB) {
        const a = JSON.stringify(objA);
        const b = JSON.stringify(objB);

        return (a < b ? -1 : (a > b ? 1 : 0));
    }

    a.sort(deepSort);
    b.sort(deepSort);

    a.should.be.deepEqual(b);
});