如何使用 chai.js 断言数组交集?

How to assert arrays intersection using chai.js?

我不喜欢这里的代码,是否有合适的方法在 chai 中找到交集,使用与查找超集类似的方法:expect([1,2]).to.contain.members([2])?

mocha.setup("bdd");

var intersection = function(arr1, arr2) {
  return arr1.filter(function(n) {
    return arr2.indexOf(n) != -1;
  });
};

describe("Test suite", function() {
    it("should find if arrays intersect", function() {
        chai.expect(intersection([1, 2], [2, 3])).not.to.be.empty;
    });
});

mocha.run();
<link href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.3.4/mocha.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.3.4/mocha.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.4.1/chai.min.js"></script>

<div id="mocha"></div>

要检查两个数组的交集,我建议您使用集合操作库。嘿,我刚好写了一个!这叫做亲和力,它是免费的。 (https://www.npmjs.com/package/affinity)。它是集合和关系运算符的库。它仍在开发中,但集合运算符工作得很好(有 400 个单元测试并且还在增加)。

在这种情况下,你会想做

var affinity = require('affinity');
var set1 = new affinity.Set({type : affinity.Integer, elements : [1, 2]});
var set2 = new affinity.Set({type : affinity.Integer, elements : [2, 3]});
chai.expect(set1.setIntersection(set2).elements()).not.to.be.empty;

// you also have setUnion, setProduct, ...

您可以使用流行的 lodash 库中的 _.intersection,如下所示:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>

...

chai.expect(_.intersection([1, 2], [2, 3])).not.to.be.empty

柴可以做到!

新语法

expect([1,2]).to.contain.oneOf([2,3]);

旧语法

expect([1,2]).to.include.any.members([2,3]);