/** * Testing utilities for handling expected failures and errors. */ import { type PromiseReference, type PromiseOrValue, type ClassType, type Maybe, type ClassLikeType } from '@dereekb/util'; import { BaseError } from 'make-error'; import { type TestDoneCallback } from './shared'; /** * Error thrown by fail() and used by expectError() */ export declare class ExpectedFailError extends BaseError { } /** * Creates an {@link ExpectedFailError} without throwing it, for use in deferred error handling. * * @param message - Optional error message. * @returns A new {@link ExpectedFailError} instance. */ export declare function failSuccessfullyError(message?: string): ExpectedFailError; /** * Throws an {@link ExpectedFailError} to signal that a test reached the expected failure point. * * Must be called inside {@link shouldFail} (typically via {@link itShouldFail}) or {@link expectSuccessfulFail}, * which catch `ExpectedFailError` and convert it into a passing test. Calling it inside a plain * `it()` block causes the test to fail because the error propagates uncaught. * * @param message - Optional error message. * @throws {ExpectedFailError} Always; never returns normally. */ export declare function failSuccessfully(message?: string): never; /** * Error thrown when success occurs when it should not have. */ export declare class UnexpectedSuccessFailureError extends BaseError { } /** * Creates an {@link UnexpectedSuccessFailureError} without throwing it. * * @param message - Optional error message; defaults to a standard "expected an error" message. * @returns A new {@link UnexpectedSuccessFailureError} instance. */ export declare function failDueToSuccessError(message?: string): UnexpectedSuccessFailureError; /** * Error thrown when the error type was different than the expected type. */ export declare class ExpectedErrorOfSpecificTypeError extends BaseError { readonly encounteredType: unknown; readonly expectedType?: Maybe; constructor(encounteredType: unknown, expectedType?: Maybe); } /** * Fails the current test by throwing an {@link UnexpectedSuccessFailureError}. * Use when a code path should not have been reached. * * @param message - Optional error message. * @throws {UnexpectedSuccessFailureError} Always; never returns normally. */ export declare function failTest(message?: string): never; /** * Throws an {@link UnexpectedSuccessFailureError} with a default message. * Typically called when an operation succeeds but was expected to throw. * * @throws {UnexpectedSuccessFailureError} Always; never returns normally. */ export declare function failDueToSuccess(): never; /** * Default error handler for {@link expectSuccessfulFail} that passes through {@link ExpectedFailError} * instances and re-throws all other errors. * * @param e - The caught error to evaluate. * @throws {unknown} Re-throws the supplied error when it is not an {@link ExpectedFailError}. */ export declare function EXPECT_ERROR_DEFAULT_HANDLER(e: unknown): void; /** * Used to assert additional information about the expected error. * * Can assert within this function, or return a boolean. A boolean returning false means the test should throw an ExpectedErrorOfSpecificTypeError. */ export type ExpectFailAssertionFunction = (error: unknown) => PromiseOrValue | void>; /** * Creates an ExpectFailAssertionFunction that asserts the encountered error is of the expected type using the instanceof keyword. * * Throws an ExpectedErrorOfSpecificTypeError on failures. * * @param expectedType - The class or constructor function that the error should be an instance of. * @returns An assertion function that validates the error type via instanceof. */ export declare function expectFailAssertErrorType(expectedType: ClassType | ClassLikeType | typeof Error | any): ExpectFailAssertionFunction; /** * Function that expects any failure to be thrown, then throws an {@link ExpectedFailError}. * * Intended to be used inside {@link itShouldFail} or {@link shouldFail}, which catch the * `ExpectedFailError` and treat it as a passing test. When used inside a plain `it()` block * the thrown `ExpectedFailError` propagates and fails the test even though `errorFn` rejected * as expected — for that case use vitest's `await expect(...).rejects.toThrow(...)` instead. * * @param errorFn - Function expected to throw an error (sync or async) * @param assertFailType - Optional assertion to validate the type or content of the thrown error. * @returns Rejects with {@link ExpectedFailError} when the expected failure is verified, or with {@link UnexpectedSuccessFailureError} when `errorFn` resolves successfully. * * @example * ```ts * itShouldFail('when the user is not authorized', async () => { * await expectFail(() => callProtectedEndpoint(), expectFailAssertHttpErrorServerErrorCode(403)); * }); * ``` */ export declare function expectFail(errorFn: () => PromiseOrValue, assertFailType?: ExpectFailAssertionFunction): Promise; /** * Invokes `fn` and returns the value it rejects with. Throws {@link UnexpectedSuccessFailureError} * when `fn` resolves successfully. * * Use this when a test needs the thrown value in hand to assert on multiple of its properties * (e.g. inspect a structured `details.code`). For "did it throw at all" checks, prefer * {@link expectFail} or vitest's `await expect(fn()).rejects.toThrow(...)`. * * @param fn - Async function expected to reject. * @returns The thrown value as `unknown`. * @throws {UnexpectedSuccessFailureError} When `fn` resolves successfully. * * @example * ```ts * const error = await captureRejection(() => callResetPassword({ resetPassword: '000000' })); * expect(error).toBeInstanceOf(HttpsError); * expect((error as HttpsError).code).toBe('invalid-argument'); * ``` */ export declare function captureRejection(fn: () => Promise): Promise; /** * Function that expects an {@link ExpectedFailError} to be thrown by `errorFn`. * * Lower-level building block used by {@link shouldFail}; most consumer tests should use * {@link itShouldFail} + {@link expectFail} (or {@link failSuccessfully}) rather than calling * this directly. If `errorFn` resolves without throwing, this calls `handleError` with an * {@link UnexpectedSuccessFailureError}; if it throws something other than `ExpectedFailError`, * `handleError` likewise rejects the surrounding test. * * @param errorFn - function expected to throw (sync or async); if it succeeds, the test fails * @param handleError - optional custom error handler; defaults to {@link EXPECT_ERROR_DEFAULT_HANDLER} */ export declare function expectSuccessfulFail(errorFn: () => void, handleError?: (e: unknown) => void): void; export declare function expectSuccessfulFail(errorFn: () => Promise, handleError?: (e: unknown) => void): Promise; /** * Extended done callback for {@link shouldFail} tests that adds a {@link failSuccessfully} convenience method. */ export interface ShouldFailDoneCallback extends TestDoneCallback { failSuccessfully(): void; } /** * A test function for {@link shouldFail} that receives a {@link ShouldFailDoneCallback} to signal failure outcomes. */ export type ShouldFailProvidesCallbackWithDone = (cb: ShouldFailDoneCallback) => Maybe; /** * A test function for {@link shouldFail} that returns its result directly (sync or async), without using a done callback. */ export type ShouldFailProvidesCallbackWithResult = () => PromiseOrValue; /** * Union type for test functions accepted by {@link shouldFail}. Supports both done-callback and promise-based patterns. */ export type ShouldFailProvidesCallback = ShouldFailProvidesCallbackWithDone | ShouldFailProvidesCallbackWithResult; /** * Used to wrap a testing function and watch for ExpectedFailError errors in order to pass the test. Other exceptions are treated normally as failures. * * This is typically used in conjunction with failSuccessfully(), expectSuccessfulFail(), or expectFail(). * * @param fn - The test function that is expected to throw an {@link ExpectedFailError} * @returns An async test function suitable for use with `it()` */ export declare function shouldFail(fn: ShouldFailProvidesCallback): () => Promise; /** * Convenience wrapper that registers an `it()` test case which is expected to fail. * * Automatically generates a "should fail" description and wraps the test function with {@link shouldFail}. * * @param describeOrFn - either a description suffix (e.g., "when input is null") or the test function directly * @param fn - the test function, if a description string was provided as the first argument */ export declare function itShouldFail(fn: ShouldFailProvidesCallback): void; export declare function itShouldFail(describe: string, fn: ShouldFailProvidesCallback): void; /** * A simulated done callback that bridges callback-based test patterns to promises. * * Calling the handler or its `fail` method resolves or rejects the underlying promise, * allowing callback-style tests to be awaited. */ export interface FakeDoneHandler extends TestDoneCallback, PromiseReference { _ref: PromiseReference; } /** * Creates a {@link FakeDoneHandler} that converts done-callback invocations into promise resolution/rejection. * * Calling the returned function with no arguments resolves the promise; * calling it with an error (or calling `.fail()`) rejects the promise. * * @returns A new {@link FakeDoneHandler} backed by a promise reference. */ export declare function fakeDoneHandler(): FakeDoneHandler;