Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 21x 4x 17x 5x 12x 4x | import type { expect as Expect } from 'vitest';
/**
* Creates a function that can be used to match errors in tests. Assumes that
* the error will have a `message`, and optionally:
* - a `string` stack
* - an `Error` cause
*
* The matcher recurs on `cause` to allow for matching nested errors. Throws if
* a `cause` is not an `Error`.
*
* @param expect - The expect function to use.
* @returns A function that can be used to match errors in tests.
*/
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export const makeErrorMatcherFactory = (expect: typeof Expect) => {
const makeErrorMatcher = (
error: Error | string,
): ReturnType<typeof expect.objectContaining> => {
if (typeof error === 'string') {
return expect.objectContaining({
message: error,
stack: expect.any(String),
});
}
return expect.objectContaining({
message: error.message,
...(error.stack !== undefined && { stack: expect.any(String) }),
...(error.cause !== undefined && {
cause:
error.cause instanceof Error
? makeErrorMatcher(error.cause)
: error.cause,
}),
});
};
return makeErrorMatcher;
};
|