Skip to content

Instantly share code, notes, and snippets.

@KATT
Last active December 12, 2022 18:25
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KATT/21142eccba29234221f973e18857f03a to your computer and use it in GitHub Desktop.
Save KATT/21142eccba29234221f973e18857f03a to your computer and use it in GitHub Desktop.
Test helper utility to expect a function or a promise to throw
// usage examples
// callback
const err1 = await waitError(() => { /* do something that throws */ })
// async callback
const err2 = await waitError(async () => { /* do something async that throws */ })
// expect a promise instance to throw
const err3 = await waitError(promise)
// expect a promise instance to throw with a specific error constructor
const err4 = await waitError(promise, MyCustomError)
type Constructor<T extends {} = {}> = new (...args: any[]) => T;
export async function waitError<TError = Error>(
/**
* Function callback or promise that you expect will throw
*/
fnOrPromise: (() => Promise<unknown> | unknown) | Promise<unknown>,
/**
* Force error constructor to be of specific type
* @default Error
**/
errorConstructor?: Constructor<TError>,
): Promise<TError> {
try {
if (typeof fnOrPromise === 'function') {
await fnOrPromise();
} else {
await fnOrPromise;
}
} catch (err) {
expect(err).toBeInstanceOf(errorConstructor ?? Error);
return err as TError;
}
throw new Error('Function did not throw');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment