Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
[api] Add eitherOfType/oneOfType assertion
  • Loading branch information
Jonathan Keslin committed Mar 31, 2017
1 parent 67b166f commit 15d5d7d
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
11 changes: 11 additions & 0 deletions README.md
Expand Up @@ -49,6 +49,7 @@ not commited to GitHub.
- [Keywords](#keywords)
- [API](#api)
- [a, an](#a-an)
- [eitherOfType, oneOfType](#eitheroftype-oneoftype)
- [instanceOf, instanceof, inherits, inherit](#instanceof-instanceof-inherits-inherit)
- [include, includes, contain, contains](#include-includes-contain-contains)
- [ok, okay, truthy, truely](#ok-okay-truthy-truely)
Expand Down Expand Up @@ -264,6 +265,16 @@ assume([]).is.a('array');

[`instanceof` is a keyword and might cause cross browser issues](#keywords)

#### eitherOfType, oneOfType

Asserts if the given value is one of the acceptable types.

The same caveats regarding `typeof` apply as described in [a, an](#a-an).

```js
assume([]).is.oneOfType(['array'], ['string']);
```

#### instanceOf, instanceof, inherits, inherit

Asserts that the value is instanceof the given constructor.
Expand Down
19 changes: 19 additions & 0 deletions index.js
Expand Up @@ -308,6 +308,25 @@ Assert.add('a, an', function typecheck(of, msg) {
return this.test(value === of, msg, expect);
});

/**
* Asserts if the given value is the correct type from a list of types.
* The same caveats regarding `typeof` apply as described in `a`, `an`.
*
* @param {String[]} ofs Acceptable types to check against
* @param {String} msg Reason of failure.
* @returns {Assert}
* @api public
*/
Assert.add('eitherOfType, oneOfType', function multitypecheck(ofs, msg) {
var value = type(this.value)
, expect = format('`%j` (%s) to @ be a %s', this.value, value, ofs.join(' or a '));

return this.test(ofs.some(function(of) {
of = of.toString().toLowerCase();
return of === value;
}), msg, expect);
});

/**
* Asserts that the value is instanceof the given constructor.
*
Expand Down
22 changes: 22 additions & 0 deletions test/test.js
Expand Up @@ -235,6 +235,28 @@ describe('Assertions', function assertions() {
});
});

describe('#eitherOfType', function () {
it('is aliased as `eitherOfType`, `oneOfType`', function () {
var x = assume('foo');

if (x.eitherOfType !== x.oneOfType) throw new Error('Incorrectly aliased');
});

it('classifies a valid type', function (next) {
assume([]).to.be.eitherOfType(['string', 'array']);

try { assume({}).to.be.eitherOfType(['string', 'array']); }
catch (e) { next(); }
});

it('supports negation properly', function (next) {
assume([]).to.not.be.eitherOfType(['string', 'object'])

try { assume({}).to.not.be.eitherOfType(['string', 'object']); }
catch (e) { next(); }
});
});

describe('#instanceof', function () {
function Foo() {}
function Bar() {}
Expand Down

0 comments on commit 15d5d7d

Please sign in to comment.