With node built-in assert I can do something like:
assert.throws(
() => {
throw new Error('Wrong value');
},
function(err) { // custom function instead of just instanceof check
if ( (err instanceof Error) && /value/.test(err) ) {
return true;
}
},
'unexpected error'
);
Is it make sense to add this feature in Chai?
Hey @kharandziuk thanks for the issue.
If you're looking to just test the error constructor and/or message, you can already do that with .throw:
assert.throws(fn, Error, /value/);
assert.throws(fn, ReferenceError, /missing/);
expect(fn).to.throw(Error, /value/);
expect(fn).to.throw(ReferenceError, /missing/);
If you're looking for something more fine grained, for the expect/should API we have satisfy which does something very similar to your example. For example:
expect(fn).to.throw().and.to.satisfy((err) => {
return error.code === 404;
});
Sadly it seems like assert doesn't include satisfy - we should look into adding it though.
How do either of these methods work for you?
This one:
expect(fn).to.throw().and.to.satisfy((err) => {
return error.code === 404;
});
is actually what I'm looking for. Does it make sense to add this sample in documentation of .throw?
Great! The bdd method description of throw has a small note about how to chain but it does not have a useful example. We could definitely extend the documentation.
BTW, satisfy is a bit of an escape hatch - it would likely be much cleaner to use other assertions to do the same thing (well, you'd get a lot better error messages when it fails). Example:
expect(fn).to.throw(Error).which.has.property('code', 404);
// You can also use multiple chains!
expect(fn).to.throw(Error).which.has.property('code').that.is.within(399, 500);
I'll switch issue over to a docs issue, and if you'd like to raise a PR to clarify the documentation for these kinds of usecases, that'd be awesome! The docs for .throws are all in the code over here
Created a PR
Most helpful comment
Created a PR