对于Chai中的数组,相当于rspec =〜

时间:2012-07-16 13:37:02

标签: javascript testing mocha chai

Chai,匹配器是否具有等同于r specs =~(这意味着具有所有元素,但顺序无关紧要。

传递示例

[1, 2, 3].should =~ [2, 1, 3]

失败

[1, 2, 3].should =~ [1, 2]

3 个答案:

答案 0 :(得分:10)

您可以使用最新Chai版本中提供的members测试:

expect([4, 2]).to.have.members([2, 4]);
expect([5, 2]).to.not.have.members([5, 2, 1]);

答案 1 :(得分:5)

我认为没有,但你可以通过building a helper轻松创建一个:

var chai = require('chai'),
    expect = chai.expect,
    assert = chai.assert,
    Assertion = chai.Assertion

Assertion.addMethod('equalAsSets', function (otherArray) {
    var array = this._obj;

    expect(array).to.be.an.instanceOf(Array);
    expect(otherArray).to.be.an.instanceOf(Array);

    var diff = array.filter(function(i) {return !(otherArray.indexOf(i) > -1);});

    this.assert(
        diff.length === 0,
        "expected #{this} to be equal to #{exp} (as sets, i.e. no order)",
        array,
        otherArray
    );
});

expect([1,2,3]).to.be.equalAsSets([1,3,2]);
expect([1,2,3]).to.be.equalAsSets([3,2]);


flag

请注意这不是无序的相等测试,它设置为相等。任何一个数组都允许重复项目;这传递了,例如:expect([1,2,3]).to.be.equalAsSets([1,3,2,2]);

答案 2 :(得分:0)