jest-expect-message icon indicating copy to clipboard operation
jest-expect-message copied to clipboard

Does not work with async assertions?

Open cspotcode opened this issue 5 years ago • 1 comments
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);

cspotcode avatar Nov 25 '19 22:11 cspotcode

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';
}

cspotcode avatar Nov 25 '19 22:11 cspotcode

Thanks for raising the issue, this is fixed in: https://www.npmjs.com/package/jest-expect-message/v/1.1.2

mattphillips avatar Sep 08 '22 19:09 mattphillips