smid
Catches errors and returns them. Useful for unit testing.
Written in TypeScript.
Install
npm install --save smid
Usage
Import the throws
function.
// ES6 / TypeScript // CommonJSconst throws = throws
throws
supports both sync functions and async functions. When catching sync errors, they are returned as-is. When catching Promise
rejections, a Promise
is returned that resolves to the error that caused the rejection.
It works by first trying to catch sync errors. If no error is thrown, it checks if the result is a Promise
(does it have a .then
property?), and attaches a rejection continuation.
Catching sync errors
// Sync functionconst err = console // boo!
Catching async
errors
// Async functionsconst err = await console // boo!
Catching rejections with plain Promise
s
// Async functions // Just passing in a Promise
If nothing throws...
// throws an error
API
throws
Signature
throws(fnOrPromise, [msg])
fnOrPromise
: A sync function, an async function, or aPromise
.msg
: If the function/promise is not throwing, an error is thrown instead. Usemsg
to override it's default message.
Why?
I find myself writing this function over and over for my testing needs. Jest's expect(...).toThrow()
is usually not enough; for example when catching errors from axios
, I want to inspect err.response
- Jest does not let me do that.
smid
mean?
What does It's Danish, it means throw
. 🇩🇰
Author
Jeff Hansen - @Jeffijoe