对于Chai中的数组,等效于rspec=~

Equivalent to rspec =~ for arrays in Chai

本文关键字:rspec Chai 数组 对于      更新时间:2023-09-26

Chai,matchers与rspecs =~有一个等式吗(这意味着拥有所有元素,但顺序无关紧要。

正在传递的示例

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

失败

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

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

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

我认为没有,但你可以通过构建一个助手来轻松创建一个:

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

http://www.rubydoc.info/gems/rspec-expectations/frames#Collection_membership

expect([4, 2]).to match_array([2, 4])