Should.js: check if two arrays contain the same lines

I have two arrays:

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

Is there anything special in shouldJS to check if these two arrays have the same elements? Something like

should(a).be.xyz(b)

who can test them? Here xyz is what I'm looking for.

+4
source share
2 answers

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

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

Note that it sort()works in place by modifying the original arrays.

+2
source

You can implement this with a function should Assertion.add. For instance:

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

All Articles