Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent to rspec =~ for arrays in Chai

Does Chai, matchers have an equilivent to rspecs =~ (which means has all elements but order doesn't matter.

Passing example

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

Failing

[1, 2, 3].should =~ [1, 2]
like image 564
austinbv Avatar asked Jul 16 '12 13:07

austinbv


2 Answers

You can use members test that is available in the latest Chai version:

expect([4, 2]).to.have.members([2, 4]);
expect([5, 2]).to.not.have.members([5, 2, 1]);
like image 81
Miroslav Bajtoš Avatar answered Sep 18 '22 22:09

Miroslav Bajtoš


I don't think there is, but you can create one easily by 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

Be aware that this isn't an unordered equality test, it is set equality. Duplicate items are permitted in either array; this passes, for instance: expect([1,2,3]).to.be.equalAsSets([1,3,2,2]);

like image 42
fresskoma Avatar answered Sep 20 '22 22:09

fresskoma