Skip to content

Commit

Permalink
Merge pull request #1242 from voliva/contains-oneOf
Browse files Browse the repository at this point in the history
(feat): expect value to contain oneOf
  • Loading branch information
vieiralucas committed Jun 28, 2019
2 parents 8dc92d8 + 9d2f6dc commit 03913cb
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
33 changes: 26 additions & 7 deletions lib/chai/core/assertions.js
Original file line number Diff line number Diff line change
Expand Up @@ -3118,6 +3118,14 @@ module.exports = function (chai, _) {
* expect(1).to.equal(1); // Recommended
* expect(1).to.not.be.oneOf([2, 3, 4]); // Not recommended
*
* It can also be chained with `.contain` or `.include`, which will work with
* both arrays and strings:
*
* expect('Today is sunny').to.contain.oneOf(['sunny', 'cloudy'])
* expect('Today is rainy').to.not.contain.oneOf(['sunny', 'cloudy'])
* expect([1,2,3]).to.contain.oneOf([3,4,5])
* expect([1,2,3]).to.not.contain.oneOf([4,5,6])
*
* `.oneOf` accepts an optional `msg` argument which is a custom error message
* to show when the assertion fails. The message can also be given as the
* second argument to `expect`.
Expand All @@ -3136,16 +3144,27 @@ module.exports = function (chai, _) {
if (msg) flag(this, 'message', msg);
var expected = flag(this, 'object')
, flagMsg = flag(this, 'message')
, ssfi = flag(this, 'ssfi');
, ssfi = flag(this, 'ssfi')
, contains = flag(this, 'contains');
new Assertion(list, flagMsg, ssfi, true).to.be.an('array');

this.assert(
if (contains) {
this.assert(
list.some(possibility => expected.indexOf(possibility) > -1)
, 'expected #{this} to contain one of #{exp}'
, 'expected #{this} to not contain one of #{exp}'
, list
, expected
);
} else {
this.assert(
list.indexOf(expected) > -1
, 'expected #{this} to be one of #{exp}'
, 'expected #{this} to not be one of #{exp}'
, list
, expected
);
, 'expected #{this} to be one of #{exp}'
, 'expected #{this} to not be one of #{exp}'
, list
, expected
);
}
}

Assertion.addMethod('oneOf', oneOf);
Expand Down
6 changes: 6 additions & 0 deletions test/expect.js
Original file line number Diff line number Diff line change
Expand Up @@ -3282,6 +3282,12 @@ describe('expect', function () {
var threeFour = [3, [4]];
expect(threeFour).to.be.oneOf([1, 2, threeFour]);

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

expect('The quick brown fox jumps over the lazy dog').to.contain.oneOf(['cat', 'dog', 'bird']);
expect('The quick brown fox jumps over the lazy dog').to.not.contain.oneOf(['elephant', 'pigeon', 'lynx']);

err(function () {
expect(1).to.be.oneOf([2, 3], 'blah');
}, "blah: expected 1 to be one of [ 2, 3 ]");
Expand Down

0 comments on commit 03913cb

Please sign in to comment.