Skip to content

Commit

Permalink
Add support for oneOf assertions
Browse files Browse the repository at this point in the history
  • Loading branch information
asmarques committed Dec 21, 2024
1 parent b458cc7 commit c38ab57
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
25 changes: 25 additions & 0 deletions chai-bignumber.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ module.exports = function (BigNumber) {
var isGreaterThanOrEqualTo = BigNumber.prototype.isGreaterThanOrEqualTo || BigNumber.prototype.greaterThanOrEqualTo;
var isLessThan = BigNumber.prototype.isLessThan || BigNumber.prototype.lessThan;
var isLessThanOrEqualTo = BigNumber.prototype.isLessThanOrEqualTo || BigNumber.prototype.lessThanOrEqualTo;
var oneOf = BigNumber.prototype.oneOf

return function (chai, utils) {
chai.Assertion.addProperty('bignumber', function () {
Expand Down Expand Up @@ -155,5 +156,29 @@ module.exports = function (BigNumber) {
value.toString()
);
});

// BigNumber.oneOf
chai.Assertion.overwriteMethod('oneOf', function (original) {
return function (list) {
if (utils.flag(this, 'bignumber')) {
var value = convert(this._obj);
var found = false
for (var i = 0; i < list.length; i++) {
if (value.isEqualTo(list[i])) {
found = true;
}
}
this.assert(
found,
'expected #{this} to be one of #{exp}',
'expected #{this} to not be one of #{exp}',
list
)
} else {
original.apply(this, arguments);
}
};
});

};
};
34 changes: 34 additions & 0 deletions test/chai-bignumber.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -723,4 +723,38 @@ describe('chai-bignumber', function () {
}
});
});

describe('oneOf', function () {
it('should find number in array', function () {
var tests = [
[new BigNumber(0), [new BigNumber(0), null, undefined]],
[1, [1, new BigNumber(2), 5]],
["3", [new BigNumber(3), 6, 7, "8"]],
[new BigNumber(4), [4, "10", new BigNumber(6)]],
[new BigNumber(5), ["5", new BigNumber(10)]],
];

for (var i = 0; i < tests.length; i++) {
var a = tests[i][0];
var l = tests[i][1];
a.should.be.bignumber.oneOf(l);
expect(a).to.be.bignumber.oneOf(l);
}
});

it('should not find number in array', function () {
var tests = [
[new BigNumber(0), []],
[10, [1, new BigNumber(2), 5]],
["3", [new BigNumber(30), null, undefined]],
];

for (var i = 0; i < tests.length; i++) {
var a = tests[i][0];
var l = tests[i][1];
a.should.not.be.bignumber.oneOf(l);
expect(a).to.not.be.bignumber.oneOf(l);
}
});
});
});

0 comments on commit c38ab57

Please sign in to comment.