/** * This file was automatically generated by xBuild. * DO NOT EDIT MANUALLY. */ import { FunctionLikeType, FunctionType, PromiseRejectType, PromiseResolveType, xExpect } from '@remotex-labs/xjet-expect'; import { Struct } from '@remotex-labs/xstruct'; import { Options } from 'yargs'; import { BuildOptions } from 'esbuild'; /** * Encodes a packet of a given kind into a `Buffer`. * * @template T - The packet kind (`PacketKind.Log`, `PacketKind.Error`, `PacketKind.Status`, or `PacketKind.Events`) * * @param kind - The type of packet to encode * @param data - Partial data matching the packet type; will be combined with header information * * @returns A `Buffer` containing the serialized packet * * @throws Error if the provided `kind` does not correspond to a known packet schema * * @remarks * This function combines a header and the payload according to the packet kind. * The header includes the suite ID, runner ID, and a timestamp. * * @since 1.0.0 */ declare function encodePacket(kind: T, data: Partial): Buffer; /** * Decodes a packet from a `Buffer` into its corresponding object representation. * * @template T - The expected packet kind (`PacketKind.Log`, `PacketKind.Error`, `PacketKind.Status`, or `PacketKind.Events`) * * @param buffer - The buffer containing the encoded packet * @returns The decoded packet object, combining the header and payload fields * * @throws Error if the packet kind is unknown or invalid * * @remarks * Decodes both the header and payload based on the packet kind. * * @since 1.0.0 */ declare function decodePacket(buffer: Buffer): DecodedPacketType; /** * Encodes an {@link Error} instance into a binary buffer following the packet schema. * * @param error - The error object to be serialized and encoded. * @param suiteId - Identifier of the suite where the error occurred. * @param runnerId - Identifier of the runner reporting the error. * * @returns A {@link Buffer} containing the encoded error packet, ready for transmission. * * @remarks * The function creates two binary sections: * - A **header**, describing the packet kind (`Error`), suite ID, runner ID, and timestamp. * - A **data buffer**, holding the serialized error details in JSON format. * * These two sections are concatenated into a single buffer. * * @example * ```ts * try { * throw new Error("Test failed"); * } catch (err) { * const buffer = encodeErrorSchema(err, "suite-123", "runner-456"); * socket.send(buffer); // transmit over a transport channel * } * ``` * * @see serializeError * @see PacketKind.Error * * @since 1.0.0 */ declare function encodeErrorSchema(error: Error, suiteId: string, runnerId: string): Buffer; /** * Represents the position of an invocation within a bundle file. * * @since 1.0.0 */ interface PacketInvocationInterface { /** * The line number where the invocation occurs (0-based). * @since 1.0.0 */ line: number; /** * The column number where the invocation occurs (0-based). * @since 1.0.0 */ column: number; /** * Source file * @since 1.0.0 */ source: string; } /** * Represents the header information for a packet sent. * @since 1.0.0 */ interface PacketHeaderInterface { /** * The type of packet being sent. * * @see PacketKind * @since 1.0.0 */ kind: PacketKind; /** * The unique identifier of the test suite. * * @since 1.0.0 */ suiteId: string; /** * The unique identifier of the runner sending the packet. * * @since 1.0.0 */ runnerId: string; /** * The timestamp when the packet was created, in ISO string format. * * @since 1.0.0 */ timestamp: string; } /** * Represents a log entry generated during test execution, similar to console output. * * @remarks * Used to capture messages like `console.log`, `console.error`, `console.info`, etc., * along with metadata about where in the test hierarchy and source code the log originated. * * @since 1.0.0 */ interface PacketLogInterface { /** * The severity level of the log entry. * Typically maps to console levels such as info, warn, debug, or error. * * @since 1.0.0 */ level: number; /** * The content of the log message. * @since 1.0.0 */ message: string; /** * The ancestry path of the test or describe block that generated this log. * @since 1.0.0 */ ancestry: string; /** * The location in the source code where the log was generated. * * @see PacketInvocationInterface * @since 1.0.0 */ invocation: PacketInvocationInterface; } /** * Represents a fatal error in a test suite. * * @remarks * This error occurs at the suite level and is **not** associated with any individual test, * describe block, or hook (e.g., before/after hooks). It indicates a failure * that prevents the suite from running normally. * * @since 1.0.0 */ interface PacketErrorInterface { /** * The serialized error describing the fatal issue in the suite. * @since 1.0.0 */ error: string; } /** * Represents an event emitted when a test or describe block starts or updates during execution. * * @remarks * Used to track the lifecycle of individual tests or describe blocks, including * whether they are skipped, marked TODO, or have errors. * This does **not** include suite-level fatal errors. * * @since 1.0.0 */ interface PacketStatusInterface { /** * Indicates whether the status is for a test or a describe block. * @since 1.0.0 */ type: number; /** * Indicates if the test or describe block is marked as TODO. * @since 1.0.0 */ todo: boolean; /** * Indicates if the test or describe block was skipped. * @since 1.0.0 */ skipped: boolean; /** * Duration of the test or describe block in milliseconds, if available. * @since 1.0.0 */ duration: number; /** * The ancestry path of the test or describe block. * @since 1.0.0 */ ancestry: string; /** * Human-readable description of the test or describe block. * @since 1.0.0 */ description: string; } /** * Represents an event emitted for a test or describe block during execution. * * @remarks * Used to track the lifecycle of individual tests or describe blocks, such as finish. * This interface is **not** for suite-level fatal errors. * * @since 1.0.0 */ interface PacketEventsInterface { /** * Indicates the type of event and whether it corresponds to a test or a describe block. * @since 1.0.0 */ type: number; /** * Error message associated with the test or describe block, if any. * @since 1.0.0 */ errors: string; /** * Duration of the test or describe block in milliseconds. * @since 1.0.0 */ duration: number; /** * The ancestry path of the test or describe block. * @since 1.0.0 */ ancestry: string; /** * Human-readable description of the test or describe block. * @since 1.0.0 */ description: string; } /** * Defines the different kinds of packets that can be transmitted or received. * * @remarks * Each packet kind corresponds to a specific type of event or message in the test framework: * - `Log`: Console or logging messages * - `Error`: Suite-level fatal errors * - `Status`: Test or describe start events, including `skipped` and `todo` flags * - `Events`: Test or describe end events, only for completed tests/describes (no skipped or TODO) * * @since 1.0.0 */ declare const enum PacketKind { /** * Represents a log message packet, e.g., `console.log`, `console.error`. * @since 1.0.0 */ Log = 1, /** * Represents a fatal suite-level error. * Not associated with any test, describe, or hook. * @since 1.0.0 */ Error = 2, /** * Represents a status packet for test or describe start events. * * @remarks * Includes flags for: * - `skipped`: Whether the test or describe was skipped * - `todo`: Whether the test is marked as TODO * * @since 1.0.0 */ Status = 3, /** * Represents an event packet for test or describe end events. * * @remarks * Only includes completed tests/describes; skipped or TODO tests are not included. * Contains information such as `passed` and `duration`. * * @since 1.0.0 */ Events = 4 } /** * Maps each {@link PacketKind} to its corresponding {@link Struct} schema for serialization/deserialization. * * @remarks * This object allows encoding and decoding packets of different kinds using * their respective `xStruct` schemas. Use `PacketSchemas[PacketKind.Log]` to * get the schema for log packets, etc. * * @see PacketKind * @see Struct * * @since 1.0.0 */ declare const PacketSchemas: Record; /** * Maps each {@link PacketKind} to its corresponding packet payload interface. * * @remarks * This type is used internally to associate packet kinds with their structured payloads. * For example, a `PacketKind.Log` corresponds to a {@link PacketLogInterface} payload. * * @since 1.0.0 */ type PacketPayloadMapType = { [PacketKind.Log]: PacketLogInterface; [PacketKind.Error]: PacketErrorInterface; [PacketKind.Status]: PacketStatusInterface; [PacketKind.Events]: PacketEventsInterface; }; /** * Represents a fully decoded packet, combining its payload and the standard packet header. * * @template T - The {@link PacketKind} indicating the type of payload * * @remarks * This type merges the payload interface corresponding to `T` from {@link PacketPayloadMapType} * with {@link PacketHeaderInterface}, so every decoded packet contains both its header and payload. * * @example * ```ts * const decodedLog: DecodedPacketType = { * kind: PacketKind.Log, * suiteId: 'suite1', * runnerId: 'runner1', * timestamp: '2025-09-02T08:00:00Z', * level: 1, * message: 'Test log message', * ancestry: 'root.describe.test', * invocation: { line: 12, column: 5 } * }; * ``` * * @since 1.0.0 */ type DecodedPacketType = PacketPayloadMapType[T] & PacketHeaderInterface; /** * A powerful mock state manager for simulating functions and classes in tests. * * @template F - The function signature being mocked, defaults to any function * * @remarks * MockState provides a complete mocking solution. It tracks * all invocations, including arguments, return values, and contexts, while also allowing * customization of behavior through various methods like `mockImplementation` and * `mockReturnValue`. * * Key features: * - Tracks call arguments, return values, and execution contexts * - Supports one-time implementations and return values * - Manages Promise resolutions and rejections * - Provides methods for resetting or restoring mock state * - Preserves the interface of the original function * * @example * ```ts * // Create a basic mock * const mockFn = new MockState(); * * // Configure return values * mockFn.mockReturnValue('default'); * mockFn.mockReturnValueOnce('first call'); * * // Use the mock * console.log(mockFn()); // 'first call' * console.log(mockFn()); // 'default' * * // Inspect calls * console.log(mockFn.mock.calls); // [[], []] * ``` * * @since 1.0.0 */ declare class MockState extends Function { /** * List of all mocks that created as WeakRef */ static mocks: Set>; /** * The `name` property represents the name of the mock function. */ name: string; /** * Flag to detect mock functions */ readonly xJetMock: boolean; /** * Holds the current state of the mock, including all invocation records. * * @remarks * This property tracks the complete history of the mock's usage, storing * information like call arguments, return values, execution contexts, * instances, and the order of invocations. * * It's initialized with empty arrays for tracking and gets updated with * each invocation. This state is what powers the inspection capabilities * accessible via the public `mock` getter. * * @since 1.0.0 */ private state; /** * Stores one-time implementations to be used on successive invocations. * * @remarks * This queue contains functions that will be consumed in FIFO order * (first-in, first-out) when the mock is called. Each implementation * is used exactly once and then removed from the queue. * * When adding implementations with `mockImplementationOnce()` or similar * methods, they are pushed to this queue. On invocation, the mock will * check this queue first, using and removing the oldest implementation * if available, or falling back to the default implementation. * * @since 1.0.0 */ private queuedImplementations; /** * The current default implementation for this mock. * * @remarks * This property holds the function that will be executed when the mock is called, * unless overridden by a queued one-time implementation. It can be set using * the `mockImplementation()` method and retrieved with `getMockImplementation()`. * * If not explicitly set, it defaults to `undefined`, meaning the mock will * return `undefined` when called (after any queued implementations are used). * * This implementation determines the behavior of the mock for all calls that * don't have a specific one-time implementation in the queue. * * @since 1.0.0 */ private implementation; /** * Preserves the original implementation provided when creating the mock. * * @remarks * This property stores the initial function passed to the constructor, allowing * the mock to be restored to its original behavior later using `mockRestore()`. * * If no implementation was provided in the constructor, this will contain a * function that returns `undefined` when called. * * The original implementation is immutable and serves as a reference point * for resetting the mock to its initial state. * * @since 1.0.0 */ private readonly originalImplementation; /** * Optional cleanup function to be called when the mock is restored. * * @remarks * If provided, this function will be executed when `mockRestore()` is called, * allowing for custom cleanup operations. This is particularly useful when * creating mocks that replace methods or properties on existing objects. * * The restore function should handle any necessary teardown, such as * restoring original object properties, removing event listeners, or * closing connections that were established during mock creation. * * @since 1.0.0 */ private readonly restore?; /** * Creates a new instance of a mock function. * * @template F - The function type being mocked. This generic type parameter allows * the mock to properly type-check parameters and return values to match * the function signature being mocked. * * @param implementation - The initial function implementation to use. If not provided, * the mock will return `undefined` when called. * @param restore - Optional cleanup function that will be called when `mockRestore()` is invoked. * Useful for restoring original behavior when mocking existing object methods. * @param name - Optional name for the mock function, used in error messages and test output. * Defaults to "xJet.fn()" if not provided. * * @remarks * The constructor initializes the mock's state, implementation, and metadata. * It returns a Proxy that allows the mock to be both a function and an object with properties. * * The Proxy intercepts: * - Function calls (via `apply`) * - Property access (via `get`) * - Constructor calls with `new` (via `construct`) * * This enables the mock to track calls, return configured values, and provide * helper methods for assertions and configuration. * * @see ReturnType * @see ImplementationType * * @since 1.0.0 */ constructor(implementation?: F, restore?: () => F | void, name?: string); /** * Gets a readonly snapshot of the current mocks state. * * @template F - The function type being mocked. * * @returns A frozen (immutable) copy of the mock state {@link MocksStateInterface}, containing information * about calls, return values, and other tracking data. * * @remarks * This property provides safe access to the mock's internal state for assertions and * debugging purposes. The returned object is a deep copy with all properties frozen * to prevent accidental modification of the mock's internal state. * * @see MocksStateInterface * * @since 1.0.0 */ get mock(): Readonly>; /** * Gets the original function implementation. * * @template F - The function type being mocked. * * @returns The original function implementation that was provided when creating the mock * or a default implementation that returns undefined if none was provided. * * @remarks * This property allows access to the original implementation that was stored * when the mock was created. It's useful when you need to temporarily access * or call the original behavior within test cases. * * @example * ```ts * // Create a mock with an original implementation * const originalFn = (x: number) => x * 2; * const mockFn = xJet.fn(originalFn); * * // Override the implementation for some tests * mockFn.mockImplementation((x: number) => x * 3); * * // Call the original implementation directly when needed * const result = mockFn.original(5); // Returns 10, not 15 * ``` * * @since 1.0.0 */ get original(): F; /** * Clears all information stored in the mock's state {@link MocksStateInterface}. * * @returns The mock instance for method chaining. * * @remarks * This method resets all stored information such as tracked calls, return values, * and other state information. It doesn't reset any custom implementations that * were set using mockImplementation or similar methods. * * @example * ```ts * const mockFn = xJet.fn(); * mockFn('first call'); * mockFn('second call'); * * expect(mockFn.mock.calls.length).toBe(2); * * mockFn.mockClear(); * * // All calls information has been cleared * expect(mockFn.mock.calls.length).toBe(0); * ``` * * @since 1.0.0 */ mockClear(): this; /** * Resets the mock by clearing all state and removing all queued implementations. * * @returns The mock instance for method chaining. * * @remarks * This method performs a more complete reset than mockClear() {@link mockClear}. * It clears all stored information about calls and additionally removes any queued implementations that were * set using mockImplementationOnce(). The default implementation will be restored. * * @example * ```ts * const mockFn = xJet.fn(() => 'default'); * mockFn.mockImplementationOnce(() => 'first call'); * mockFn.mockImplementationOnce(() => 'second call'); * * console.log(mockFn()); // 'first call' * * mockFn.mockReset(); * * // All calls have been cleared, and queued implementations removed * console.log(mockFn()); // 'default' * ``` * * @see mockClear * @since 1.0.0 */ mockReset(): this; /** * Restores the original implementation of the mocked function. * * @returns The mock instance for method chaining. * * @remarks * This method performs the most complete reset operation. It first calls mockReset() {@link mockReset} * to clear all state and queued implementations, then restores the original implementation * provided when the mock was created. If a custom restore function was provided, * it will be used instead to determine the implementation to restore. * * @example * ```ts * // Create a mock with an original implementation * const originalFn = (x: number) => x * 2; * const mockFn = xJet.fn(originalFn); * * // Override the implementation * mockFn.mockImplementation((x: number) => x * 3); * * console.log(mockFn(5)); // 15 * * // Restore the original implementation * mockFn.mockRestore(); * * console.log(mockFn(5)); // 10 * ``` * * @see mockClear * @see mockReset * * @since 1.0.0 */ mockRestore(): this; /** * Returns the current implementation of the mock function. * * @returns The current mock implementation, or undefined if no implementation exists. * * @remarks * This method returns the current implementation function used by the mock. * This could be the default implementation, a custom implementation set via * mockImplementation() {@link mockImplementation}, or the original implementation * if mockRestore() {@link mockRestore} was called. * * @example * ```ts * const mockFn = xJet.fn(() => 'default'); * * // Get the default implementation * const impl = mockFn.getMockImplementation(); * console.log(impl()); // 'default' * * // Change the implementation * mockFn.mockImplementation(() => 'new implementation'); * * // Get the new implementation * const newImpl = mockFn.getMockImplementation(); * console.log(newImpl()); // 'new implementation' * ``` * * @since 1.0.0 */ getMockImplementation(): ImplementationType | undefined; /** * Returns the next implementation to be used when the mock is called. * * @returns The next implementation from the queue, or the default implementation if the queue is empty. * * @remarks * This method retrieves and removes the next implementation from the queue of implementations * added via mockImplementationOnce() {@link mockImplementationOnce}. If the queue is empty, * it returns the default implementation set via mockImplementation() {@link mockImplementation} * or the original function. * * @example * ```ts * const mockFn = xJet.fn(() => 'default'); * mockFn.mockImplementationOnce(() => 'first call'); * mockFn.mockImplementationOnce(() => 'second call'); * * const firstImpl = mockFn.getNextImplementation(); * console.log(firstImpl()); // 'first call' * * const secondImpl = mockFn.getNextImplementation(); * console.log(secondImpl()); // 'second call' * * const defaultImpl = mockFn.getNextImplementation(); * console.log(defaultImpl()); // 'default' * ``` * * @since 1.0.0 */ getNextImplementation(): ImplementationType | undefined; /** * Sets a new implementation for this mock function. * * @param fn - The function to be used as the mock implementation. * @returns The mock instance for method chaining. * * @remarks * This method sets a persistent implementation that will be used whenever the mock function is called, * unless there are queued implementations from mockImplementationOnce() {@link mockImplementationOnce}. * The implementation remains until it is replaced by another call to mockImplementation() or restored * via mockRestore() {@link mockRestore}. * * @example * ```ts * const mockFn = xJet.fn(); * * mockFn.mockImplementation((x: number) => x * 2); * * console.log(mockFn(5)); // 10 * console.log(mockFn(10)); // 20 * * // Change the implementation * mockFn.mockImplementation((x: number) => x * 3); * * console.log(mockFn(5)); // 15 * ``` * * @see mockRestore * @see mockImplementationOnce * * @since 1.0.0 */ mockImplementation(fn: ImplementationType): this; /** * Adds a one-time implementation for this mock function. * * @param fn - The function to be used as the mock implementation for a single call. * @returns The mock instance for method chaining. * * @remarks * This method queues an implementation that will be used for a single call to the mock function. * After being used once, it will be removed from the queue. Multiple implementations can be queued, * and they will be used in the order they were added. Once all queued implementations are used, * the mock will revert to using the implementation set by mockImplementation() {@link mockImplementation}. * * @example * ```ts * const mockFn = xJet.fn(() => 'default'); * * mockFn.mockImplementationOnce(() => 'first call') * .mockImplementationOnce(() => 'second call'); * * console.log(mockFn()); // 'first call' * console.log(mockFn()); // 'second call' * console.log(mockFn()); // 'default' * ``` * * @see mockReset * @see mockImplementation * * @since 1.0.0 */ mockImplementationOnce(fn: ImplementationType): this; /** * Sets a fixed return value for this mock function. * * @param value - The value to be returned when the mock function is called. * @returns The mock instance for method chaining. * * @remarks * This method is a convenience wrapper around mockImplementation() {@link mockImplementation} * that creates an implementation which always returns the same value. It replaces any existing * implementation with a function that simply returns the specified value. * * @example * ```ts * const mockFn = xJet.fn(); * * mockFn.mockReturnValue(42); * * console.log(mockFn()); // 42 * console.log(mockFn('anything')); // 42 * console.log(mockFn({}, [])); // 42 * * // Can be changed * mockFn.mockReturnValue('new value'); * console.log(mockFn()); // 'new value' * ``` * * @see mockImplementation * @see mockReturnValueOnce * * @since 1.0.0 */ mockReturnValue(value: ReturnType): this; /** * Adds a one-time fixed return value for this mock function. * * @param value - The value to be returned for a single call to the mock function. * @returns The mock instance for method chaining. * * @remarks * This method is a convenience wrapper around mockImplementationOnce() {@link mockImplementationOnce} * that creates a one-time implementation which returns the specified value. Multiple return values * can be queued, and they will be used in the order they were added. After all queued values are * consumed, the mock will revert to its default implementation. * * @example * ```ts * const mockFn = xJet.fn(() => 'default'); * * mockFn.mockReturnValueOnce(42) * .mockReturnValueOnce('string value') * .mockReturnValueOnce({ object: true }); * * console.log(mockFn()); // 42 * console.log(mockFn()); // 'string value' * console.log(mockFn()); // { object: true } * console.log(mockFn()); // 'default' * ``` * * @see mockReturnValue * @see mockImplementationOnce * * @since 1.0.0 */ mockReturnValueOnce(value: ReturnType): this; /** * Sets a resolved Promise return value for this mock function. * * @param value - The value that the Promise will resolve to. * @returns The mock instance for method chaining. * * @remarks * This method is a convenience wrapper that creates an implementation which returns a * Promise that resolves to the specified value. It's particularly useful for testing * async functions that should return resolved Promises. * * @example * ```ts * const mockFn = xJet.fn(); * * mockFn.mockResolvedValue('resolved value'); * * // The mock now returns a Promise that resolves to 'resolved value' * mockFn().then(result => { * console.log(result); // 'resolved value' * }); * * // Can also be used with async/await * const result = await mockFn(); * console.log(result); // 'resolved value' * ``` * * @see mockRejectedValue * @see mockImplementation * @see mockResolvedValueOnce * * @since 1.0.0 */ mockResolvedValue(value: PromiseValueType>): this; /** * Adds a one-time resolved Promise return value for this mock function. * * @param value - The value that the Promise will resolve to for a single call. * @returns The mock instance for method chaining. * * @remarks * This method is a convenience wrapper that creates a one-time implementation which returns * a Promise that resolves to the specified value. Multiple resolved values can be queued and * will be used in the order they were added. After all queued values are consumed, the mock * will revert to its default implementation. * * @example * ```ts * const mockFn = xJet.fn(() => Promise.resolve('default')); * * mockFn.mockResolvedValueOnce('first call') * .mockResolvedValueOnce('second call') * .mockResolvedValueOnce('third call'); * * // Each call returns a different Promise * await expect(mockFn()).resolves.toEqual('first call'); * await expect(mockFn()).resolves.toEqual('second call'); * await expect(mockFn()).resolves.toEqual('third call'); * await expect(mockFn()).resolves.toEqual('default'); * ``` * * @see mockResolvedValue * @see mockRejectedValueOnce * @see mockImplementationOnce * * @since 1.0.0 */ mockResolvedValueOnce(value: PromiseValueType>): this; /** * Sets a rejected Promise return value for this mock function. * * @param value - The error that the Promise will reject with. * @returns The mock instance for method chaining. * * @remarks * This method is a convenience wrapper that creates an implementation which returns a * Promise that rejects with the specified value. It's particularly useful for testing * error handling in async functions. * * @example * ```ts * const mockFn = xJet.fn(); * * mockFn.mockRejectedValue(new Error('Something went wrong')); * * // The mock now returns a Promise that rejects with the error * mockFn().catch(error => { * console.error(error.message); // 'Something went wrong' * }); * * // Can also be used with async/await and try/catch * try { * await mockFn(); * } catch (error) { * console.error(error.message); // 'Something went wrong' * } * ``` * * @see mockResolvedValue * @see mockImplementation * @see mockRejectedValueOnce * * @since 1.0.0 */ mockRejectedValue(value: PromiseValueType>): this; /** * Adds a one-time rejected Promise return value for this mock function. * * @param value - The error that the Promise will reject with for a single call. * @returns The mock instance for method chaining. * * @remarks * This method is a convenience wrapper that creates a one-time implementation which returns * a Promise that rejects with the specified value. Multiple rejected values can be queued and * will be used in the order they were added. After all queued values are consumed, the mock * will revert to its default implementation. * * @example * ```ts * const mockFn = xJet.fn(() => Promise.resolve('success')); * * mockFn.mockRejectedValueOnce(new Error('first error')) * .mockRejectedValueOnce(new Error('second error')); * * // First call rejects with 'first error' * await expect(mockFn()).rejects.toThrow('first error'); * * // Second call rejects with 'second error' * await expect(mockFn()).rejects.toThrow('second error'); * * // Third call uses the default implementation and resolves * await expect(mockFn()).resolves.toEqual('success'); * ``` * * @see mockRejectedValue * @see mockResolvedValueOnce * @see mockImplementationOnce * * @since 1.0.0 */ mockRejectedValueOnce(value: PromiseValueType>): this; /** * Initializes the internal state object for the mock function. * * @returns A new mock state object with default empty values. * * @remarks * This private method creates and returns a fresh state object used to track * mock function invocations. The state includes: * - calls: Arguments passed to the mock function * - results: Return values or errors from each call * - lastCall: Arguments from the most recent call * - contexts: 'this' context values for each call * - instances: Objects created when the mock is used as a constructor * - invocationCallOrder: Tracking the sequence of calls across multiple mocks * * This method is used internally when creating a new mock or when resetting * an existing mocks state. * * @since 1.0.0 */ private initState; /** * Invokes the mock function with the provided arguments and context. * * @param thisArg - The 'this' context for the function call * @param args - The arguments to pass to the function * @returns The result of the mock implementation or undefined * * @remarks * This private method handles the actual invocation of the mock function and manages all * state trackings. * * This method is central to the mock's functionality, enabling call tracking, * result recording, and the execution of custom implementations. * * @since 1.0.0 */ private invoke; /** * Handles property access for the mock function proxy. * * @param target - The mock function instance * @param property - The property name or symbol being accessed * @returns The property value from either the mock or the original implementation * * @remarks * This private method is used as the 'get' trap for the Proxy surrounding the mock function. * It provides property access fallback behavior - first checking if the property exists * on the mock itself, and if not, retrieving it from the original implementation. * * This enables the mock to maintain its own properties while still allowing access to * properties from the original function, providing a more transparent mocking experience. * * @since 1.0.0 */ private invokeGet; /** * Handles constructor invocation when the mock is used with 'new'. * * @param target - The mock function instance * @param argArray - The arguments passed to the constructor * @param newTarget - The constructor that was directly invoked * @returns The constructed instance * * @remarks * This method is used as the 'construct' trap for the Proxy surrounding the mock function. * It delegates to the `invoke` method to handle the actual function call, then tracks the * resulting instance in the mock's state for later verification. * * The method handles both cases where the constructor returns an object (which becomes the * instance) and where it doesn't (in which case the newTarget becomes the instance). * * @since 1.0.0 */ private invokeClass; /** * Handles function invocation when the mock is called. * * @param target - The mock function instance * @param thisArg - The 'this' context for the function call * @param argumentsList - The arguments passed to the function * @returns The result of the function invocation * * @remarks * This method is used as the 'apply' trap for the Proxy surrounding the mock function. * It captures the calling context in the mock's state for later verification, then * delegates to the `invoke` method to handle the actual function call logic. * * This method is called whenever the mock function is invoked as a regular function * (not as a constructor). * * @since 1.0.0 */ private invokeFunction; } /** * Represents the possible result types of a mock function invocation. * * @template 'return' | 'throw' | 'incomplete' * * @since 1.0.0 */ type MockInvocationResultType = 'return' | 'throw' | 'incomplete'; /** * Represents the result of a mock function invocation, providing details regarding the outcome, * such as whether the function returned a value, threw an error, or did not complete its execution. * * @template T - Specifies the expected return type of the mock function when the result is of type `'return'`. * * @remarks * This interface is useful in mock testing frameworks to analyze the behavior of mocked functions * and their respective invocation outcomes. * * @since 1.0.0 */ interface MockInvocationResultInterface { /** * Indicates the result type: * - `'return'`: The mock function successfully returned a value. * - `'throw'`: The mock function threw an error or exception. * - `'incomplete'`: The mock function invocation has not been completed (rare case). * * @see MockInvocationResultType * * @since 1.0.0 */ type: MockInvocationResultType; /** * The value associated with the invocation result: * - If `type` is `'return'`, this is the mocks return value (`T`). * - If `type` is `'throw'`, this is the thrown error (`unknown`). * - If `type` is `'incomplete'`, this is `undefined`. * * @since 1.0.0 */ value: T | (unknown & { type?: never; }) | undefined | unknown; } /** * Interface representing the internal state of a mock function, tracking details of its invocations, * such as arguments, contexts, return values, and more. * * @template ReturnType - The type of value returned by the mock function. * @template Context - The type of the `this` context used during the mocks execution. Defaults to `DefaultContextType`. * @template Args - The type of arguments passed to the mock function. Default to an array of unknown values (`Array`). * * @remarks * This interface is designed to provide detailed tracking of mocks behavior, * including call arguments, contexts, instances, invocation order, and results. * Useful for testing and debugging in scenarios that require precise information about mock execution. * * @since 1.0.0 */ interface MocksStateInterface { /** * An array that holds the arguments for each invocation made to the mock. * Each entry corresponds to the arguments passed during a single call to the mock function. * * @since 1.0.0 */ calls: Array>; /** * The arguments passed to the mock during its most recent invocation. * Returns `undefined` if the mock has not been called yet. * * @since 1.0.0 */ lastCall?: Parameters; /** * An array of contexts (`this` values) for each invocation made to the mock. * Each entry corresponds to the context in which the mock was called. * * @since 1.0.0 */ contexts: Array>; /** * An array of all object instances created by the mock. * Each entry represents an instance was instantiated during the mocks invocations. * * @since 1.0.0 */ instances: Array>; /** * An array of invocation order indices for the mock. * xJet assigns an index to each call, starting from 1, to track the order in which mocks are invoked within a test file. * * @since 1.0.0 */ invocationCallOrder: Array; /** * An array of results for each invocation made to the mock. * Each entry represents the outcome of a single call, including the return value or any error thrown. * * @since 1.0.0 */ results: Array>>; } /** * Extracts the resolved value type from a `PromiseLike` type. * * @template T The input type to inspect. * * @remarks * If `T` extends `PromiseLike`, the resulting type is `U | T`, meaning it includes both * the resolved value type and the original `PromiseLike` type. * * If `T` is not a `PromiseLike`, the resulting type is simply `T`. * * This utility type is useful when you want to support both synchronous and asynchronous values * transparently — for example, when a function may return either a raw value or a promise. * * @example * ```ts * type A = PromiseValueType>; // number | Promise * type B = PromiseValueType; // string * ``` * * @since 1.0.0 */ type PromiseValueType = T | (T extends PromiseLike ? U | T : never); /** * A utility type that extracts the signature of a function and allows it to be reused in an implementation. * * @remarks * This type creates a representation of a function's signature based on its return type, parameters, and * `this` context. It's particularly useful for creating mock implementations, decorators, or wrappers * that need to maintain the same signature as the original function. * * By using this type, you can ensure type safety when implementing functions that need to match * an existing function's signature exactly, including its return type, parameter types, and `this` binding. * * @typeParam F - The original function type to extract the signature from * * @example * ```ts * // Original function * function greet(name: string): string { * return `Hello, ${name}!`; * } * * // Implementation with the same signature * const mockGreet: ImplementationType = function(name) { * return `Mocked greeting for ${name}`; * }; * * // Both functions now have the exact same type signature * ``` * * @since 1.2.2 */ type ImplementationType = FunctionLikeType>, Parameters, ThisParameterType>; /** * Base class for implementing custom reporters. * * @remarks * The `AbstractReporter` defines lifecycle hooks that can be implemented * by concrete reporter classes to customize how test results are reported. * * Reporters receive structured event messages during test execution, * including suite start/end, describe/test assertions, logs, and finalization. * * Each method is optional (`?`) and may be implemented depending on * the reporter’s needs (e.g., console logging, file output, JSON reporting). * * @example * ```ts * class ConsoleReporter extends AbstractReporter { * log(log: LogMessageInterface): void { * console.log(`[LOG] ${log.message}`); * } * * suiteStart(event: StartMessageInterface): void { * console.log(`Suite started: ${event.suiteName}`); * } * } * ``` * * @see RunnerInterface * @see LogMessageInterface * @see StartMessageInterface * @see EndMessageInterface * * @since 1.0.0 */ declare abstract class AbstractReporter { protected readonly logLevel: LogLevel; protected readonly outFilePath?: string | undefined; /** * Creates a new reporter. * * @param logLevel - The minimum log level this reporter should handle. * @param outFilePath - Optional file path where logs or reports should be written. */ constructor(logLevel: LogLevel, outFilePath?: string | undefined); /** * Initializes the reporter before test execution starts. * * @remarks * This method is called at the beginning of each test session. * In **watch mode**, it will be invoked for every new session restart. * Reporters can use this hook to reset the internal state, prepare output files, * or print session headers. * * @param suites - A list of suite names to be executed in this session. * @param runners - A list of configured runners available in this session. * * @since 1.0.0 */ init?(suites: Array, runners: Array): void; /** * Handles log messages emitted during test execution. * * @param log - The structured log message including level, text, * and optional metadata. * * @remarks * This method is triggered whenever the test code calls * `xJet.log()`, `xJet.error()`, or similar logging helpers. * Reporters can use this hook to capture, format, and * output logs to the console, files, or custom UIs. * * @see LogMessageInterface * @since 1.0.0 */ log?(log: LogMessageInterface): void; /** * Signals the start of a test suite execution. * * @param event - The structured event containing suite metadata * such as its ID, name, and runner. * * @remarks * Called when a suite begins running. Reporters can use this * hook to display suite headers, initialize timers, or log * contextual information about the suite. * * @see StartMessageInterface * @since 1.0.0 */ suiteStart?(event: StartMessageInterface): void; /** * Signals the completion of a test suite execution. * * @param event - The structured event containing final suite * metadata such as its ID, name, duration, and * aggregated results. * * @remarks * Called after a suite has finished running. Reporters can use * this hook to display summary information, update progress, * or finalize suite-level reporting. * * @see EndMessageInterface * @since 1.0.0 */ suiteEnd?(event: EndMessageInterface): void; /** * Signals the start of a `describe` block execution. * * @param event - The structured event containing metadata * about the `describe` block, including its * ID, name, and parent context. * * @remarks * Called when a `describe` block begins running. Reporters * can use this hook to display section headers, indent logs, * or prepare contextual grouping in the output. * * @see StartAssertionMessageInterface * @since 1.0.0 */ describeStart?(event: StartAssertionMessageInterface): void; /** * Signals the completion of a `describe` block execution. * * @param event - The structured event containing metadata * about the `describe` block, including its * ID, name, duration, and results. * * @remarks * Called after a `describe` block has finished running. * Reporters can use this hook to close sections, summarize * grouped tests, or adjust indentation and formatting. * * @see EndAssertionMessageInterface * @since 1.0.0 */ describeEnd?(event: EndAssertionMessageInterface): void; /** * Signals the start of an individual test execution. * * @param event - The structured event containing metadata * about the test, including its ID, name, * and parent suite or `describe` block. * * @remarks * Called when a test begins running. Reporters can use this * hook to display test-level headers, start timers, or * track progress. * * @see StartAssertionMessageInterface * @since 1.0.0 */ testStart?(event: StartAssertionMessageInterface): void; /** * Signals the completion of an individual test execution. * * @param event - The structured event containing metadata * about the test, including its ID, name, * duration, and result status. * * @remarks * Called after a test has finished running. Reporters can use * this hook to display test results, update progress bars, * or log assertion summaries. * * @see EndAssertionMessageInterface * @since 1.0.0 */ testEnd?(event: EndAssertionMessageInterface): void; /** * Called when all suites have finished executing. * * @remarks * This method is invoked at the **end of each test session**. * In watch mode, it will be called after every session completes, * allowing reporters to finalize logs, write summary files, or * perform cleanup for that session. * * @since 1.0.0 */ finish?(): void; } /** * Represents the result of a single assertion within a test. * * @remarks * This interface captures the outcome of an assertion and allows * for extensible additional properties. * * @example * ```ts * const result: AssertionResultInterface = { * name: 'should add numbers correctly', * pass: true, * expected: 4, * received: 4 * }; * ``` * * @since 1.0.0 */ interface AssertionResultInterface { /** * Optional name or description of the assertion. * @since 1.0.0 */ name?: string; /** * Indicates whether the assertion passed (`true`) or failed (`false`). * @since 1.0.0 */ pass?: boolean; /** * Optional message describing the assertion result or reason for failure. * @since 1.0.0 */ message?: string; /** * Optional value that was expected in the assertion. * @since 1.0.0 */ expected?: unknown; /** * Optional actual value received in the assertion. * @since 1.0.0 */ received?: unknown; /** * Additional arbitrary properties relevant to the assertion result. * @since 1.0.0 */ [key: string]: unknown; } /** * Represents the invocation point of a test suite in the source code. * * @remarks * This interface captures the location and source of a suite definition, * useful for reporting, debugging, or mapping transpiled code back to * the original source. * * @example * ```ts * const suiteInvocation: SuiteInvocationInterface = { * code: 'describe("MySuite", () => {})', * line: 10, * column: 5, * source: '/path/to/test.spec.ts' * }; * ``` * * @since 1.0.0 */ interface SuiteInvocationInterface { /** * The code string representing the suite invocation. * @since 1.0.0 */ code: string; /** * The line number in the source file where the suite is defined. * @since 1.0.0 */ line: number; /** * The column number in the source file where the suite starts. * @since 1.0.0 */ column: number; /** * The absolute or relative path to the source file containing the suite. * @since 1.0.0 */ source: string; } /** * Represents an error that occurred within a test suite. * * @remarks * This interface captures the essential information about a suite-level * error, including its location, message, stack trace, and optional * assertion result if the error originated from a failed expectation. * * @example * ```ts * const error: SuiteErrorInterface = { * code: 'expect(value).toBe(4)', * name: 'AssertionError', * line: 12, * column: 5, * stack: 'Error: ...', * message: 'Expected 3 to be 4', * matcherResult: { * pass: false, * expected: 4, * received: 3 * } * }; * ``` * * @since 1.0.0 */ interface SuiteErrorInterface { /** * The code snippet that caused the error. * @since 1.0.0 */ code: string; /** * The format code snippet that caused the error. * @since 1.0.0 */ formatCode: string; /** * The type or name of the error (e.g., 'AssertionError'). * @since 1.0.0 */ name: string; /** * The line number in the source file where the error occurred. * @since 1.0.0 */ line: number; /** * The column number in the source file where the error occurred. * @since 1.0.0 */ column: number; /** * The stack trace of the error. * @since 1.0.0 */ stack: string; /** * The human-readable error message. * @since 1.0.0 */ message: string; /** * Optional assertion result if the error originated from a failed expectation. * * @see AssertionResultInterface * @since 1.0.0 */ matcherResult?: AssertionResultInterface; } /** * Represents an error that occurs within a test suite. * * @remarks * Provides detailed information about the error, including location in the * source file, stack trace, and optionally the result of a failed assertion. * * @example * ```ts * const error: SuiteErrorInterface = { * code: 'expect(value).toBe(4)', * name: 'AssertionError', * line: 12, * column: 5, * stack: 'Error: ...', * message: 'Expected 3 to be 4', * matcherResult: { * pass: false, * expected: 4, * received: 3 * } * }; * ``` * * @since 1.0.0 */ interface SuiteErrorInterface { /** * The source code snippet that caused the error. * @since 1.0.0 */ code: string; /** * The type or name of the error (e.g., 'AssertionError'). * @since 1.0.0 */ name: string; /** * The line number in the source file where the error occurred. * @since 1.0.0 */ line: number; /** * The column number in the source file where the error occurred. * @since 1.0.0 */ column: number; /** * The stack trace of the error. * @since 1.0.0 */ stack: string; /** * The human-readable error message. * @since 1.0.0 */ message: string; /** * Optional result of the assertion that caused the error if applicable. * @since 1.0.0 */ matcherResult?: AssertionResultInterface; } /** * Represents a structured log message emitted during test execution. * * @remarks * Log messages are used by reporters to capture runtime information, * including standard logs, warnings, errors, and contextual metadata. * * @example * ```ts * const log: LogMessageInterface = { * level: 'info', * levelId: 3, * suite: 'loginTests', * runner: 'chrome', * message: 'Test started', * ancestry: ['a', 'b', 'c'] * timestamp: new Date(), * invocation: { * code: 'describe("Login", ...)', * line: 10, * column: 5, * source: '/path/to/login.spec.ts' * } * }; * ``` * * @since 1.0.0 */ interface LogMessageInterface { /** * The log level as a string (e.g., 'info', 'error'). * @since 1.0.0 */ level: string; /** * The name or ID of the suite associated with this log. * @since 1.0.0 */ suite: string; /** * The name or ID of the runner that emitted this log. * @since 1.0.0 */ runner: string; /** * The numeric representation of the log level. * @since 1.0.0 */ levelId: number; /** * The human-readable log message. * @since 1.0.0 */ message: string; /** * The timestamp when the log was created. * @since 1.0.0 */ timestamp: Date; /** * The hierarchy of parent suites or `describes` or `test` blocks for this assertion. * @since 1.0.0 */ ancestry: Array; /** * Optional information about the suite invocation that generated this log. * * @see SuiteInvocationInterface * @since 1.0.0 */ invocation?: SuiteInvocationInterface; } /** * Represents the event emitted when a test suite starts execution. * * @remarks * Reporters can use this event to initialize suite-level logging, * display headers, or track suite execution timing. * * @example * ```ts * const startEvent: StartMessageInterface = { * suite: 'loginTests', * runner: 'chrome', * timestamp: new Date() * }; * ``` * * @since 1.0.0 */ interface StartMessageInterface { /** * The name or ID of the suite that is starting. * @since 1.0.0 */ suite: string; /** * The name or ID of the runner executing this suite. * @since 1.0.0 */ runner: string; /** * The timestamp when the suite started execution. * @since 1.0.0 */ timestamp: Date; } /** * Represents the event emitted when a test suite finishes execution. * * @remarks * Extends {@link StartMessageInterface} with additional information * such as the duration of the suite and any errors encountered. * Reporters can use this event to summarize results and handle * suite-level failures. * * @example * ```ts * const endEvent: EndMessageInterface = { * suite: 'loginTests', * runner: 'chrome', * timestamp: new Date(), * duration: 120, * error: { * code: 'expect(value).toBe(4)', * name: 'AssertionError', * line: 12, * column: 5, * stack: 'Error: ...', * message: 'Expected 3 to be 4' * } * }; * ``` * * @see StartMessageInterface * @see SuiteErrorInterface * * @since 1.0.0 */ interface EndMessageInterface extends StartMessageInterface { /** * The duration of the suite execution in milliseconds. * @since 1.0.0 */ duration: number; /** * Optional error that occurred during the suite execution. * @since 1.0.0 */ error?: SuiteErrorInterface; } /** * Represents the event emitted when an individual assertion or `describe` or `test` block starts execution. * * @remarks * Extends {@link StartMessageInterface} with additional information specific * to assertions, such as ancestry, description, and optional flags for skipped or todo tests. * Reporters can use this event to track assertion execution and organize output hierarchically. * * @example * ```ts * const startAssertion: StartAssertionMessageInterface = { * suite: 'loginTests', * runner: 'chrome', * timestamp: new Date(), * ancestry: ['Login Suite', 'User Authentication'], * description: 'should log in successfully', * skipped: false * }; * ``` * * @see StartMessageInterface * * @since 1.0.0 */ interface StartAssertionMessageInterface extends StartMessageInterface { /** * Indicates if the assertion is marked as "todo". * @since 1.0.0 */ todo?: boolean; /** * Indicates if the assertion is skipped. * @since 1.0.0 */ skipped?: boolean; /** * The hierarchy of parent suites or `describes` blocks for this assertion. * @since 1.0.0 */ ancestry: Array; /** * The human-readable description of the assertion. * @since 1.0.0 */ description: string; } /** * Represents the event emitted when an individual assertion or `describes` or `test` block finishes execution. * * @remarks * Extends {@link StartMessageInterface} with assertion-specific details * such as pass/fail status, errors, ancestry, duration, and description. * Reporters can use this event to track results and generate detailed output. * * @example * ```ts * const endAssertion: EndAssertionMessageInterface = { * suite: 'loginTests', * runner: 'chrome', * timestamp: new Date(), * passed: false, * errors: [ * { * code: 'expect(value).toBe(4)', * name: 'AssertionError', * line: 12, * column: 5, * stack: 'Error: ...', * message: 'Expected 3 to be 4' * } * ], * ancestry: ['Login Suite', 'User Authentication'], * duration: 50, * description: 'should log in successfully' * }; * ``` * * @see StartMessageInterface * @see SuiteErrorInterface * * @since 1.0.0 */ interface EndAssertionMessageInterface extends StartMessageInterface { /** * Indicates whether the assertion passed (`true`) or failed (`false`). * @since 1.0.0 */ passed: boolean; /** * Optional array of errors that occurred during this assertion. * * @see SuiteErrorInterface * @since 1.0.0 */ errors?: Array; /** * The hierarchy of parent suites or `describe` blocks for this assertion. * @since 1.0.0 */ ancestry: Array; /** * The duration of the assertion execution in milliseconds. * @since 1.0.0 */ duration: number; /** * The human-readable description of the assertion. * @since 1.0.0 */ description: string; } /** * Represents a test runner. * * @property id - Unique identifier of the runner * @property name - Name of the runner * * @since 1.0.0 */ interface RunnerInterface { id: string; name: string; } /** * Configuration settings for the test runtime environment * * @since 1.0.0 */ interface RuntimeConfigInterface { /** * Whether to stop test execution after the first failure * * @since 1.0.0 */ bail: boolean; /** * List of test patterns to filter which tests are executed * * @since 1.0.0 */ filter: Array; /** * Maximum time in milliseconds allowed for test execution before timeout * * @since 1.0.0 */ timeout: number; /** * Unique identifier for the test suite being executed * * @since 1.0.0 */ suiteId: string; /** * Unique identifier for the test runner instance * * @since 1.0.0 */ runnerId: string; /** * Path to the test file being executed * * @since 1.0.0 */ path: string; /** * Random test determinism * * @since 1.0.0 */ randomize: boolean; } /** * Represents an interface for managing running test suites with promise control functions * * @see PromiseRejectType * @see PromiseResolveType * * @since 1.0.0 */ interface RunningSuitesInterface { /** * Function to reject the promise associated with the running suite * * @since 1.0.0 */ resolve: PromiseRejectType; /** * Function to resolve the promise associated with the running suite * * @since 1.0.0 */ reject: PromiseResolveType; } /** * Defines the log verbosity levels for reporters and test execution. * * @remarks * Each level represents the minimum severity of messages that should be * captured or displayed. Higher levels include all messages from lower levels. * * @example * ```ts * if (log.level >= LogLevel.Warn) { * console.warn(log.message); * } * ``` * * @since 1.0.0 */ declare enum LogLevel { Silent = 0, Error = 1, Warn = 2, Info = 3, Debug = 4 } /** * Defines the types of messages emitted during test execution. * * @remarks * These message types are used internally by reporters, runners, * and event emitters to categorize test events. Each type corresponds * to a specific stage or element of the test lifecycle. * * @example * ```ts * if (message.type === MessageType.Test) { * console.log('Test event received'); * } * ``` * * @since 1.0.0 */ declare const enum MessageType { Test = 1, Describe = 2, EndSuite = 3, StartSuite = 4 } /** * Represents a test runner engine responsible for executing bundled test files. * * @remarks * A `TestRunnerInterface` abstracts the underlying JavaScript engine * that runs the test bundles produced by xJet. * * Its responsibilities include: * - Receiving a bundled test suite and executing it. * - Establishing a communication channel with xJet to stream results and test events. * - Handling timeouts, disconnections, and cleanup. * * Custom runners can be implemented to run tests in different environments * (e.g., Node.js, browser, Deno, or even remote workers). * * @since 1.0.0 */ interface TestRunnerInterface { /** * Optional unique identifier for this runner instance. * * If not provided, xJet will automatically generate and assign * a runner ID when the runner is registered. * * @since 1.0.0 */ id?: string; /** * Human-readable name of the test runner (e.g., `"NodeRunner"`, `"BrowserRunner"`). * * @since 1.0.0 */ name: string; /** * Maximum time (in milliseconds) allowed for establishing a connection * between xJet and the runner. * * @since 1.0.0 */ connectionTimeout?: number; /** * Maximum time (in milliseconds) allowed for a test suite execution. * @since 1.0.0 */ dispatchTimeout?: number; /** * Sends a compiled/bundled test suite to the runner for execution. * * @param suite - The compiled JavaScript test suite as a binary buffer. * @param suiteId - A unique identifier for the test suite. * @param path - The test file path (relative to the project root). * @returns A promise that resolves once the suite has been successfully dispatched. * * @since 1.0.0 */ dispatch(suite: Buffer, suiteId: string, path: string): Promise | void; /** * Establishes a communication channel with the runner to receive results. * * @param resolve - Callback invoked whenever the runner sends results back. * @param runnerId - A unique identifier for this runner instance. * @param argv - Optional arguments to pass throw the cli. * * @returns A promise that resolves once the connection is active. * * @since 1.0.0 */ connect(resolve: (data: Buffer) => void, runnerId: string, argv: Record): Promise | void; /** * Disconnects the runner and cleans up resources. * * @returns A promise that resolves once the disconnection is complete. * * @since 1.0.0 */ disconnect?(): Promise | void; } /** * Defines the configuration options available for the xJet test runner. * * @remarks * The configuration controls test discovery, filtering, reporting, execution * behavior, and build options. * * @since 1.0.0 */ interface ConfigurationInterface { /** * Positional arguments passed to xJet that are not recognized as flags. * @since 1.0.0 */ _: Array; /** * If `true`, stop running tests after the first failure. * @since 1.0.0 */ bail: boolean; /** * If `true`, watch files for changes and re-run tests automatically. * @since 1.0.0 */ watch: boolean; /** * Glob patterns or file paths used to discover test files. * * @example * ```ts * files: ["**\/*.test.ts", "**\/*.spec.ts", "src/specific/file.test.ts"] * ``` * * @since 1.0.0 */ files: Array; /** * A subset of test files (by path or glob) selected from {@link files}. * * @remarks * - Supports glob syntax (e.g., `"tests/unit/**\/*.test.ts"`). * - Can also include explicit absolute or relative file paths. * - Entries must resolve to files already discovered in {@link files}, * or be parent directories of such files. * - Acts as a filter on top of {@link files}: only the matching files will run. * - If not set, all files from {@link files} will run. * * @example * ```ts * files: ["**\/*.test.ts"], * suites: ["tests/unit/**\/*.test.ts"] // runs only tests in `tests/unit` * * files: ["**\/*.test.ts"], * suites: ["tests/math/add.test.ts"] // runs only this file * ``` * * @since 1.0.0 */ suites: Array; /** * A list of test names (`it`, `test`) or suite names (`describe`) to run. * * @remarks * - If set, only the tests or suites listed here will be executed. * - If not set, all tests in the discovered files will run. * * @since 1.0.0 */ filter: Array; /** * Logging verbosity level for test execution. * * @remarks * Determines which messages are shown during test runs. * Controlled via {@link LogLevel}, which includes levels such as * `Silent`, `Error`, `Warn`, `Info`, `Trace`, and `Debug`. * * This provides finer control than the `silent` flag, * allowing reporters or console output to show only the * desired level of detail. * * @since 1.0.0 */ logLevel: keyof typeof LogLevel; /** * Maximum time (in milliseconds) a single test can run before being marked as failed. * @since 1.0.0 */ timeout: number; /** * If true, include both xJet internal and native stack traces in error output. * * @remarks * - When `false`, stack traces are minimized to user code only. * - When `true`, full stack traces are printed, including internal frames. * * @since 1.0.0 */ verbose: boolean; /** * A list of files or patterns to exclude from the test run. * * @since 1.0.0 */ exclude: Array; /** * The reporter to use for test results. * * @remarks * - Accepts either a built-in reporter name or a path to a custom reporter module. * - Built-in reporters: `"spec"` (default), `"json"`, `"junit"`. * - If a file path is provided, it must resolve to a JavaScript module * that exports a reporter implementation. * * @example * ```ts * reporter: "spec" // Use a built-in spec reporter. * reporter: "json" // Output results as JSON * reporter: "junit" // Output results in JUnit XML format * reporter: "./my-reporter.ts" // Use a custom reporter from a local file * ``` * * @since 1.0.0 */ reporter: string | 'spec' | 'junit' | 'json'; /** * Number of test files to run in parallel. * @since 1.0.0 */ parallel: number; /** * If `true`, randomize the order of test execution. * @since 1.0.0 */ randomize: boolean; /** * If `true`, omit stack traces entirely from error output. * @since 1.0.0 */ noStackTrace: boolean; /** * Optional list of custom test runners to use instead of the default Node.js runner. * @since 1.0.0 */ testRunners?: Array; /** * Optional file path to write reporter output. * * @remarks * - If set, results will be printed to `stdout` and also written to this file. * - Useful for CI/CD pipelines that require machine-readable results * (e.g., `junit.xml` or `results.json`). * * @example * ```ts * reporter: "junit", * outputFile: "reports/junit.xml" * ``` * * @since 1.1.0 */ outputFile?: string; /** * Optional object containing user-defined CLI options parsed by `yargs`. * * @remarks * - This allows users to define custom CLI options dynamically at runtime. * - Keys are option names, values are typed according to `yargs` parsing rules. * - Supports strings, numbers, booleans, arrays, and nested options. * * @example * ```ts * userArgv: { * host: "localhost", * port: 8080, * debug: true * } * ``` * * @since 1.0.0 */ userArgv?: Record; /** * Build configuration applied when transpiling or bundling test files. * @since 1.0.0 */ build: { /** * ECMAScript target(s) for build output (e.g., `"esnext"`, `"es2019"`). * @since 1.0.0 */ target?: BuildOptions['target']; /** * External dependencies to exclude from the test bundle. * @since 1.0.0 */ external?: BuildOptions['external']; /** * Platform target for execution: * - `"browser"` * - `"node"` * - `"neutral"` * * @since 1.0.0 */ platform?: BuildOptions['platform']; /** * Defines how packages are resolved: * - `"bundle"` → include them in the output bundle * - `"external"` → require them at runtime * * @since 1.0.0 */ packages?: BuildOptions['packages']; }; } /** * Represents a configuration object specific to xJet, allowing for partial and deeply nested properties to be defined. * * This type is a partial deep version of the `ConfigurationInterface`, enabling flexible configuration by only requiring * the properties that need to be customized, while other properties can take their default values. * * @remarks * The `xJetConfig` type is useful when working with extensive configuration objects where only a subset of properties * needs to be overridden. It enables better maintainability and cleaner code by avoiding the need to specify the entire * structure of the `ConfigurationInterface`. * * @see ConfigurationInterface * * @since 1.0.0 */ type xJetConfig = Partial; /** * Represents a callback function type used for parameterized test suite definitions. * * @template T - The type of arguments passed to the test function * * @param name - The title of the describe block, which can include parameter placeholders * @param fn - The function containing the tests to be run, which receives the test parameters * * @returns void * * @remarks * This type definition is used for creating parameterized test suites where test data * is passed to the test function. The name parameter supports various placeholder formats * to incorporate test data into the test suite title. * * @since 1.0.0 */ type DescribeCallbackType = (name: string, fn: (args: T) => void) => void; /** * Interface defining the describe directive functionality for test organization. * * The describe directive creates a block that groups together related tests. * It serves as the primary organizational structure for test suites, allowing * developers to group related test cases and create a hierarchy of test blocks. * * @template T - The type parameter for the describe directive * * @remarks * Describe blocks can be nested within each other to create logical groupings of tests. * They can also have before/after hooks attached to them for setup and teardown code. * * @example * ```ts * describe('Calculator', () => { * describe('add method', () => { * test('adds two positive numbers', () => { * expect(calculator.add(1, 2)).toBe(3); * }); * * test('adds a positive and negative number', () => { * expect(calculator.add(1, -2)).toBe(-1); * }); * }); * }); * ``` * * @see TestCase * @see TestDirectiveInterface * * @since 1.0.0 */ interface DescribeDirectiveInterface { /** * Executes a test suite block with the given name and test function. * * @param name - The title of the test suite * @param fn - The function containing the tests to be run within this suite * * @returns void * * @example * ```ts * describe('User authentication', () => { * test('should log in with valid credentials', () => { * // Test implementation * expect(login('user', 'password')).toBe(true); * }); * * test('should fail with invalid credentials', () => { * // Test implementation * expect(login('user', 'wrong')).toBe(false); * }); * }); * ``` * * @since 1.0.0 */ (name: string, fn: () => void): void; /** * Marks this describe to be skipped during test execution. * * @returns this - The current instance for method chaining * * @example * ```ts * describe.skip('Features under development', () => { * test('new feature', () => { * // This test will be skipped * }); * }); * ``` * * @since 1.0.0 */ get skip(): this; /** * Marks this test suite to be the only one executed in the current context. * * @returns this - The current instance for method chaining * * @example * ```ts * describe.only('Critical functionality', () => { * test('core feature', () => { * // Only this suite will run * }); * }); * ``` * * @since 1.0.0 */ get only(): this; /** * Creates parameterized test suites using template literals with placeholders. * * @template T - Array type representing the test case data * * @param string - Template string with placeholders for test data * @param placeholders - Values to be substituted into the template string placeholders * * @returns A callback function that accepts a test name pattern and implementation function * * @remarks * The name parameter can include formatters: * - Generate unique test titles by positionally injecting parameters with printf formatting: * - %p - pretty-format * - %s - String * - %d - Number * - %i - Integer * - %f - Floating point value * - %j - JSON * - %o - Object * - %# - Index of the test case * - %% - Single percent sign ('%'). This does not consume an argument * - Or generate unique test titles by injecting properties of test case object with $variable: * - To inject nested object values supply a keyPath i.e. $variable.path.to.value (only works for "own" properties) * - Use $# to inject the index of the test case * - You cannot use $variable with printf formatting except for %% * * The fn parameter is the function that will receive the parameters in each row as function arguments. * Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds. * * @example * ```ts * describe.each` * a | b | expected * ${1} | ${1} | ${2} * ${2} | ${3} | ${5} * `('$a + $b = $expected', ({ a, b, expected }) => { * test('adds correctly', () => { * expect(a + b).toBe(expected); * }); * }); * ``` * * @see DescribeCallbackType * @since 1.0.0 */ each>(string: TemplateStringsArray, ...placeholders: T): DescribeCallbackType>; /** * Creates parameterized test suites from arrays of test case values. * * @template T - Type representing arrays of test cases * * @param cases - Arrays containing the test case data * * @returns A callback function that accepts a test name pattern and implementation function * * @remarks * The name parameter can include formatters: * - Generate unique test titles by positionally injecting parameters with printf formatting: * - %p - pretty-format * - %s - String * - %d - Number * - %i - Integer * - %f - Floating point value * - %j - JSON * - %o - Object * - %# - Index of the test case * - %% - Single percent sign ('%'). This does not consume an argument * - Or generate unique test titles by injecting properties of test case object with $variable: * - To inject nested object values supply a keyPath i.e. $variable.path.to.value (only works for "own" properties) * - Use $# to inject the index of the test case * - You cannot use $variable with printf formatting except for %% * * The fn parameter is the function that will receive the parameters in each row as function arguments. * Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds. * * @example * ```ts * describe.each([ * [1, 1, 2], * [2, 3, 5] * ])('add(%i, %i) = %i', (a, b, expected) => { * test('adds correctly', () => { * expect(a + b).toBe(expected); * }); * }); * ``` * * @see DescribeCallbackType * @since 1.0.0 */ each | [ unknown ]>(...cases: T[]): DescribeCallbackType; /** * Creates parameterized test suites from individual test case values. * * @template T - Type representing the test case data * * @param args - Individual test case values * * @returns A callback function that accepts a test name pattern and implementation function * * @remarks * The name parameter can include formatters: * - Generate unique test titles by positionally injecting parameters with printf formatting: * - %p - pretty-format * - %s - String * - %d - Number * - %i - Integer * - %f - Floating point value * - %j - JSON * - %o - Object * - %# - Index of the test case * - %% - Single percent sign ('%'). This does not consume an argument * - Or generate unique test titles by injecting properties of test case object with $variable: * - To inject nested object values supply a keyPath i.e. $variable.path.to.value (only works for "own" properties) * - Use $# to inject the index of the test case * - You cannot use $variable with printf formatting except for %% * * The fn parameter is the function that will receive the parameters in each row as function arguments. * Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds. * * @example * ```ts * describe.each( * { name: 'John', age: 30 }, * { name: 'Jane', age: 25 } * )('Testing $name', (person) => { * test('age check', () => { * expect(person.age).toBeGreaterThan(18); * }); * }); * ``` * * @see DescribeCallbackType * @since 1.0.0 */ each(...args: readonly T[]): DescribeCallbackType; /** * Creates parameterized test suites from individual objects or primitive values. * * @template T - Array type representing the test case data * * @param args - Individual test case values in an array * * @returns A callback function that accepts a test name pattern and implementation function * * @remarks * The name parameter can include formatters: * - Generate unique test titles by positionally injecting parameters with printf formatting: * - %p - pretty-format * - %s - String * - %d - Number * - %i - Integer * - %f - Floating point value * - %j - JSON * - %o - Object * - %# - Index of the test case * - %% - Single percent sign ('%'). This does not consume an argument * - Or generate unique test titles by injecting properties of test case object with $variable: * - To inject nested object values supply a keyPath i.e. $variable.path.to.value (only works for "own" properties) * - Use $# to inject the index of the test case * - You cannot use $variable with printf formatting except for %% * * The fn parameter is the function that will receive the parameters in each row as function arguments. * Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds. * * @example * ```ts * describe.each( * 1, 2, 3, 4 * )('Testing with value %i', (value) => { * test('is positive', () => { * expect(value).toBeGreaterThan(0); * }); * }); * ``` * * @see DescribeCallbackType * * @since 1.0.0 */ each>(...args: T): DescribeCallbackType; /** * Invokes a test block with the specified description and function. * * @param description - String for the title of the test block * @param block - Function that contains the test logic to be executed * @param args - Optional array of arguments to pass to the test function * * @remarks * The description parameter can include formatters: * - Generate unique test titles by positionally injecting parameters with printf formatting: * - %p - pretty-format * - %s - String * - %d - Number * - %i - Integer * - %f - Floating point value * - %j - JSON * - %o - Object * - %# - Index of the test case * - %% - Single percent sign ('%'). This does not consume an argument * - Or generate unique test titles by injecting properties of test case object with $variable: * - To inject nested object values supply a keyPath i.e. $variable.path.to.value (only works for "own" properties) * - Use $# to inject the index of the test case * - You cannot use $variable with printf formatting except for %% * * The block parameter is the function that will receive the parameters in each row as function arguments. * Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds. * * @returns void */ invoke(description: string, block: FunctionType, args?: Array): void; } /** * Represents a test callback function that registers a named test with arguments and optional done callback * * @template T - The type of arguments passed to the test function * * @param name - The descriptive name of the test * @param fn - The test implementation function that either accepts arguments and a done callback, or returns a Promise * @returns A void function that registers the test in the testing framework * * @example * ```ts * const testEach: TestCallbackType<{value: number}> = (name, fn) => { * test(`Test ${name}`, (done) => { * fn({value: 42}, done); * }); * }; * ``` * * @see TestDirectiveInterface - The interface that utilizes this callback type * @since 1.0.0 */ type TestCallbackType = (name: string, fn: (args: T, done: DoneCallbackType) => void | ((args: T) => Promise)) => void; interface TestDirectiveInterface { /** * Registers a test case with the given name and optional callback function * * @param name - The descriptive name of the test case * @param fn - The callback function containing the test implementation * @param timeout - The maximum time in milliseconds the test is allowed to run before timing out * @returns Nothing * * @example * ```ts * test('should validate user input', () => { * const result = validateInput('test@example.com'); * expect(result).toBe(true); * }); * * test('should handle async operations', async () => { * const data = await fetchUserData(1); * expect(data.name).toBe('John'); * }, 5000); * ``` * * @see CallbackHandlerType - The type definition for the test callback function * @since 1.0.0 */ (name: string, fn?: CallbackHandlerType, timeout?: number): void; /** * Creates a skipped test that will be recognized but not executed during test runs * * @override * @returns The same TestDirectiveInterface instance with skip flag enabled, allowing for method chaining * @throws Error - When attempting to combine with 'only' flag which would create conflicting test behavior * * @remarks * When applied, the test will be marked as skipped in test reports but won't be executed. * Cannot be combined with the 'only' modifier due to conflicting behavior. * * @example * ```ts * test.skip('temporarily disabled test', () => { * expect(result).toBe(true); * }); * ``` * * @see TestDirectiveInterface * @since 1.0.0 */ get skip(): TestDirectiveInterface; /** * Creates an exclusive test that will run while other non-exclusive tests are skipped * * @override * @returns The same TestDirectiveInterface instance with only flag enabled, allowing for method chaining * @throws Error - When attempting to combine with 'skip' flag which would create conflicting test behavior * * @remarks * When applied, only this test and other tests marked with 'only' will be executed. * This is useful for focusing on specific tests during development or debugging. * Cannot be combined with the 'skip' modifier due to conflicting behavior. * * @example * ```ts * test.only('focus on this test', () => { * const result = performOperation(); * expect(result).toBe(expectedValue); * }); * ``` * * @see TestDirectiveInterface * @since 1.0.0 */ get only(): TestDirectiveInterface; /** * Marks a test as planned but not yet implemented or currently incomplete * * @override * @returns The same TestDirectiveInterface instance with todo flag enabled, allowing for method chaining * @throws Error - When attempting to combine with 'skip' flag which would create redundant test configuration * * @remarks * Tests marked as todo will be reported in test results as pending or incomplete. * This is useful for planning test cases before implementing them or for documenting * tests that need to be written in the future. * * @example * ```ts * test.todo('implement validation test for email addresses'); * * // Or with empty implementation * test.todo('handle error cases', () => { * // To be implemented * }); * ``` * * @see TestDirectiveInterface * @since 1.0.0 */ get todo(): TestDirectiveInterface; /** * Marks a test that is expected to fail, allowing tests to be committed even with known failures * * @override * @returns The same TestDirectiveInterface instance with failing flag enabled, allowing for method chaining * @throws Error - When attempting to combine with incompatible directives that would create ambiguous test behavior * * @remarks * The failing directive is useful when you want to document a bug that currently makes a test fail. * Tests marked as failing will be reported as passed when they fail, and failed when they pass. * This helps maintain test suites that contain tests for known issues or bugs that haven't been fixed yet. * * @example * ```ts * test.failing('this bug is not fixed yet', () => { * const result = buggyFunction(); * expect(result).toBe(expectedValue); // This will fail as expected * }); * ``` * * @see TestDirectiveInterface * @since 1.0.0 */ get failing(): TestDirectiveInterface; /** * Creates a parameterized test suite with table data defined using template literals * * @template T - Array type containing the values for parameterized tests * @param string - Template strings array containing the table header and row structure * @param placeholders - Values to be inserted into the template strings to form the test data table * @returns A function that accepts a title template and callback to define the test suite * @throws Error - When the template format is invalid or doesn't match the provided values * * @remarks * This method allows creating data-driven tests with a table-like syntax using template literals. * Each row in the provided table represents a separate test case with different inputs. * The values from each row will be mapped to named parameters in the test callback. * * The description supports parameter formatting with the following placeholders: * - %p - pretty-format output * - %s - String value * - %d, %i - Number as integer * - %f - Floating point value * - %j - JSON string * - %o - Object representation * - %# - Index of the test case * - %% - Single percent sign (doesn't consume an argument) * * Alternatively, you can inject object properties using $variable notation: * - $variable - Injects the property value * - $variable.path.to.value - Injects nested property values (works only with own properties) * - $# - Injects the index of the test case * - Note: $variable cannot be combined with printf formatting except for %% * * @example * ```ts * test.each` * a | b | expected * ${1} | ${1} | ${2} * ${2} | ${2} | ${4} * ${3} | ${3} | ${6} * `('$a + $b should be $expected', ({a, b, expected}) => { * expect(a + b).toBe(expected); * }); * ``` * @see each * @see TestCallbackType * * @since 1.0.0 */ each>(string: TemplateStringsArray, ...placeholders: T): TestCallbackType>; /** * Creates a parameterized test suite with an array of test cases * * @template T - Array type representing the structure of each test case * @param cases - One or more test cases, where each case is an array of values * @returns A function that accepts a title template and callback to define the test suite * @throws Error - When invalid test cases are provided or parameter count doesn't match the callback * * @remarks * This method allows creating data-driven tests by providing an array of test cases. * Each case array represents a separate test run with different parameters. * The values from each array will be passed as arguments to the test callback function. * * The description supports parameter formatting with the following placeholders: * - %p - pretty-format output * - %s - String value * - %d, %i - Number as integer * - %f - Floating point value * - %j - JSON string * - %o - Object representation * - %# - Index of the test case * - %% - Single percent sign (doesn't consume an argument) * * Alternatively, you can inject object properties using $variable notation: * - $variable - Injects the property value * - $variable.path.to.value - Injects nested property values (works only with own properties) * - $# - Injects the index of the test case * - Note: $variable cannot be combined with printf formatting except for %% * * @example * ```ts * test.each( * [1, 1, 2], * [2, 2, 4], * [3, 3, 6] * )('adds %i + %i to equal %i', (a, b, expected) => { * expect(a + b).toBe(expected); * }); * ``` * @see each * @see TestCallbackType * * @since 1.0.0 */ each | [ unknown ]>(...cases: T[]): TestCallbackType; /** * Creates a parameterized test suite with an array of generic test cases * * @template T - Type representing the structure of each test case * @param args - One or more test cases of type T to be used as parameters * @returns A function that accepts a title template and callback to define the test suite * @throws Error - When invalid test cases are provided or parameter format doesn't match the callback expectations * * @remarks * This method provides a flexible way to create data-driven tests using a variety of case types. * The test callback will be executed once for each provided test case. * Parameter values from each case will be passed to the test callback function. * * The description supports parameter formatting with the following placeholders: * - %p - pretty-format output * - %s - String value * - %d, %i - Number as integer * - %f - Floating point value * - %j - JSON string * - %o - Object representation * - %# - Index of the test case * - %% - Single percent sign (doesn't consume an argument) * * Alternatively, you can inject object properties using $variable notation: * - $variable - Injects the property value * - $variable.path.to.value - Injects nested property values (works only with own properties) * - $# - Injects the index of the test case * - Note: $variable cannot be combined with printf formatting except for %% * * @example * ```ts * // Using objects as test cases * test.each( * { a: 1, b: 1, expected: 2 }, * { a: 2, b: 2, expected: 4 }, * { a: 3, b: 3, expected: 6 } * )('adds $a + $b to equal $expected', ({a, b, expected}) => { * expect(a + b).toBe(expected); * }); * ``` * * @see each * @see TestCallbackType * @since 1.0.0 */ each(...args: readonly T[]): TestCallbackType; /** * Creates a parameterized test suite by spreading an array of test cases * * @template T - Array type containing the individual test cases * @param args - Individual test cases spread from an array * @returns A function that accepts a title template and callback to define the test suite * @throws Error - When invalid test cases are provided or case format is incompatible with the test callback * * @remarks * This method enables data-driven testing by spreading an array of test cases into individual parameters. * Each element in the array represents a separate test case that will be executed individually. * The test callback will be invoked once for each test case in the array. * * The description supports parameter formatting with the following placeholders: * - %p - pretty-format output * - %s - String value * - %d, %i - Number as integer * - %f - Floating point value * - %j - JSON string * - %o - Object representation * - %# - Index of the test case * - %% - Single percent sign (doesn't consume an argument) * * Alternatively, you can inject object properties using $variable notation: * - $variable - Injects the property value * - $variable.path.to.value - Injects nested property values (works only with own properties) * - $# - Injects the index of the test case * - Note: $variable cannot be combined with printf formatting except for %% * * @example * ```ts * const testCases = [ * [1, 1, 2], * [2, 2, 4], * [3, 3, 6] * ]; * * test.each(...testCases)('adds %i + %i to equal %i', (a, b, expected) => { * expect(a + b).toBe(expected); * }); * ``` * @see each * @see TestCallbackType * * @since 1.0.0 */ each>(...args: T): TestCallbackType; /** * Executes a function block as a test case with the specified description * * @param description - Human-readable description of what this test case is verifying * @param block - Function to be executed as the test case implementation * @param args - Optional array of arguments to pass to the test function * @param timeout - Optional timeout in milliseconds for this specific test case * @returns void * @throws Error - When the test function throws an exception or an assertion fails * * @remarks * This method provides a way to directly invoke a test function with optional arguments. * It registers the test with the test runner and executes it during the test run phase. * The provided description will be used for test reporting and identification. * * @example * ```ts * test.invoke('should add two numbers correctly', (a, b) => { * expect(a + b).toBe(3); * }, [1, 2], 1000); * ``` * * @see FunctionType * @since 1.0.0 */ invoke(description: string, block: FunctionType, args?: Array, timeout?: number): void; } /** * Represents a callback function type used to signal the completion of an operation. * Typically used in asynchronous functions to convey success or error states. * * @param error - An optional parameter indicating the error details. * Pass a string or an object with a `message` property to specify the error reason. * If no error occurs, this parameter may be omitted or set to `undefined`. * * @remarks * This type is designed for scenarios requiring explicit error signaling. * Consumers of this callback should handle both error and non-error cases appropriately. * * @since 1.0.0 */ type DoneCallbackType = (error?: string | { message: string; }) => void; /** * Represents a type definition for a callback handler function. * * @remarks * This type can either be: * - A synchronous function taking a `done` callback of type `DoneCallbackType` * as an argument and optionally returning `undefined`. * - An asynchronous function that returns a `Promise`. * This type is designed to provide flexibility for synchronous functions operating with a `done` callback * or asynchronous functions using `Promise`. * * @since 1.0.0 */ type CallbackHandlerType = ((done: DoneCallbackType) => void | undefined) | (() => Promise); /** * Creates and registers a hook with the current test suite * * @param hookType - Type of hook to register * @param callback - Function to execute for this hook * @param location - The precise source code location where the error occurred * @param timeout - Maximum execution time in milliseconds * @returns void * * @example * ```ts * createHook(HookType.BEFORE_EACH, () => { * // Setup code to run before each test * resetTestDatabase(); * }, 10000); * ``` * * @see HookType * @see HookModel * @see SuiteState * * @since 1.0.0 */ declare function createHook(hookType: HookType, callback: FunctionType, location: string, timeout?: number): void; /** * Registers an after-all hook to be executed once after all tests in a suite have completed * * @param callback - Function to execute after all tests in the suite * @param timeout - Maximum execution time in milliseconds * @returns void * * @throws Error - If called outside a test suite context * * @remarks * This function is a wrapper around the createHook function, specifically for creating AFTER_ALL hooks. * After-all hooks are useful for cleanup operations that should occur once after all tests complete. * * @example * ```ts * afterAllDirective(() => { * // Teardown code to run after all tests * disconnectFromDatabase(); * }, 10000); * ``` * * @see createHook * @see HookType.AFTER_ALL * * @since 1.0.0 */ declare function afterAllDirective(callback: FunctionType, timeout?: number): void; /** * Registers a before-all hook to be executed once before any tests in a suite run * * @param callback - Function to execute before any tests in the suite * @param timeout - Maximum execution time in milliseconds * @returns void * * @throws Error - If called outside a test suite context * * @remarks * This function is a wrapper around the createHook function, specifically for creating BEFORE_ALL hooks. * Before-all hooks are useful for setup operations that should occur once before any tests run. * * @default timeout 5000 * * @example * ```ts * beforeAllDirective(() => { * // Setup code to run before any tests * initializeTestDatabase(); * }, 10000); * ``` * * @see createHook * @see HookType.BEFORE_ALL * * @since 1.0.0 */ declare function beforeAllDirective(callback: FunctionType, timeout?: number): void; /** * Registers an after-each hook to be executed after each test in a suite completes * * @param callback - Function to execute after each test * @param timeout - Maximum execution time in milliseconds * @returns void * * @throws Error - If called outside a test suite context * * @remarks * This function is a wrapper around the createHook function, specifically for creating AFTER_EACH hooks. * After-each hooks run after each test case and are useful for cleanup operations that should occur * after every individual test. * * @default timeout 5000 * * @example * ```ts * afterEachDirective(() => { * // Cleanup code to run after each test * resetTestState(); * }, 8000); * ``` * * @see createHook * @see HookType.AFTER_EACH * * @since 1.0.0 */ declare function afterEachDirective(callback: FunctionType, timeout?: number): void; /** * Registers a before-each hook to be executed before each test in a suite runs * * @param callback - Function to execute before each test * @param timeout - Maximum execution time in milliseconds * * @returns void * * @throws Error - If called outside a test suite context * * @remarks * This function is a wrapper around the createHook function, specifically for creating BEFORE_EACH hooks. * Before-each hooks run before each test case and are useful for setup operations that should occur * before every individual test. * * @default timeout 5000 * * @example * ```ts * beforeEachDirective(() => { * // Setup code to run before each test * prepareTestEnvironment(); * }, 8000); * ``` * * @see createHook * @see HookType.BEFORE_EACH * * @since 1.0.0 */ declare function beforeEachDirective(callback: FunctionType, timeout?: number): void; /** * Represents the types of lifecycle hooks that can be used in testing frameworks or similar systems. * * @remarks * The `HookType` enum defines constants for various lifecycle stages * that are commonly used to implement setup and teardown logic * in testing or other procedural workflows. * * @since 1.0.0 */ declare const enum HookType { AFTER_ALL = "afterAll", BEFORE_ALL = "beforeAll", AFTER_EACH = "afterEach", BEFORE_EACH = "beforeEach" } /** * Provides a virtual timer system that mimics native `setTimeout`/`setInterval` * while allowing controlled execution for deterministic tests. * * @remarks * This service replaces the global timing functions with fake timers so that * time can be manually advanced and callbacks triggered predictably. * It is intended for unit testing scenarios where you need full control over * asynchronous timing without waiting in real time. * * @example * ```ts * useFakeTimers(); * setTimeout(() => console.log('done'), 1000); * advanceTimersByTime(1000); // logs 'done' immediately * useRealTimers(); * ``` * * @since 1.1.0 */ declare class TimerService { /** * Active timers managed by the fake timer engine. * @since 1.1.0 */ readonly timers: Map; /** * Stores original `Date.now` to restore when real timers are re-enabled. * @since 1.1.0 */ readonly originalDateNow: () => number; /** * Stores original global `setTimeout`. * @since 1.1.0 */ readonly originalSetTimeout: typeof setTimeout; /** * Stores original global `setInterval`. * @since 1.1.0 */ readonly originalSetInterval: typeof setInterval; /** * Stores original global `clearTimeout`. * @since 1.1.0 */ readonly originalClearTimeout: typeof clearTimeout; /** * Stores original global `clearInterval`. * @since 1.1.0 */ readonly originalClearInterval: typeof clearInterval; /** * Simulated current timestamp for the fake timers. * @since 1.1.0 */ private now; /** * Incremental id used to register timers uniquely. * @since 1.1.0 */ private nextId; /** * Replaces the global timer functions with in-memory fakes. * * @remarks * After calling this method, any calls to `setTimeout`, `setInterval`, * `clearTimeout`, or `clearInterval` will be intercepted and stored in the * {@link timers} map instead of scheduling real OS timers. * This allows tests to control time progression manually using * {@link advanceTimersByTime}, {@link runAllTimers}, or * {@link runOnlyPendingTimers}. * * @example * ```ts * timerService.useFakeTimers(); * const id = setTimeout(() => console.log('done'), 1000); * timerService.advanceTimersByTime(1000); // logs "done" immediately * ``` * * @since 1.1.0 */ useFakeTimers(): void; /** * Restores the original global timer APIs and `Date.now`. * * @remarks * This method undoes the effects of {@link useFakeTimers}, re-binding * the native implementations of `setTimeout`, `setInterval`, * `clearTimeout`, `clearInterval`, and `Date.now`. * After calling this, timers once again behave according to real system * time and manual advancement methods such as * {@link advanceTimersByTime} no longer apply. * * @example * ```ts * timerService.useFakeTimers(); * // ...run tests with controlled time... * timerService.useRealTimers(); // restore native timers * ``` * * @since 1.1.0 */ useRealTimers(): void; /** * Clears all active fake timers. * * @remarks * This method removes every timer currently stored in {@link timers}, * effectively resetting the fake timer state without advancing time. * It is useful for cleaning up between tests to ensure no lingering * scheduled callbacks remain. * * @example * ```ts * useFakeTimers(); * setTimeout(() => console.log('A'), 100); * clearAllTimers(); // removes all scheduled timers * advanceTimersByTime(100); // nothing happens * ``` * * @since 1.3.0 */ clearAllTimers(): void; /** * Advances the simulated clock by a specific number of milliseconds and * executes all timers whose scheduled time has elapsed. * * @remarks * Use this method after calling {@link useFakeTimers} to fast-forward the * internal clock without waiting in real time. * Any `setTimeout` or `setInterval` callbacks scheduled within the * advanced period will run immediately in order of their scheduled time. * * @param ms - The number of milliseconds to move the simulated time forward. * * @example * ```ts * timerService.useFakeTimers(); * setTimeout(() => console.log('done'), 500); * timerService.advanceTimersByTime(500); // logs "done" * ``` * * @since 1.1.0 */ advanceTimersByTime(ms: number): void; /** * Executes every scheduled timer until none remain. * * @remarks * This method repeatedly advances the simulated clock to the next * scheduled timer and runs its callback until the {@link timers} map * is empty. * It is useful when you want to immediately flush **all** pending * `setTimeout` or `setInterval` callbacks regardless of their delay, * without specifying a time increment. * * @example * ```ts * timerService.useFakeTimers(); * setTimeout(() => console.log('A'), 100); * setTimeout(() => console.log('B'), 200); * timerService.runAllTimers(); // logs "A" then "B" * ``` * * @since 1.1.0 */ runAllTimers(): void; /** * Executes only the timers that are currently pending at the time of call, * without running any new timers that may be scheduled by those callbacks. * * @remarks * Unlike {@link runAllTimers}, this method captures the set of timers * that exist when the method is invoked and restricts execution to that * initial set. * If any of those timers schedule additional timers while running, * the newly scheduled ones will **not** be executed during this call. * * @example * ```ts * timerService.useFakeTimers(); * setTimeout(() => { * console.log('first'); * setTimeout(() => console.log('second'), 100); * }, 100); * * timerService.runOnlyPendingTimers(); * // Logs only "first" because "second" was created afterward. * ``` * * @since 1.1.0 */ runOnlyPendingTimers(): void; /** * Asynchronous equivalent of {@link runAllTimers}. * * @remarks * This method first yields to the event loop to allow any pending promises * to resolve before executing all remaining fake timers. * It ensures a deterministic sequence when timers and microtasks coexist. * * @example * ```ts * useFakeTimers(); * Promise.resolve().then(() => console.log('microtask')); * setTimeout(() => console.log('timer'), 0); * await timerService.runAllTimersAsync(); * // Logs: * // microtask * // timer * ``` * * @since 1.3.0 */ runAllTimersAsync(): Promise; /** * Asynchronous equivalent of {@link runOnlyPendingTimers}. * * @remarks * This method first yields to the event loop to allow any pending promises * to resolve before executing only currently pending fake timers. * Timers scheduled during execution will not run until explicitly advanced later. * * @example * ```ts * useFakeTimers(); * setTimeout(() => { * console.log('first'); * setTimeout(() => console.log('second'), 100); * }, 100); * await timerService.runOnlyPendingTimersAsync(); * // Logs: * // first * ``` * * @since 1.3.0 */ runOnlyPendingTimersAsync(): Promise; } /** * Globally enables fake timers using the shared {@link TimerService}. * * @remarks * After calling this function, all calls to `setTimeout`, `setInterval`, * `clearTimeout`, and `clearInterval` will be intercepted by the * {@link TimerService} and stored in-memory instead of executing in real time. * This allows deterministic testing by manually advancing time with * {@link advanceTimersByTime}, {@link runAllTimers}, or * {@link runOnlyPendingTimers}. * * @example * ```ts * useFakeTimers(); * setTimeout(() => console.log('done'), 1000); * advanceTimersByTime(1000); // logs "done" immediately * ``` * * @since 1.1.0 */ declare function useFakeTimers(): void; /** * Restores real timers globally using the shared {@link TimerService}. * * @remarks * This function undoes the effects of {@link useFakeTimers}, restoring the * native implementations of `setTimeout`, `setInterval`, `clearTimeout`, * `clearInterval`, and `Date.now`. * After calling this, timers once again behave according to real system time, * and manual advancement methods like {@link advanceTimersByTime} no longer apply. * * @example * ```ts * useFakeTimers(); * // ...run tests with controlled time... * useRealTimers(); // restore native timers * ``` * * @since 1.1.0 */ declare function useRealTimers(): void; /** * Executes all timers currently registered in the {@link TimerService}. * * @remarks * This function repeatedly runs all pending `setTimeout` and `setInterval` * callbacks until no timers remain. * It is equivalent to calling {@link TimerService.runAllTimers} on the * injected service instance and is useful for immediately flushing * all scheduled timers in tests. * * @example * ```ts * useFakeTimers(); * setTimeout(() => console.log('A'), 100); * setTimeout(() => console.log('B'), 200); * runAllTimers(); // logs "A" then "B" * ``` * * @since 1.1.0 */ declare function runAllTimers(): void; /** * Removes all scheduled fake timers from the {@link TimerService}. * * @remarks * This function clears all active timers registered in the shared timer service, * effectively canceling any pending callbacks that would have run during * timer advancement. * * It's useful for resetting the fake timer state between test cases to ensure * no lingering timers affect further tests or for scenarios where you * need to abort all pending operations. * * @example * ```ts * useFakeTimers(); * setTimeout(() => console.log('A'), 100); * setTimeout(() => console.log('B'), 200); * * clearAllTimers(); // removes all scheduled timers * advanceTimersByTime(1000); // nothing happens, not show any logs * ``` * * @since 1.3.0 */ declare function clearAllTimers(): void; /** * Executes only the timers that are pending at the time of invocation. * * @remarks * This function runs the callbacks of timers that exist when the function * is called, without executing any new timers that may be scheduled * during their execution. * It delegates to {@link TimerService.runOnlyPendingTimers} on the injected * service instance. * * @example * ```ts * useFakeTimers(); * setTimeout(() => { * console.log('first'); * setTimeout(() => console.log('second'), 100); * }, 100); * * runOnlyPendingTimers(); * // Logs only "first"; "second" is not executed yet * ``` * * @since 1.1.0 */ declare function runOnlyPendingTimers(): void; /** * Advances the simulated time by a specified number of milliseconds and * executes all timers that are due. * * @remarks * This function delegates to {@link TimerService.advanceTimersByTime} * on the injected service instance. * It is intended to be used after {@link useFakeTimers} to fast-forward * time in tests without waiting for real timers. * * @param ms - The number of milliseconds to advance (default is `0`). * * @example * ```ts * useFakeTimers(); * setTimeout(() => console.log('done'), 500); * advanceTimersByTime(500); // logs "done" * ``` * * @since 1.1.0 */ declare function advanceTimersByTime(ms?: number): void; /** * Asynchronous equivalent of {@link runAllTimers}. * * @remarks * Yields to the event loop before running all pending fake timers. * Useful when working with both Promises and fake timers. * * @example * ```ts * xJet.useFakeTimers(); * Promise.resolve().then(() => console.log('promise done')); * setTimeout(() => console.log('timeout done'), 0); * await xJet.runAllTimersAsync(); * // Logs: * // promise done * // timeout done * ``` * * @since 1.3.0 */ declare function runAllTimersAsync(): Promise; /** * Asynchronous equivalent of {@link runOnlyPendingTimers}. * * @remarks * Yields to the event loop before running only timers that are currently pending. * Any timers scheduled by those callbacks will not be executed until a later call. * * @example * ```ts * useFakeTimers(); * setTimeout(() => { * console.log('first'); * setTimeout(() => console.log('second'), 100); * }, 100); * await runOnlyPendingTimersAsync(); * // Logs only "first" * ``` * * @since 1.3.0 */ declare function runOnlyPendingTimersAsync(): Promise; /** * Interface representing a single timer stored and executed by the {@link TimerService}. * * @remarks * This interface tracks all properties needed to manage both one-time * and repeating timers within the fake timer system. * * @example * ```ts * const timer: TimerInterface = { * id: 1, * time: 1000, * args: [], * callback: () => console.log('done'), * interval: null, * }; * ``` * * @since 1.1.0 */ interface TimerInterface { /** * Unique identifier for the timer. * @since 1.1.0 */ id: number; /** * The simulated timestamp (in milliseconds) when the timer is next due to run. * @since 1.1.0 */ time: number; /** * Arguments passed to the timer's callback function. * @since 1.1.0 */ args: Array; /** * Callback function to execute when the timer triggers. * @since 1.1.0 */ callback: () => void; /** * Interval in milliseconds for repeating timers. * `null` indicates a one-time timer (like `setTimeout`), otherwise behaves like `setInterval`. * * @since 1.1.0 */ interval: number | null; } /** * Checks if a property on an object is provided via a proxy mechanism rather than directly defined. * * @template T - The type of object being checked * * @param obj - The object to inspect * @param key - The property key to check on the object * @returns `true` if the property is provided by a proxy, `false` if directly defined * * @remarks * This function determines whether a property on an object is being provided through * a proxy mechanism (like a Proxy object or getter) rather than being directly defined * on the object itself. It works by checking if the key doesn't exist in the object's * own properties while still returning a non-undefined value when accessed. * * This is useful for: * - Detecting dynamically created properties * - Identifying properties provided via getters or proxies * - Distinguishing between direct properties and inherited/proxied ones * * @example * ```ts * // Regular object with direct property * const directObj = { name: 'Test' }; * console.log(isProxyProperty(directObj, 'name')); // false * * // Object with proxy property * const handler = { * get(target, prop) { * if (prop === 'dynamic') return 'This is dynamic'; * return target[prop]; * } * }; * const proxyObj = new Proxy({}, handler); * console.log(isProxyProperty(proxyObj, 'dynamic')); // true * ``` * * @since 1.2.0 */ declare function isProxyProperty(obj: T, key: keyof T): boolean; /** * Determines if a value is a mock proxy created by the mocking system. * * @param value - The value to check * @returns `true` if the value is a mock proxy, `false` otherwise * * @remarks * This function checks if an object has the internal `__isMockProxy__` symbol property * which is added to all mock proxy objects created by the mocking framework. * * Mock proxies are specialized proxy objects that intercept property access * and method calls while providing mocking capabilities. * * @example * ```ts * const regularObject = { name: 'Test' }; * const mockObject = createMock({ name: 'Test' }); * * isMockProxy(regularObject); // false * isMockProxy(mockObject); // true * ``` * * @since 1.2.2 */ declare function isMockProxy(value: Record): boolean; /** * Creates a mock proxy that intercepts property access on an object. * * @template T - The type of the target object being proxied * @param target - The object to be proxied * @returns A MockProxyInterface that intercepts property access on the target * * @remarks * This function creates a proxy around an object that allows for interception * and customization of property access. The proxy maintains an internal state * that tracks mocked properties and provides mechanisms for customizing getter behavior. * * The proxy implements special properties: * - `__isMockProxy__`: Used to identify mock proxy objects * - `__MockMap__`: Provides access to the internal state for managing mocks * * Property access behavior: * 1. First checks if a custom getter is defined and uses it if available * 2. Then checks if the property has a specific mock implementation * 3. Falls back to the original property on the target object * * @example * ```ts * const user = { name: 'John', getAge: () => 30 }; * const mockUser = createMockProxy(user); * * // Access original property * console.log(mockUser.name); // "John" * * // Add a mock for a property * const mockMap = mockUser.__MockMap__; * mockMap.mocks.set('getAge', () => 25); * * // Now returns the mock implementation * console.log(mockUser.getAge()); // 25 * ``` * * @since 1.2.2 */ declare function createMockProxy(target: T): MockProxyInterface; /** * Creates a spy on a property access for a proxied object. * * @template T - The type of the target object * @template K - The key of the property to spy on * * @param target - The proxy object containing the property to spy on * @param prop - The name of the property to spy on * @returns A MockState object wrapping the property access * * @remarks * This specialized spy function is designed to work with properties accessed through proxy objects. * It handles the complexities of intercepting property access in proxied objects by: * * 1. Locating the proxy object in the global scope if needed * 2. Converting a normal object to a mock proxy if it isn't already one * 3. Setting up a spy on the property get operation * * The function ensures proper cleanup by providing a cleanup function that removes * the spy from the proxy's internal mock map when the spy is restored. * * @throws Error - When the target object cannot be found in the global scope * * @example * ```ts * // With an existing proxy * const proxyObj = createMockProxy({ getData: () => 'data' }); * const spy = spyOnProxyGet(proxyObj, 'getData'); * * proxyObj.getData(); // Spy records this call * spy.verify.called(); // Passes * * // With a normal object (will be converted to proxy) * const obj = { getValue: () => 42 }; * const valueSpy = spyOnProxyGet(obj, 'getValue'); * * obj.getValue(); // Spy records this call * valueSpy.verify.called(); // Passes * ``` * * @since 1.2.2 */ declare function spyOnProxyGet, K extends keyof T>(target: T, prop: K): MockState; /** * Creates a spy on a method or property of an object. * * @template T - The type of the target object * @template K - The key of the property or method to spy on * * @param target - The object containing the method or property to spy on * @param key - The name of the method or property to spy on * @returns A MockState object wrapping the original method or property * * @remarks * This function creates a spy that wraps around an existing method or property on an object. * The spy tracks all calls to the method or access to the property while still executing the original functionality. * * - For methods: The spy preserves the original `this` context and passes all arguments to the original method * - For properties: The spy intercepts property access and returns the original value * * @example * ```ts * // Spying on a method * const user = { * getName: (prefix: string) => prefix + ' John' * }; * const spy = xJet.spyOn(user, 'getName'); * * user.getName('Mr.'); // Returns "Mr. John" * ``` * * @since 1.0.0 */ declare function spyOnImplementation(target: T, key: K): T[K] extends FunctionType ? MockState<(this: ThisParameterType, ...args: Parameters) => PartialResolvedType>> : MockState<() => T[K]>; /** * Interface representing the internal state of a mock proxy. * * @remarks * This interface defines the structure for storing and managing the internal state * of mock proxies, including mock implementations and custom property access behavior. * * @since 1.2.2 */ interface MockProxyStateInterface { /** * Map storing mock implementations for specific properties. * Keys are property names, values are the mock implementations. * * @since 1.2.2 */ mocks: Map; /** * Optional custom getter function that overrides default property access behavior. * When provided, this function is called for all property access on the mock proxy. * * @since 1.2.2 */ customGetter: ((target: object, prop: PropertyKey, receiver: unknown) => unknown) | null; } /** * Interface representing a mock proxy object. * * @remarks * A `MockProxyInterface` defines the structure of objects that have been * wrapped by a mocking proxy system. These proxies intercept property access * and allow for dynamic replacement or monitoring of object properties. * * @since 1.2.2 */ interface MockProxyInterface extends Record { /** * A boolean flag that indicates this object is a mock proxy. * Used for type checking and identification of mock objects. * * @since 1.2.2 */ readonly __isMockProxy__?: true; /** * Provides access to the internal state of the mock proxy, * including mapped mock implementations and custom getter functions. * * @since 1.2.2 */ readonly __MockMap__?: MockProxyStateInterface; } /** * Represents a mockable function interface with a customizable return type, context, * and argument list. This interface extends `MockState` to facilitate tracking * and testing of function behaviors and states. * * @template F - The function / class type being mocked * * @remarks * This interface is useful for creating test doubles or mock implementations that simulate * complex behaviors (allows for both `function-like` behavior and `constructor-like` behavior) * while tracking interactions and state information. * * @see MockState * * @since 1.0.0 */ interface MockableFunctionInterface extends MockState { /** * Constructor signature when the mocked item is used with 'new' */ new (...args: Parameters): ReturnType; /** * Function call signature preserving 'this' context and parameters */ (this: ThisParameterType, ...args: Parameters): ReturnType; } /** * Makes properties of a type or its resolved promise value optional. * Converts `never` to `void` to avoid unassignable types. * * @template T - The type to transform * * @remarks * If `T` is a `PromiseLike` type, this utility unwraps it and makes the resolved value's * properties optional. * If `T` is `never`, it is converted to `void`. * Otherwise, it directly makes `T`'s properties optional. * * @example * ```ts * // Makes properties of User optional * type MaybeUser = PartialResolvedType; * * // Makes properties of resolved User optional * type MaybeAsyncUser = PartialResolvedType>; * * // Never becomes void * type MaybeNever = PartialResolvedType; // void * ``` * * @since 1.2.2 */ type PartialResolvedType = [ T ] extends [ never ] ? void : T extends PromiseLike ? Promise> : Partial; /** * Creates a mock for an object property using property descriptors. * * @template T - The type of the target object containing the property to mock * * @param target - The object containing the property to mock * @param key - The name of the property to mock * @returns A {@link MockState} instance that tracks interactions with the property * * @remarks * The `mockDescriptorProperty` function replaces a property on a target object with a getter/setter * that intercepts access to that property. This allows for monitoring and controlling property * access during tests. The original property can be restored later through the mock's * restore capability. * * Responsibilities: * - Intercepting property access via custom property descriptors * - Capturing the original property value and descriptor * - Creating a {@link MockState} instance to track interactions * - Supporting property restoration through the {@link MockState.mockRestore} method * - Maintaining references in the global {@link MockState.mocks} registry * * @example * ```ts * // Mock a property on an object * const obj = { value: 42 }; * const mockValue = mockDescriptorProperty(obj, 'value'); * ``` * * @see MockState * @since 1.2.0 */ declare function mockDescriptorProperty(target: T, key: string | number | symbol): MockState; /** * Creates a mock function interface with the specified implementation and optional restore function. * * @template ReturnType - The return type of the mocked function. * @template Args - The argument type of the mocked function. Defaults to an array of unknown values. * @template Context - The context type that the mocked function binds to. * * @param implementation - An optional implementation of the mocked function. * @param restore - An optional restore function used to reset the mock. * @returns A mocked function interface with the specified behaviors. * * @remarks * The `fnImplementation` function creates a mock function handler, typically used in testing scenarios. * It transforms regular functions into mockable objects that can be monitored and controlled. * * Responsibilities: * - Creating mock functions with custom implementations * - Supporting restore functionality for resetting mocks * - Providing type-safe mock interfaces via {@link MockableFunctionInterface} * - Integrating with the {@link MockState} system * * @example * ```ts * // Creating a mock with a custom implementation * const mock = xJet.fn((x: number) => x * 2); * console.log(mock(5)); // 10 * * // Creating a mock with a restore function * const mockWithRestore = xJet.fn(undefined, () => { console.log('Restored!'); }); * mockWithRestore.restore(); // "Restored!" * ``` * * @see MockState * @see MockableFunctionInterface * @see FunctionLikeType * * @since 1.2.0 */ declare function fnImplementation, Context>(implementation?: FunctionLikeType, restore?: () => FunctionLikeType | void): MockableFunctionInterface>; /** * Creates a mock implementation of the provided class constructor. * * @param method - The class constructor to mock * @param implementation - Optional custom implementation of the mocked constructor * @returns The mock state associated with the mocked constructor * * @remarks * This overload of the mockImplementation function is specifically designed for mocking class constructors. * It allows for replacing a class implementation during testing while tracking instantiation. * * The implementation function can return a partial instance of the class, which will be used * as the constructed object when the mock is called with 'new'. * * @example * ```ts * class User { * name: string; * age: number; * constructor (name: string, age: number) { * this.name = name; * this.age = age; * } * } * * const MockUser = mockImplementation(User, (name, age) => ({ name, age: age + 1 })); * const user = new MockUser('Alice', 30); // user.age === 31 * MockUser.verify.called(); // passes * ``` * * @since 1.2.2 */ declare function mockImplementation any>(method: F, implementation?: (...args: ConstructorParameters) => PartialResolvedType>): MockState<(...args: ConstructorParameters) => PartialResolvedType>>; /** * Creates a mock implementation of the provided function. * * @param method - The function to mock * @param implementation - Optional custom implementation that returns a partial result * @returns The mock state associated with the mocked function * * @remarks * This overload of the mockImplementation function allows for providing an implementation * that returns a partial result object. This is particularly useful when mocking functions * that return complex objects where only specific properties are relevant for testing. * * The implementation preserves the 'this' context from the original function, allowing * for proper method mocking on objects. * * @example * ```ts * interface User { * id: number; * name: string; * email: string; * } * * function getUser(id: number): User { * // real implementation * return { id, name: 'Real User', email: 'user@example.com' }; * } * * const mockGetUser = mockImplementation(getUser, (id) => ({ id, name: 'Mock User' })); * const user = mockGetUser(123); // { id: 123, name: 'Mock User' } * ``` * * @since 1.2.2 */ declare function mockImplementation(method: F, implementation?: (...args: Parameters) => PartialResolvedType>): MockState<(this: ThisParameterType, ...args: Parameters) => PartialResolvedType>>; /** * Creates a mock for an element with an optional custom implementation. * * @template Element - The type of the element being mocked * * @param item - The element to mock * @param implementation - Optional custom implementation to replace the original element's behavior * @returns A {@link MockState} instance that controls and tracks the mock * * @remarks * The `mockImplementation` function creates a new {@link MockState} instance that wraps * around the provided element, allowing you to observe interactions with it and optionally * override its behavior. This is useful for isolating components during testing by * replacing their dependencies with controlled mocks. * * Responsibilities: * - Creating a trackable mock from any element * - Supporting custom implementation substitution * - Maintaining type safety between the original and mocked elements * - Enabling interaction tracking and verification capabilities * - Providing a fluent API for configuring mock behavior * * @example * ```ts * // Mock a simple value like export const testValue = 'original value' * const mockValue = xJet.mock(testValue); * mockValue.mockReturnValue("mocked value"); * * // Mock a function * const originalFn = (name: string) => `Hello, ${name}!`; * const mockedFn = xJet.mock(originalFn); * * // Configure custom implementation * mockedFn.mockImplementation((name: string) => `Hi, ${name}!`); * * test ('uses mocked function', () => { * const result = xJet.mock(testValue); * expect(result).toBe('Hi, World!'); * expect(mockedFn).toHaveBeenCalledWith('World'); * }); * ``` * * @see MockState * @see FunctionLikeType * * @since 1.2.0 */ declare function mockImplementation(item: Element, implementation?: () => Element): MockState<() => Element>; /** * Export global variables */ declare global { namespace xJet { /** * Mock */ const fn: typeof fnImplementation; const mock: typeof mockImplementation; const spyOn: typeof spyOnImplementation; const clearAllMocks: () => void; const resetAllMocks: () => void; const restoreAllMocks: () => void; /** * Logs */ const log: typeof console.log; const info: typeof console.info; const warn: typeof console.warn; const error: typeof console.error; const debug: typeof console.error; /** * Timers */ const runAllTimers: typeof runAllTimers; const useFakeTimers: typeof useFakeTimers; const useRealTimers: typeof useRealTimers; const clearAllTimers: typeof clearAllTimers; const runAllTimersAsync: typeof runAllTimersAsync; const advanceTimersByTime: typeof advanceTimersByTime; const runOnlyPendingTimers: typeof runOnlyPendingTimers; const runOnlyPendingTimersAsync: typeof runOnlyPendingTimersAsync; } const it: TestDirectiveInterface; const test: TestDirectiveInterface; const expect: typeof xExpect; const describe: DescribeDirectiveInterface; const afterAll: typeof afterAllDirective; const beforeAll: typeof beforeAllDirective; const afterEach: typeof afterEachDirective; const beforeEach: typeof beforeEachDirective; } export { AbstractReporter, AssertionResultInterface, EndAssertionMessageInterface, EndMessageInterface, LogLevel, LogMessageInterface, MessageType, MockState, StartAssertionMessageInterface, StartMessageInterface, SuiteErrorInterface, SuiteInvocationInterface, TestRunnerInterface, encodeErrorSchema, xJetConfig };