diff --git a/lib/chai/core/assertions.js b/lib/chai/core/assertions.js index 26404f5a8..4d3fb821c 100644 --- a/lib/chai/core/assertions.js +++ b/lib/chai/core/assertions.js @@ -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`. @@ -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); diff --git a/test/expect.js b/test/expect.js index 6c87a8e84..d7493c38a 100644 --- a/test/expect.js +++ b/test/expect.js @@ -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 ]");