Last active
December 12, 2022 18:25
-
-
Save KATT/21142eccba29234221f973e18857f03a to your computer and use it in GitHub Desktop.
Test helper utility to expect a function or a promise to throw
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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