question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Using expect(...).to.throw(...) with custom assertion function

See original GitHub issue

I would like to be able to run more detailed assertions against a thrown exception than what currently seems possible. It would be awesome if expect(...).to.throw(...) supported something like the following pattern:

expect(function() {
  someFunctionThatThrows();
}).to.throw(function(err) {
  expect(err.toString()).to.equal('Error: something is wrong here');
  expect(err.actual).to.not.exist;
  expect(err.expected).to.not.exist;
});

I currently have this implemented in a local helper, but I think that supporting this might make sense in chai itself:

Assertion.overwriteMethod('throw', function (_super) {
  return function(fn) {
    if (typeof fn === 'function') {
      var obj = this._obj;

      try {
        obj();
      } catch (err) {
        return fn(err);
      }

      throw new chai.AssertionError('expected [Function] to throw an exception');

    } else {
      _super.apply(this, arguments);
    }
  };
});

Note that this doesn’t support using it with .not and I’m not sure if that would actually make sense. That case should probably be handled though and fail if the 'negate' flag is encountered.

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:2
  • Comments:12 (8 by maintainers)

github_iconTop GitHub Comments

14reactions
keithamuscommented, Apr 1, 2016

@Turbo87 There’s a few solutions here, let me go through them:

If you want to assert on all of the properties for equality, .deep.equal will work:

expect(functionThatThrows).to.throw(ErrorConstructor, 'a message')
  .that.deep.equals({
    'firstProp': 'foo',
    'secondProp': 'bar',
  });

If you want to assert on some of the properties for equality, .members will work:

expect(functionThatThrows).to.throw(ErrorConstructor, 'a message')
  .which.has.members({
    'firstProp': 'foo',
    'secondProp': 'bar',
  });

However, if you want to assert some semantics over individual properties, we don’t have a way to do that just yet. You could use satisfy for now:

expect(functionThatThrows).to.throw(ErrorConstructor, 'a message')
  .that.satisfies(function (error) {
    return typeof error.firstProp === 'string' && typeof error.secondProp === 'string';
  });

Alternatively, you can subscribe to issue https://github.com/chaijs/chai/issues/644 - which is working out how to implement a matcher API for this kind of thing.

Hopefully that gives you some ideas to work with @Turbo87. Let us know if that’s helpful, or if you want to discuss things further 😄

7reactions
RahmanMcommented, May 23, 2018

Ok, this error message was very confusing. For anyone else who might be having the same issue the solution was this:

expect(()=> calc.divide(2,0)).to.throw('Divide by zero is not permitted.');

Instead of:

expect(()=> calc.divide(2,0)).to.throw(new Error('Divide by zero is not permitted.'));

Read more comments on GitHub >

github_iconTop Results From Across the Web

Expect a function to throw an exception in Jest - eloquent code
Suppose we want to test the following function using Node.js and assert that it indeed throws an error: func.js:
Read more >
Mocha / Chai expect.to.throw not catching thrown errors
You have to pass a function to expect . Like this: expect(model.get.bind(model, 'z')).to.throw('Property does not exist in model schema.
Read more >
Expect - Jest
Instead, you will use expect along with a "matcher" function to assert something about a value. It's easier to understand this with an...
Read more >
Expect / Should - Chai Assertion Library
Both use the same chainable language to construct assertions, but they differ in the way an assertion ... expect(function () {}).to.not.throw(); expect({a: ...
Read more >
assert.throws() - QUnit API
When testing code that is expected to throw an exception based on a specific set of ... description here' ); // using a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found