async-catch

0.0.1 • Public • Published

Async-Catch

Problem

The Mocha test framework relies on uncaughtException to handle synchronous exceptions in async test code, but not 100% reliably. So tests often have code like this:

it('does something', function(done) {
  doSomethingAsync(function(error, thing) {
    if (error) {
      return done(error);
    }
    try {
      thing.should.equal({ foo: 'bar' });
      done();
    } catch (error) {
      done(error);
    }
  });
});

In other words:

  1. if (error) return error; all over the place.
  2. Catching synchronous assertions and passing exceptions to an async callback.

This introduces a lot of repetitive and unnecessary verbosity.


Solution

Wrap the synchronous assertions in a function, and pass that function to a wrapper that also handles explicit Error's.

There are two interfaces:

stopIfError

stopIfError(callback)(error, fn, fn...)

Handle a stack of Error's or synchronous functions. On any (synchronous) error, pass it to callback (and return the error synchronously). If no error, does nothing. For flow where test wants to continue making assertions.

Can use like:

it('does something', function(done) {
  doSomethingAsync(function(error, thing) {
    return if(stopIfError(done)(
      error,
      function(){
        assert(thing.foo);
      },
      function(){
        assert(thing.bar);
      }
    ));
 
    // (test continues if no error)
    assert(something else);
  });
});

checkAndStop

checkAndStop(callback)(error, fn, fn...)

This will call callback either way, with or without an error. For flow where test is done making assertions.

it('does something', function(done) {
  doSomethingAsync(function(error, thing) {
    checkAndStop(done)(
      error,
      function(){
        assert(thing.foo);
      },
      function(){
        assert(thing.bar);
      }
    ));
  });
});

Credits

By Ben Buckman. Thanks to CJ Winslow and Derek Bredensteiner for valuable feedback.

Readme

Keywords

Package Sidebar

Install

npm i async-catch

Weekly Downloads

0

Version

0.0.1

License

ISC

Last publish

Collaborators

  • benbuckman