smid v0.1.1
smid
Catches errors and returns them. Useful for unit testing.
Written in TypeScript.
Install
npm install --save smidUsage
Import the throws function.
// ES6 / TypeScript
import { throws } from 'smid'
// CommonJS
const throws = require('smid').throwsthrows 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 function
const err = throws(() => {
// ... some code that throws
throw new Error('boo!')
})
console.log(err.message) // boo!Catching async errors
// Async functions
const err = await throws(async () => {
await someStuff()
throw new Error('boo!')
})
console.log(err.message) // boo!Catching rejections with plain Promises
// Async functions
throws(() => {
return Promise.reject(new Error('boo!'))
}).then((err) => {
console.log(err.message) // boo!
})
// Just passing in a Promise
throws(Promise.reject(new Error('boo!')))
.then((err) => {
console.log(err.message) // boo!
})If nothing throws...
throws(() => 'All is hell that ends well')
// throws an errorAPI
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. Usemsgto 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.
What does smid mean?
It's Danish, it means throw. 🇩🇰
Author
Jeff Hansen - @Jeffijoe