jest-expect-message
jest-expect-message copied to clipboard
Does not work with async assertions?
trafficstars
Does this library handle async assertions? It does not appear to intercept rejections from promises. For example:
await expect(Promise.reject(true)).rejects.toBe(false);
Here's how I tweaked the wrapMatcher function to handle promises.
const wrapMatcher = (matcher, customMessage) => {
const newMatcher = (...args) => {
try {
return maybeWrapPromise(matcher(...args));
} catch(error) {
rethrowError(error);
}
function maybeWrapPromise(v) {
if(isPromiseLike(v)) {
return (async () => {
try {
return await v;
} catch(error) {
rethrowError(error);
}
})();
} else {
return v;
}
}
function rethrowError(error) {
if(!error.matcherResult) {
throw error;
}
const { matcherResult } = error;
if(typeof customMessage !== 'string' || customMessage.length < 1) {
throw new JestAssertionError(matcherResult, newMatcher);
}
const message = () => customMessage + '\n\n' + matcherResult.message();
throw new JestAssertionError({ ...matcherResult, message }, newMatcher);
}
};
return newMatcher;
};
/** Type guard to detect promises */
function isPromiseLike(v: any): v is PromiseLike<any> {
return v && typeof v.then === 'function';
}
Thanks for raising the issue, this is fixed in: https://www.npmjs.com/package/jest-expect-message/v/1.1.2