Skip to content

Commit 03913cb

Browse files
authored
Merge pull request #1242 from voliva/contains-oneOf
(feat): expect value to contain oneOf
2 parents 8dc92d8 + 9d2f6dc commit 03913cb

File tree

2 files changed

+32
-7
lines changed

2 files changed

+32
-7
lines changed

lib/chai/core/assertions.js

+26-7
Original file line numberDiff line numberDiff line change
@@ -3118,6 +3118,14 @@ module.exports = function (chai, _) {
31183118
* expect(1).to.equal(1); // Recommended
31193119
* expect(1).to.not.be.oneOf([2, 3, 4]); // Not recommended
31203120
*
3121+
* It can also be chained with `.contain` or `.include`, which will work with
3122+
* both arrays and strings:
3123+
*
3124+
* expect('Today is sunny').to.contain.oneOf(['sunny', 'cloudy'])
3125+
* expect('Today is rainy').to.not.contain.oneOf(['sunny', 'cloudy'])
3126+
* expect([1,2,3]).to.contain.oneOf([3,4,5])
3127+
* expect([1,2,3]).to.not.contain.oneOf([4,5,6])
3128+
*
31213129
* `.oneOf` accepts an optional `msg` argument which is a custom error message
31223130
* to show when the assertion fails. The message can also be given as the
31233131
* second argument to `expect`.
@@ -3136,16 +3144,27 @@ module.exports = function (chai, _) {
31363144
if (msg) flag(this, 'message', msg);
31373145
var expected = flag(this, 'object')
31383146
, flagMsg = flag(this, 'message')
3139-
, ssfi = flag(this, 'ssfi');
3147+
, ssfi = flag(this, 'ssfi')
3148+
, contains = flag(this, 'contains');
31403149
new Assertion(list, flagMsg, ssfi, true).to.be.an('array');
31413150

3142-
this.assert(
3151+
if (contains) {
3152+
this.assert(
3153+
list.some(possibility => expected.indexOf(possibility) > -1)
3154+
, 'expected #{this} to contain one of #{exp}'
3155+
, 'expected #{this} to not contain one of #{exp}'
3156+
, list
3157+
, expected
3158+
);
3159+
} else {
3160+
this.assert(
31433161
list.indexOf(expected) > -1
3144-
, 'expected #{this} to be one of #{exp}'
3145-
, 'expected #{this} to not be one of #{exp}'
3146-
, list
3147-
, expected
3148-
);
3162+
, 'expected #{this} to be one of #{exp}'
3163+
, 'expected #{this} to not be one of #{exp}'
3164+
, list
3165+
, expected
3166+
);
3167+
}
31493168
}
31503169

31513170
Assertion.addMethod('oneOf', oneOf);

test/expect.js

+6
Original file line numberDiff line numberDiff line change
@@ -3282,6 +3282,12 @@ describe('expect', function () {
32823282
var threeFour = [3, [4]];
32833283
expect(threeFour).to.be.oneOf([1, 2, threeFour]);
32843284

3285+
expect([1, 2]).to.contain.oneOf([4,2,5]);
3286+
expect([3, 4]).to.not.contain.oneOf([2,1,5]);
3287+
3288+
expect('The quick brown fox jumps over the lazy dog').to.contain.oneOf(['cat', 'dog', 'bird']);
3289+
expect('The quick brown fox jumps over the lazy dog').to.not.contain.oneOf(['elephant', 'pigeon', 'lynx']);
3290+
32853291
err(function () {
32863292
expect(1).to.be.oneOf([2, 3], 'blah');
32873293
}, "blah: expected 1 to be one of [ 2, 3 ]");

0 commit comments

Comments
 (0)