import { AssertionError } from "./assertion_error.ts";import { assertIsError } from "./assert_is_error.ts";
export function assertRejects( fn: () => PromiseLike<unknown>, msg?: string,): Promise<unknown>;export function assertRejects<E extends Error = Error>( fn: () => PromiseLike<unknown>, ErrorClass: new (...args: any[]) => E, msgIncludes?: string, msg?: string,): Promise<E>;export async function assertRejects<E extends Error = Error>( fn: () => PromiseLike<unknown>, errorClassOrMsg?: | (new (...args: any[]) => E) | string, msgIncludesOrMsg?: string, msg?: string,): Promise<E | Error | unknown> { let ErrorClass: (new (...args: any[]) => E) | undefined = undefined; let msgIncludes: string | undefined = undefined; let err;
if (typeof errorClassOrMsg !== "string") { if ( errorClassOrMsg === undefined || errorClassOrMsg.prototype instanceof Error || errorClassOrMsg.prototype === Error.prototype ) { ErrorClass = errorClassOrMsg as new (...args: any[]) => E; msgIncludes = msgIncludesOrMsg; } } else { msg = errorClassOrMsg; } let doesThrow = false; let isPromiseReturned = false; const msgSuffix = msg ? `: ${msg}` : "."; try { const possiblePromise = fn(); if ( possiblePromise && typeof possiblePromise === "object" && typeof possiblePromise.then === "function" ) { isPromiseReturned = true; await possiblePromise; } } catch (error) { if (!isPromiseReturned) { throw new AssertionError( `Function throws when expected to reject${msgSuffix}`, ); } if (ErrorClass) { if (error instanceof Error === false) { throw new AssertionError(`A non-Error object was rejected${msgSuffix}`); } assertIsError( error, ErrorClass, msgIncludes, msg, ); } err = error; doesThrow = true; } if (!doesThrow) { throw new AssertionError( `Expected function to reject${msgSuffix}`, ); } return err;}