argsy
awesome argument assertion
Made with ❤ at @outlandish
Argument-oriented assertions...
- assertions that name offending arguments
- collects assertion failures and groups them in a single error
- reports function name, location, and clean stack trace
- support for optional arguments
Example
Before
{ if typeof name !== 'string' || !namelength throw 'expecting name to be non-empty string' else if message && typeof message !== 'string' throw 'expecting message to be string' console} //=> Error: expecting name to be non-empty string
After
{ optional console}//=> Error: Failed argument assertions in call to "hello" at C:/hello.js:1:// - expecting name to be non-empty string
Install
npm install --save argsy
yarn add argsy
Import
// ES2015
// CommonJSvar assert =
API
assert.{method}(val[, subject][, name[, name2]])
Assert val
is of type indicated by method
(see below).
- val {*} value to assert
- subject {*} (optional) subject of assert
- name {String} name to report in error message
- nam2 {String} (optional) name of subject
No return value.
AssertionInstance
assert([name]) : AssertionInstance
Create a new assertion instance.
- name {String} (optional) name of the assertion instance
Returns an AssertionInstance
.
AssertionInstance.{method}(val[, subject][, name[, name2]])
Assert val
is of type indicated by method
(see below).
- val {*} value to assert
- subject {*} (optional) subject of assert
- name {String} name to report in error message
- nam2 {String} (optional) name of subject
Returns the AssertionInstance
.
Methods
ok
notOk
str
obj
nonEmptyStr
num
sym
int
bool
undef
null
nan
elem (use subject arg)
key (use subject arg)
AssertionInstance.optional.{method}()
Assert an optional value.
Shares the same API as AssertionInstance.method
(see above).
Returns the AssertionInstance
.
AssertionInstance.$eval()
Assert the arguments.
This should be called last in the chain of assertion declarations.
More Examples
examples/report.js
Evaluates all assertions, groups them, and reports all failures.
Note call to $eval
at the end.
{ return a + b} const a = Numberprocessargv1const b = Numberprocessargv2const result = console
Good
$ node examples/add.js 1 21+2=3
Bad
$ node add.jsError: Failed argument assertions in call to "add" at C:/argsy/examples/report.js:10: - expecting a to be number - expecting b to be number at Function.evaluate at add at Object.<anonymous>
examples/spongebob.js
Stops and throws at first failed assertion.
{ assert optional console} //=> Spongebob is a sponge //=> Error: Expecting name to be a non-empty string //=> Spongebob is a crabby patty flipper
Contributing
All pull requests and issues welcome!
If you're not sure how, check out the great video tutorials on egghead.io!
License
MIT © Sam Gluck