Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add resume() for async tests that trap exceptions #889

Closed
wants to merge 1 commit into from
Closed

Add resume() for async tests that trap exceptions #889

wants to merge 1 commit into from

Conversation

juandopazo
Copy link

Hi!

Mocha's async support is awesome, but it as a small deficiency for testing code that catches exceptions, most notably promise-based code or code using task.js. For example:

it('should show the correct assertion failure', function (done) {
  somePromise.then(function (value) {
    // since then() catches exceptions here
    // when the test passes everything is ok
    // but when the assertion fails
    // the test doesn't report the assertion failure
    expect(value).to.be(5);
    done();
  })
})

This pull request introduces a helper function hidden as a property of the done callback that catches its own exceptions and concludes the test the same way as done. This would let us use the following pattern:

it('should show the correct assertion failure', function (then) {
  somePromise.then(function (value) {
    then.resume(function () {
      expect(value).to.be(5);
    });
  })
})

I would be very much OK with other names for resume like next, or a second callback if you think it would be a better choice.

@tomasdev
Copy link

tomasdev commented Jun 5, 2013

Why not leave the logic on the test itself?

it('should show the correct assertion failure', function (done) {
  somePromise.then(function (value) {
    try {
      expect(value).to.be(5);
      done();
    } catch (e) {
      done(e);
    }
  });
});

@juandopazo
Copy link
Author

To avoid repetition. I wish there was a less verbose way of doing it, but there doesn't seem to be one.

@juandopazo
Copy link
Author

I just realized I can write this on top of done() with a global function and it's nice enough:

function resume(done, fn) {
  try {
    fn();
    done();
  } catch (err) {
    done(err);
  }
}

it('...', function (test) {
  promise.then(function (value) {
    resume(test, function () {
      expect(value).to.be(5);
    })
  })
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants