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

时间:2021-05-20 12:15:13

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

shouldJS有什么特别的东西可以测试这两个数组是否有相同的项目吗?什么都喜欢

should(a).be.xyz(b)

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

那可以测试一下吗?在这里,xyz是我正在寻找的。

2 个解决方案

#1


2  

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.

请注意,sort()可以就地工作,改变原始数组。

#2


1  

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

您可以使用should的Assertion.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);

#1


2  

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.

请注意,sort()可以就地工作,改变原始数组。

#2


1  

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

您可以使用should的Assertion.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);