-
-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'yousef-s-predicate-instance-of'
- Loading branch information
Showing
3 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import 'mocha'; | ||
import { given } from 'mocha-testdata'; | ||
|
||
import { ensure, isInstanceOf, TinyType } from '../../src'; | ||
import { expect } from '../expect'; | ||
|
||
describe('predicates', () => { | ||
|
||
/** @test {isInstanceOf} */ | ||
describe('::isInstanceOf', () => { | ||
class Birthday extends TinyType { | ||
constructor(public readonly value: Date) { | ||
super(); | ||
|
||
ensure('Birthday', value, isInstanceOf(Date)); | ||
} | ||
} | ||
|
||
it('ensures that the argument is an instance of Date', () => { | ||
expect(() => new Birthday(new Date())).to.not.throw; // tslint:disable-line:no-unused-expression | ||
}); | ||
|
||
given( | ||
'2018-10-10', | ||
undefined, | ||
null, | ||
{}, | ||
'string', | ||
).it('complains if the value does not meet the predicate', (value: any) => { | ||
expect(() => new Birthday(value)).to.throw(`Birthday should be instance of Date`); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import { Predicate } from './Predicate'; | ||
|
||
/** | ||
* @desc Ensures that the `value` is an instance of `type` | ||
* | ||
* @example | ||
* import { ensure, isInstanceOf, TinyType } from 'tiny-types'; | ||
* | ||
* class Birthday extends TinyType { | ||
* constructor(public readonly value: Date) { | ||
* ensure('Date', value, isInstanceOf(Date)); | ||
* } | ||
* } | ||
* | ||
* @param {Constructor<T>} type | ||
* @returns {Predicate<T>} | ||
*/ | ||
export function isInstanceOf<T>(type: { new (...args: any[]): T }): Predicate<T> { | ||
return Predicate.to(`be instance of ${type.name}`, (value: T) => value instanceof type); | ||
} |