UNPKG

@assertive-ts/core

Version:

A type-safe fluent assertion library

77 lines (76 loc) 2.87 kB
import { Assertion, Constructor } from "./Assertion"; import { ErrorAssertion } from "./ErrorAssertion"; import { type TypeFactory } from "./helpers/TypeFactories"; export type AnyFunction = (...args: unknown[]) => unknown; /** * Encapsulates assertion methods applicable to functions. * * @param T the type of the function's signature */ export declare class FunctionAssertion<T extends AnyFunction> extends Assertion<T> { constructor(actual: T); /** * Check if the function throws when called. Optionally, you can check that * the thrown error is strictly equal to an `Error` instance by passing it as * a parameter. * * @example * ``` * expect(throwingFunction).toThrow(); * expect(throwingFunction).toThrow(myErrorInstance); * ``` * * @param error the error the function should throw * @returns the assertion instance */ toThrow<E extends Error>(error?: E): this; /** * Check if the function throws an `Error`. If the `ErrorType` is passed, * it also checks if the error is an instance of the specific type. * * @example * ``` * expect(throwingFunction) * .toThrowError() * .toHaveMessage("Oops! Something went wrong...") * * expect(myCustomFunction) * .toThrowError(MyCustomError) * .toHaveMessage("Something failed!"); * ``` * * @typeParam E the type of the `Error` * @param ExpectedType optional error type constructor to check the thrown * error against. If is not provided, it defaults to * {@link Error} * @returns a new {@link ErrorAssertion} to assert over the error */ toThrowError(): ErrorAssertion<Error>; toThrowError<E extends Error>(Expected: Constructor<E>): ErrorAssertion<E>; /** * Check if the function throws a non-error value when called. Additionally, * you can pass a {@link TypeFactory} in the second argument so the returned * assertion is for the specific value type. Otherwise, a basic * {@link Assertion Assertion<unknown>} instance is returned. * * @example * ``` * expect(raiseValue) * .toThrowValue() * .toBeEqual(someValue); * * expect(raiseExitCode) * .toThrowValue(TypeFactories.Number) * .toBeNegative(); * ``` * * @typeParam S the type of the factory's value * @typeParam A the type of the assertion factory * @param expected the value the function is expected to throw * @param typeFactory optional type factory to perform more specific * assertions over the thrown value * @returns the factory assertion or a basic assertion instance */ toThrowValue<S, A extends Assertion<S>>(typeFactory?: TypeFactory<S, A>): A; private captureError; }