smid
TypeScript icon, indicating that this package has built-in type declarations

0.1.1 • Public • Published

smid

Catches errors and returns them. Useful for unit testing.

Written in TypeScript.

npm dependency Status devDependency Status Build Status Coveralls npm npm Built with TypeScript

Install

npm install --save smid

Usage

Import the throws function.

// ES6 / TypeScript
import { throws } from 'smid'
 
// CommonJS
const throws = require('smid').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 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 error

API

throws

Signature

  • throws(fnOrPromise, [msg])
    • fnOrPromise: A sync function, an async function, or a Promise.
    • msg: If the function/promise is not throwing, an error is thrown instead. Use msg 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.

What does smid mean?

It's Danish, it means throw. 🇩🇰

Author

Jeff Hansen - @Jeffijoe

Readme

Keywords

none

Package Sidebar

Install

npm i smid

Weekly Downloads

286

Version

0.1.1

License

MIT

Last publish

Collaborators

  • jeffijoe