Add toBeRejectedWithError matcher

This commit is contained in:
Alexey Prokhorov
2019-04-26 01:46:56 +04:00
parent afb24d1050
commit 35968e4a60
3 changed files with 190 additions and 1 deletions

View File

@@ -0,0 +1,88 @@
getJasmineRequireObj().toBeRejectedWithError = function(j$) {
/**
* Expect a promise to be rejected with a value matched to the expected
* @function
* @async
* @name async-matchers#toBeRejectedWithError
* @param {Error} [expected] - `Error` constructor the object that was thrown needs to be an instance of. If not provided, `Error` will be used.
* @param {RegExp|String} [message] - The message that should be set on the thrown `Error`
* @example
* await expectAsync(aPromise).toBeRejectedWithError(MyCustomError, 'Error message');
* await expectAsync(aPromise).toBeRejectedWithError(MyCustomError, /Error message/);
* await expectAsync(aPromise).toBeRejectedWithError(MyCustomError);
* await expectAsync(aPromise).toBeRejectedWithError('Error message');
* return expectAsync(aPromise).toBeRejectedWithError(/Error message/);
*/
return function toBeRejectedWithError() {
return {
compare: function(actualPromise, arg1, arg2) {
var expected = getExpectedFromArgs(arg1, arg2);
return actualPromise.then(
function() {
return {
pass: false,
message: 'Expected a promise to be rejected but it was resolved.'
};
},
function(actualValue) { return matchError(actualValue, expected); }
);
}
};
};
function matchError(actual, expected) {
if (!j$.isError_(actual)) {
return fail(expected, 'not rejected with Error.');
}
if (!(actual instanceof expected.error)) {
return fail(expected, 'rejected with type ' + j$.fnNameFor(actual.constructor) + '.');
}
var actualMessage = actual.message;
if (actualMessage === expected.message || typeof expected.message === 'undefined') {
return pass(expected);
}
if (expected.message instanceof RegExp && expected.message.test(actualMessage)) {
return pass(expected);
}
return fail(expected, 'rejected with ' + j$.pp(actual) + '.');
}
function pass(expected) {
return {
pass: true,
message: 'Expected a promise to be rejected with ' + expected.printValue + '.'
};
}
function fail(expected, message) {
return {
pass: false,
message: 'Expected a promise to be rejected with ' + expected.printValue + ' but it was ' + message
};
}
function getExpectedFromArgs(arg1, arg2) {
var error, message;
if (typeof arg1 === 'function' && j$.isError_(arg1.prototype)) {
error = arg1;
message = arg2;
} else {
error = Error;
message = arg1;
}
return {
error: error,
message: message,
printValue: j$.fnNameFor(error) + ': ' + j$.pp(message)
};
}
};

View File

@@ -3,7 +3,8 @@ getJasmineRequireObj().requireAsyncMatchers = function(jRequire, j$) {
'toBeResolved',
'toBeRejected',
'toBeResolvedTo',
'toBeRejectedWith'
'toBeRejectedWith',
'toBeRejectedWithError'
],
matchers = {};