【问题标题】:Should.js: check if two arrays contain same stringsshould.js:检查两个数组是否包含相同的字符串
【发布时间】:2019-01-07 22:44:50
【问题描述】:

我有两个数组:

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

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

should(a).be.xyz(b)

那可以测试他们吗?在这里,xyz 就是我要找的。​​p>

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

    • 这个答案不正确。 .equal 使用 === 来表示引用相等。需要使用.eql。
    • @denbardadym 感谢您的注意,更新了我的答案。
    【解决方案2】:

    您可以使用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);
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多