Should.js: check if two arrays contain same strings

时间:2016-07-11 20:20:09

标签: javascript node.js unit-testing testing should.js

I have two arrays:

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

Is there anything special in shouldJS to test if these two arrays have same items? Anything Like

should(a).be.xyz(b)

that can test them? Here, xyz is what I am looking for.

3 个答案:

答案 0 :(得分:4)

A naive, but possibly sufficient solution would be to sort the arrays before comparing them:

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

Note that sort() works in-place, mutating the original arrays.

答案 1 :(得分:1)

You could implement this with should's Assertion.add feature. For example:

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);

答案 2 :(得分:0)

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);
});