npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

catch-and-match

v0.2.16

Published

Assert an error thrown (a)synchronously by a function.

Downloads

12

Readme

catch-and-match

Assert an error thrown (a)synchronously by a function.

Made with ❤ at @outlandish

js-standard-style

Install

npm install catch-and-match --save-dev

Catch and Match

Sometimes asserting that something just throws isn't enough. catch-and-match allows you to assert that a function which should throw throws the error you expect. This is particularly useful for testing functions that produce error messages which provide useful feedback (the best kind of functions!).

Assert error is an instance of Error (e.g. ReferenceError)

Replace a traditional try/catch

it('should throw a ReferenceError', function (cb) {
    // Without catch-and-match                   |  // With catch-and-match
    try {                                        |  catchAndMatch(
        String(a);  // a === undefined           |      () => String(a),
    } catch (err) {                              |      ReferenceError,
        if (!(err instanceof ReferenceError)) {  |      cb);
            cb(new Error());                     |
            return;                              |  // Or return a Promise
        }                                        |  return catchAndMatch(
        cb();                                    |      () => String(a),
    }                                            |      ReferenceError);
});

Replace catching a rejected Promise

it('should throw a ReferenceError', function () {
    // Without catch-and-match                       |  // With catch-and-match
    return someFuncThatRejects()                     |  catchAndMatch(
        .catch((err) => {                            |      someFuncThatRejects,
            if (!(err instanceof ReferenceError)) {  |      ReferenceError);
                throw err;                           |
            }                                        |
        });                                          |
});

Assert error message using a regular expression

it('should throw with error message containing "not defined"', function (cb) {
    return catchAndMatch(() => String(a), /not defined/);
});

Assert error message using a string

it('should throw with error message "a is not defined"', function (cb) {
    return catchAndMatch(() => String(a), 'a is not defined');
});

Assert error matches custom validation

it('should throw with error message "a is not defined"', function (cb) {
    return catchAndMatch(() => String(a), function (err) {
        return err.message === 'a is not defined';
    });
});

Usage

catchAndMatch(fn, matcher[, cb]) : Promise

fn {Function} function that should throw traditionally or within a Promise

  • if fn does not throw, catch-and-match returns a rejected Promise and calls cb with an error as its first argument
  • if fn throws the error is tested against matcher (see below)

matcher {RegExp|String|Function|Error} method of inspecting error:

  • a Function is passed the error and should return true when the test should pass
  • a String is turned to simple RegExp (new RegExp(str))
  • a RegExp is tested against the error message (re.test(err.message))
  • an Error (any constructor that inherits from Error) is matched against the error (e.g. err.constructor === ReferenceError)

cb {Function} (optional) error-first callback

Examples

If in your tests you are placing function invocations within a try block to purposefully cause them to throw and then calling the test's 'done' callback within the catch after inspecting the error, you can replace this pattern with a catchAndMatch:

Example function

function log (str) {
    if (typeof str !== 'string') {
        throw new Error('str should be a string');
    }
    console.log(str);
}

Before

it('should throw an error without correct arguments', function (cb) {
    try {
        // make the function throw by passing an illegal argument
        log(10);
    } catch (err) {
        // inspect that the error thrown has the right message
        if (err.message.includes('should be a string')) {
            cb();
            return;
        }
        // the wrong error was thrown, so fail the test
        cb(new Error('wrong error thrown'));
    }
});

After, using Promise

// Passes with string matcher
it('should throw an error without correct arguments', function () {
    return catchAndMatch(log.bind(undefined, 'hello'), /should be a string/);
});

// Passes with function matcher
it('should throw an error without correct arguments', function () {
    return catchAndMatch(log.bind(undefined, 10), function (err) {
        return err.includes('should be a string');
    });
});

After, using callback

// Fails with RegExp matcher
it('should throw an error without correct arguments', function (cb) {
    catchAndMatch(log.bind(undefined, 10), /should be a string/, cb);
});

Contributing

All pull requests and issues welcome! If you're not sure how, check out Kent C. Dodds' great video tutorials on egghead.io!