0.4.3 • Published 3 years ago

@carnesen/run-and-catch v0.4.3

Weekly downloads
606
License
MIT
Repository
github
Last release
3 years ago

@carnesen/run-and-catch

Build Status npm version badge github stars badge

Calls a function and throws if it doesn't and doesn't if it does. Useful for unit testing throws in async functions.

Install

$ npm install @carnesen/run-and-catch

This package includes runtime JavaScript files (ES2017 + CommonJS) and their corresponding TypeScript type declarations.

Usage

Here is an example of a unit test for an async function that throws:

import { runAndCatch } from '@carnesen/run-and-catch';

async function myFunc(message: string) {
   if (message.startsWith('_')) {
      throw new Error('Message is not allowed to start with _');
   }
}

describe(myFunc.name, () => {
   it('throws "not allowed" if message starts with _', async () => {
      // THE CLUNKY WAY. DON'T DO IT LIKE THIS.
      try {
         await myFunc('_foo');
         throw new Error('The previous line should have thrown');
      } catch (exception) {
         expect(exception.message).toMatch('not allowed');
      }

      // THE BETTER WAY WITH @carnesen/run-and-catch
      const exception = await runAndCatch(myFunc, '_foo');
      expect(exception.message).toMatch('not allowed');
      expect(exception.code).toBe('BAD_MESSAGE');
   });
});

runAndCatch is intelligently typed in the sense that the TypeScript compiler would complain if you tried this:

// NOT OK
runAndCatch(myFunc, 3);
// ^^ error TS2345: Argument of type '3' is not assignable to parameter of type 'string'.

runAndCatch throws if the function does not throw:

// throws "Expected the provided function to throw."
runAndCatch(myFunc, 'hello');

This package also exports a synchronous function runner, runAndCatchSync that is just like runAndCatch except it does not await on the result of function call.

More information

This micro-package has a half dozen unit tests with 100% coverage. Check out those tests for more examples. If you encounter any bugs or have any questions or feature requests, please don't hesitate to file an issue or submit a pull request on this project's repository on GitHub.

Related

License

MIT © Chris Arnesen

0.4.3

3 years ago

0.4.2

3 years ago

0.4.1

4 years ago

0.4.0

4 years ago

0.3.0

4 years ago

0.1.2

4 years ago

0.2.0

4 years ago

0.1.1

4 years ago

0.1.0

5 years ago

0.0.0

5 years ago

0.0.0-0

5 years ago