Package Exports
- catch-and-match
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (catch-and-match) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
catch-and-match
Assert an error thrown (a)synchronously by a function.
Made with ❤ at @outlandish
Install
npm install catch-and-match --save-devCatch 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!).
Usage
catchAndMatch(fn, matcher[, cb])
fn {Function} function that should throw traditionally or within a Promise
- if
fndoes not throw, catch and match returns a rejected Promise and callscbwith an error as its first argument - if
fnthrows the error is tested againstmatcher(see below)
matcher {RegExp|String|Function} 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 constructor is matched against the constructor of the error (
err.constructor === ReferenceError)
cb {Function} error-first callback indicating success of catch and match
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);
});