vitest-types
Version:
1,387 lines (1,314 loc) • 183 kB
TypeScript
///<reference path="./chai.d.cts" />
import { assert } from 'chai';
import * as chai_2 from 'chai';
import { should } from 'chai';
declare type AddEventListenerOptionsArgument = Parameters<typeof EventTarget.prototype.addEventListener>[2];
/**
* Registers a callback function to be executed once after all tests within the current suite have completed.
* This hook is useful for scenarios where you need to perform cleanup operations after all tests in a suite have run, such as closing database connections or cleaning up temporary files.
*
* **Note:** The `afterAll` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
*
* @param {Function} fn - The callback function to be executed after all tests.
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
* @returns {void}
* @example
* ```ts
* // Example of using afterAll to close a database connection
* afterAll(async () => {
* await database.disconnect();
* });
* ```
*/
export declare function afterAll(fn: AfterAllListener, timeout?: number): void;
declare interface AfterAllListener {
(suite: Readonly<RunnerTestSuite | RunnerTestFile>): Awaitable_2<unknown>;
}
/**
* Registers a callback function to be executed after each test within the current suite has completed.
* This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions.
*
* **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
*
* @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
* @returns {void}
* @example
* ```ts
* // Example of using afterEach to delete temporary files created during a test
* afterEach(async () => {
* await fileSystem.deleteTempFiles();
* });
* ```
*/
export declare function afterEach<ExtraContext = object>(fn: AfterEachListener<ExtraContext>, timeout?: number): void;
declare interface AfterEachListener<ExtraContext = object> {
(context: ExtendedContext<RunnerTestCase | RunnerCustomCase> & ExtraContext, suite: Readonly<RunnerTestSuite>): Awaitable_2<unknown>;
}
export declare interface AfterSuiteRunMeta {
coverage?: unknown;
testFiles: string[];
transformMode: TransformMode | 'browser';
projectName?: string;
}
/**
* Checks if all the boolean types in the {@linkcode Types} array are `true`.
*/
declare type And<Types extends boolean[]> = Types[number] extends true ? true : false;
/** @deprecated do not use, internal helper */
export declare type ArgumentsType<T> = ArgumentsType_2<T>;
declare type ArgumentsType_2<T> = T extends (...args: infer U) => any ? U : never;
declare type ArgumentsType_3<T> = T extends (...args: infer A) => any ? A : never;
/** @deprecated do not use, internal helper */
export declare type Arrayable<T> = Arrayable_2<T>;
declare type Arrayable_2<T> = T | Array<T>;
export { assert }
export declare interface Assertion<T = any> extends VitestAssertion<Chai.Assertion, T>, JestAssertion<T> {
/**
* Ensures a value is of a specific type.
*
* @example
* expect(value).toBeTypeOf('string');
* expect(number).toBeTypeOf('number');
*/
toBeTypeOf: (expected: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined') => void;
/**
* Asserts that a mock function was called exactly once.
*
* @example
* expect(mockFunc).toHaveBeenCalledOnce();
*/
toHaveBeenCalledOnce: () => void;
/**
* Checks that a value satisfies a custom matcher function.
*
* @param matcher - A function returning a boolean based on the custom condition
* @param message - Optional custom error message on failure
*
* @example
* expect(age).toSatisfy(val => val >= 18, 'Age must be at least 18');
*/
toSatisfy: <E>(matcher: (value: E) => boolean, message?: string) => void;
/**
* Checks that a promise resolves successfully at least once.
*
* @example
* await expect(promise).toHaveResolved();
*/
toHaveResolved: () => void;
/**
* Checks that a promise resolves to a specific value.
*
* @example
* await expect(promise).toHaveResolvedWith('success');
*/
toHaveResolvedWith: <E>(value: E) => void;
/**
* Ensures a promise resolves a specific number of times.
*
* @example
* expect(mockAsyncFunc).toHaveResolvedTimes(3);
*/
toHaveResolvedTimes: (times: number) => void;
/**
* Asserts that the last resolved value of a promise matches an expected value.
*
* @example
* await expect(mockAsyncFunc).toHaveLastResolvedWith('finalResult');
*/
toHaveLastResolvedWith: <E>(value: E) => void;
/**
* Ensures a specific value was returned by a promise on the nth resolution.
*
* @example
* await expect(mockAsyncFunc).toHaveNthResolvedWith(2, 'secondResult');
*/
toHaveNthResolvedWith: <E>(nthCall: number, value: E) => void;
/**
* Verifies that a promise resolves.
*
* @example
* await expect(someAsyncFunc).resolves.toBe(42);
*/
resolves: PromisifyAssertion<T>;
/**
* Verifies that a promise rejects.
*
* @example
* await expect(someAsyncFunc).rejects.toThrow('error');
*/
rejects: PromisifyAssertion<T>;
}
export declare interface AssertType {
<T>(value: T): void;
}
export declare const assertType: AssertType;
export declare interface AsymmetricMatchersContaining {
/**
* Matches if the received string contains the expected substring.
*
* @example
* expect('I have an apple').toEqual(expect.stringContaining('apple'));
* expect({ a: 'test string' }).toEqual({ a: expect.stringContaining('test') });
*/
stringContaining: (expected: string) => any;
/**
* Matches if the received object contains all properties of the expected object.
*
* @example
* expect({ a: '1', b: 2 }).toEqual(expect.objectContaining({ a: '1' }))
*/
objectContaining: <T = any>(expected: T) => any;
/**
* Matches if the received array contains all elements in the expected array.
*
* @example
* expect(['a', 'b', 'c']).toEqual(expect.arrayContaining(['b', 'a']));
*/
arrayContaining: <T = unknown>(expected: Array<T>) => any;
/**
* Matches if the received string or regex matches the expected pattern.
*
* @example
* expect('hello world').toEqual(expect.stringMatching(/^hello/));
* expect('hello world').toEqual(expect.stringMatching('hello'));
*/
stringMatching: (expected: string | RegExp) => any;
/**
* Matches if the received number is within a certain precision of the expected number.
*
* @param precision - Optional decimal precision for comparison. Default is 2.
*
* @example
* expect(10.45).toEqual(expect.closeTo(10.5, 1));
* expect(5.11).toEqual(expect.closeTo(5.12)); // with default precision
*/
closeTo: (expected: number, precision?: number) => any;
}
declare type AsyncExpectationResult = Promise<SyncExpectationResult>;
/**
* Represents a value that can be of various types.
*/
declare type AValue = {
[avalue]?: undefined;
} | string | number | boolean | symbol | bigint | null | undefined | void;
/**
* A type which should match anything passed as a value but *doesn't*
* match {@linkcode Mismatch}. It helps TypeScript select the right overload
* for {@linkcode PositiveExpectTypeOf.toEqualTypeOf | .toEqualTypeOf()} and
* {@linkcode PositiveExpectTypeOf.toMatchTypeOf | .toMatchTypeOf()}.
*
* @internal
*/
declare const avalue: unique symbol;
/** @deprecated do not use, internal helper */
export declare type Awaitable<T> = Awaitable_3<T>;
declare type Awaitable_2<T> = T | PromiseLike<T>;
declare type Awaitable_3<T> = T | PromiseLike<T>;
/**
* Represents the base interface for the
* {@linkcode expectTypeOf()} function.
* Provides a set of assertion methods to perform type checks on a value.
*/
declare interface BaseExpectTypeOf<Actual, Options extends {
positive: boolean;
}> {
/**
* Checks whether the type of the value is `any`.
*/
toBeAny: Scolder<ExpectAny<Actual>, Options>;
/**
* Checks whether the type of the value is `unknown`.
*/
toBeUnknown: Scolder<ExpectUnknown<Actual>, Options>;
/**
* Checks whether the type of the value is `never`.
*/
toBeNever: Scolder<ExpectNever<Actual>, Options>;
/**
* Checks whether the type of the value is `function`.
*/
toBeFunction: Scolder<ExpectFunction<Actual>, Options>;
/**
* Checks whether the type of the value is `object`.
*/
toBeObject: Scolder<ExpectObject<Actual>, Options>;
/**
* Checks whether the type of the value is an {@linkcode Array}.
*/
toBeArray: Scolder<ExpectArray<Actual>, Options>;
/**
* Checks whether the type of the value is `number`.
*/
toBeNumber: Scolder<ExpectNumber<Actual>, Options>;
/**
* Checks whether the type of the value is `string`.
*/
toBeString: Scolder<ExpectString<Actual>, Options>;
/**
* Checks whether the type of the value is `boolean`.
*/
toBeBoolean: Scolder<ExpectBoolean<Actual>, Options>;
/**
* Checks whether the type of the value is `void`.
*/
toBeVoid: Scolder<ExpectVoid<Actual>, Options>;
/**
* Checks whether the type of the value is `symbol`.
*/
toBeSymbol: Scolder<ExpectSymbol<Actual>, Options>;
/**
* Checks whether the type of the value is `null`.
*/
toBeNull: Scolder<ExpectNull<Actual>, Options>;
/**
* Checks whether the type of the value is `undefined`.
*/
toBeUndefined: Scolder<ExpectUndefined<Actual>, Options>;
/**
* Checks whether the type of the value is `null` or `undefined`.
*/
toBeNullable: Scolder<ExpectNullable<Actual>, Options>;
/**
* Checks whether the type of the value is **`bigint`**.
*
* @example
* <caption>#### Distinguish between **`number`** and **`bigint`**</caption>
*
* ```ts
* import { expectTypeOf } from 'expect-type'
*
* const aVeryBigInteger = 10n ** 100n
*
* expectTypeOf(aVeryBigInteger).not.toBeNumber()
*
* expectTypeOf(aVeryBigInteger).toBeBigInt()
* ```
*
* @since 1.1.0
*/
toBeBigInt: Scolder<ExpectBigInt<Actual>, Options>;
/**
* Checks whether a function is callable with the given parameters.
*
* __Note__: You cannot negate this assertion with
* {@linkcode PositiveExpectTypeOf.not | .not}, you need to use
* `ts-expect-error` instead.
*
* @example
* ```ts
* const f = (a: number) => [a, a]
*
* expectTypeOf(f).toBeCallableWith(1)
* ```
*
* __Known Limitation__: This assertion will likely fail if you try to use it
* with a generic function or an overload.
* @see {@link https://github.com/mmkal/expect-type/issues/50 | This issue} for an example and a workaround.
*
* @param args - The arguments to check for callability.
* @returns `true`.
*/
toBeCallableWith: Options['positive'] extends true ? <Args extends OverloadParameters<Actual>>(...args: Args) => ExpectTypeOf<OverloadsNarrowedByParameters<Actual, Args>, Options> : never;
/**
* Checks whether a class is constructible with the given parameters.
*
* @example
* ```ts
* expectTypeOf(Date).toBeConstructibleWith('1970')
*
* expectTypeOf(Date).toBeConstructibleWith(0)
*
* expectTypeOf(Date).toBeConstructibleWith(new Date())
*
* expectTypeOf(Date).toBeConstructibleWith()
* ```
*
* @param args - The arguments to check for constructibility.
* @returns `true`.
*/
toBeConstructibleWith: Options['positive'] extends true ? <Args extends ConstructorOverloadParameters<Actual>>(...args: Args) => true : never;
/**
* Equivalent to the {@linkcode Extract} utility type.
* Helps narrow down complex union types.
*
* @example
* ```ts
* type ResponsiveProp<T> = T | T[] | { xs?: T; sm?: T; md?: T }
*
* interface CSSProperties {
* margin?: string
* padding?: string
* }
*
* function getResponsiveProp<T>(_props: T): ResponsiveProp<T> {
* return {}
* }
*
* const cssProperties: CSSProperties = { margin: '1px', padding: '2px' }
*
* expectTypeOf(getResponsiveProp(cssProperties))
* .extract<{ xs?: any }>() // extracts the last type from a union
* .toEqualTypeOf<{
* xs?: CSSProperties
* sm?: CSSProperties
* md?: CSSProperties
* }>()
*
* expectTypeOf(getResponsiveProp(cssProperties))
* .extract<unknown[]>() // extracts an array from a union
* .toEqualTypeOf<CSSProperties[]>()
* ```
*
* __Note__: If no type is found in the union, it will return `never`.
*
* @param v - The type to extract from the union.
* @returns The type after extracting the type from the union.
*/
extract: <V>(v?: V) => ExpectTypeOf<Extract<Actual, V>, Options>;
/**
* Equivalent to the {@linkcode Exclude} utility type.
* Removes types from a union.
*
* @example
* ```ts
* type ResponsiveProp<T> = T | T[] | { xs?: T; sm?: T; md?: T }
*
* interface CSSProperties {
* margin?: string
* padding?: string
* }
*
* function getResponsiveProp<T>(_props: T): ResponsiveProp<T> {
* return {}
* }
*
* const cssProperties: CSSProperties = { margin: '1px', padding: '2px' }
*
* expectTypeOf(getResponsiveProp(cssProperties))
* .exclude<unknown[]>()
* .exclude<{ xs?: unknown }>() // or just `.exclude<unknown[] | { xs?: unknown }>()`
* .toEqualTypeOf<CSSProperties>()
* ```
*/
exclude: <V>(v?: V) => ExpectTypeOf<Exclude<Actual, V>, Options>;
/**
* Equivalent to the {@linkcode Pick} utility type.
* Helps select a subset of properties from an object type.
*
* @example
* ```ts
* interface Person {
* name: string
* age: number
* }
*
* expectTypeOf<Person>()
* .pick<'name'>()
* .toEqualTypeOf<{ name: string }>()
* ```
*
* @param keyToPick - The property key to pick.
* @returns The type after picking the property.
*/
pick: <KeyToPick extends keyof Actual>(keyToPick?: KeyToPick) => ExpectTypeOf<Pick<Actual, KeyToPick>, Options>;
/**
* Equivalent to the {@linkcode Omit} utility type.
* Helps remove a subset of properties from an object type.
*
* @example
* ```ts
* interface Person {
* name: string
* age: number
* }
*
* expectTypeOf<Person>().omit<'name'>().toEqualTypeOf<{ age: number }>()
* ```
*
* @param keyToOmit - The property key to omit.
* @returns The type after omitting the property.
*/
omit: <KeyToOmit extends keyof Actual | (PropertyKey & Record<never, never>)>(keyToOmit?: KeyToOmit) => ExpectTypeOf<Omit<Actual, KeyToOmit>, Options>;
/**
* Extracts a certain function argument with `.parameter(number)` call to
* perform other assertions on it.
*
* @example
* ```ts
* function foo(a: number, b: string) {
* return [a, b]
* }
*
* expectTypeOf(foo).parameter(0).toBeNumber()
*
* expectTypeOf(foo).parameter(1).toBeString()
* ```
*
* @param index - The index of the parameter to extract.
* @returns The extracted parameter type.
*/
parameter: <Index extends number>(index: Index) => ExpectTypeOf<OverloadParameters<Actual>[Index], Options>;
/**
* Equivalent to the {@linkcode Parameters} utility type.
* Extracts function parameters to perform assertions on its value.
* Parameters are returned as an array.
*
* @example
* ```ts
* function noParam() {}
*
* function hasParam(s: string) {}
*
* expectTypeOf(noParam).parameters.toEqualTypeOf<[]>()
*
* expectTypeOf(hasParam).parameters.toEqualTypeOf<[string]>()
* ```
*/
parameters: ExpectTypeOf<OverloadParameters<Actual>, Options>;
/**
* Equivalent to the {@linkcode ConstructorParameters} utility type.
* Extracts constructor parameters as an array of values and
* perform assertions on them with this method.
*
* For overloaded constructors it will return a union of all possible parameter-tuples.
*
* @example
* ```ts
* expectTypeOf(Date).constructorParameters.toEqualTypeOf<
* [] | [string | number | Date]
* >()
* ```
*/
constructorParameters: ExpectTypeOf<ConstructorOverloadParameters<Actual>, Options>;
/**
* Equivalent to the {@linkcode ThisParameterType} utility type.
* Extracts the `this` parameter of a function to
* perform assertions on its value.
*
* @example
* ```ts
* function greet(this: { name: string }, message: string) {
* return `Hello ${this.name}, here's your message: ${message}`
* }
*
* expectTypeOf(greet).thisParameter.toEqualTypeOf<{ name: string }>()
* ```
*/
thisParameter: ExpectTypeOf<ThisParameterType<Actual>, Options>;
/**
* Equivalent to the {@linkcode InstanceType} utility type.
* Extracts the instance type of a class to perform assertions on.
*
* @example
* ```ts
* expectTypeOf(Date).instance.toHaveProperty('toISOString')
* ```
*/
instance: Actual extends new (...args: any[]) => infer I ? ExpectTypeOf<I, Options> : never;
/**
* Equivalent to the {@linkcode ReturnType} utility type.
* Extracts the return type of a function.
*
* @example
* ```ts
* expectTypeOf(() => {}).returns.toBeVoid()
*
* expectTypeOf((a: number) => [a, a]).returns.toEqualTypeOf([1, 2])
* ```
*/
returns: Actual extends Function ? ExpectTypeOf<OverloadReturnTypes<Actual>, Options> : never;
/**
* Extracts resolved value of a Promise,
* so you can perform other assertions on it.
*
* @example
* ```ts
* async function asyncFunc() {
* return 123
* }
*
* expectTypeOf(asyncFunc).returns.resolves.toBeNumber()
*
* expectTypeOf(Promise.resolve('string')).resolves.toBeString()
* ```
*
* Type Equivalent:
* ```ts
* type Resolves<PromiseType> = PromiseType extends PromiseLike<infer ResolvedType>
* ? ResolvedType
* : never
* ```
*/
resolves: Actual extends PromiseLike<infer ResolvedType> ? ExpectTypeOf<ResolvedType, Options> : never;
/**
* Extracts array item type to perform assertions on.
*
* @example
* ```ts
* expectTypeOf([1, 2, 3]).items.toEqualTypeOf<number>()
*
* expectTypeOf([1, 2, 3]).items.not.toEqualTypeOf<string>()
* ```
*
* __Type Equivalent__:
* ```ts
* type Items<ArrayType> = ArrayType extends ArrayLike<infer ItemType>
* ? ItemType
* : never
* ```
*/
items: Actual extends ArrayLike<infer ItemType> ? ExpectTypeOf<ItemType, Options> : never;
/**
* Extracts the type guarded by a function to perform assertions on.
*
* @example
* ```ts
* function isString(v: any): v is string {
* return typeof v === 'string'
* }
*
* expectTypeOf(isString).guards.toBeString()
* ```
*/
guards: Actual extends (v: any, ...args: any[]) => v is infer T ? ExpectTypeOf<T, Options> : never;
/**
* Extracts the type asserted by a function to perform assertions on.
*
* @example
* ```ts
* function assertNumber(v: any): asserts v is number {
* if (typeof v !== 'number')
* throw new TypeError('Nope !')
* }
*
* expectTypeOf(assertNumber).asserts.toBeNumber()
* ```
*/
asserts: Actual extends (v: any, ...args: any[]) => asserts v is infer T ? unknown extends T ? never : ExpectTypeOf<T, Options> : never;
}
/**
* Registers a callback function to be executed once before all tests within the current suite.
* This hook is useful for scenarios where you need to perform setup operations that are common to all tests in a suite, such as initializing a database connection or setting up a test environment.
*
* **Note:** The `beforeAll` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
*
* @param {Function} fn - The callback function to be executed before all tests.
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
* @returns {void}
* @example
* ```ts
* // Example of using beforeAll to set up a database connection
* beforeAll(async () => {
* await database.connect();
* });
* ```
*/
export declare function beforeAll(fn: BeforeAllListener, timeout?: number): void;
declare interface BeforeAllListener {
(suite: Readonly<RunnerTestSuite | RunnerTestFile>): Awaitable_2<unknown>;
}
/**
* Registers a callback function to be executed before each test within the current suite.
* This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables.
*
* **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
*
* @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.
* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
* @returns {void}
* @example
* ```ts
* // Example of using beforeEach to reset a database state
* beforeEach(async () => {
* await database.reset();
* });
* ```
*/
export declare function beforeEach<ExtraContext = object>(fn: BeforeEachListener<ExtraContext>, timeout?: number): void;
declare interface BeforeEachListener<ExtraContext = object> {
(context: ExtendedContext<RunnerTestCase | RunnerCustomCase> & ExtraContext, suite: Readonly<RunnerTestSuite>): Awaitable_2<unknown>;
}
export declare const bench: BenchmarkAPI;
/**
* Both the `Task` and `Bench` objects extend the `EventTarget` object,
* so you can attach a listeners to different types of events
* to each class instance using the universal `addEventListener` and
* `removeEventListener`
*/
/**
* Bench events
*/
declare type BenchEvents = 'abort' | 'complete' | 'error' | 'reset' | 'start' | 'warmup' | 'cycle' | 'add' | 'remove' | 'todo';
declare interface BenchEventsMap {
abort: NoopEventListener;
start: NoopEventListener;
complete: NoopEventListener;
warmup: NoopEventListener;
reset: NoopEventListener;
add: TaskEventListener;
remove: TaskEventListener;
cycle: TaskEventListener;
error: TaskEventListener;
todo: TaskEventListener;
}
/**
* The Benchmark instance for keeping track of the benchmark tasks and controlling
* them.
*/
export declare class BenchFactory extends EventTarget {
_tasks: Map<string, BenchTask>;
_todos: Map<string, BenchTask>;
/**
* Executes tasks concurrently based on the specified concurrency mode.
*
* - When `mode` is set to `null` (default), concurrency is disabled.
* - When `mode` is set to 'task', each task's iterations (calls of a task function) run concurrently.
* - When `mode` is set to 'bench', different tasks within the bench run concurrently.
*/
concurrency: 'task' | 'bench' | null;
/**
* The maximum number of concurrent tasks to run. Defaults to Infinity.
*/
threshold: number;
signal?: AbortSignal;
throws: boolean;
warmupTime: number;
warmupIterations: number;
time: number;
iterations: number;
now: () => number;
setup: Hook;
teardown: Hook;
constructor(options?: BenchOptions);
private runTask;
/**
* run the added tasks that were registered using the
* {@link add} method.
* Note: This method does not do any warmup. Call {@link warmup} for that.
*/
run(): Promise<BenchTask[]>;
/**
* See Bench.{@link concurrency}
*/
runConcurrently(threshold?: number, mode?: NonNullable<BenchFactory['concurrency']>): Promise<BenchTask[]>;
/**
* warmup the benchmark tasks.
* This is not run by default by the {@link run} method.
*/
warmup(): Promise<void>;
/**
* warmup the benchmark tasks concurrently.
* This is not run by default by the {@link runConcurrently} method.
*/
warmupConcurrently(threshold?: number, mode?: NonNullable<BenchFactory['concurrency']>): Promise<void>;
/**
* reset each task and remove its result
*/
reset(): void;
/**
* add a benchmark task to the task map
*/
add(name: string, fn: Fn, opts?: FnOptions): this;
/**
* add a benchmark todo to the todo map
*/
todo(name: string, fn?: Fn, opts?: FnOptions): this;
/**
* remove a benchmark task from the task map
*/
remove(name: string): this;
addEventListener<K extends BenchEvents, T = BenchEventsMap[K]>(type: K, listener: T, options?: AddEventListenerOptionsArgument): void;
removeEventListener<K extends BenchEvents, T = BenchEventsMap[K]>(type: K, listener: T, options?: RemoveEventListenerOptionsArgument): void;
/**
* table of the tasks results
*/
table(convert?: (task: BenchTask) => Record<string, string | number> | undefined): (Record<string, string | number> | null)[];
/**
* (getter) tasks results as an array
*/
get results(): (BenchTaskResult | undefined)[];
/**
* (getter) tasks as an array
*/
get tasks(): BenchTask[];
get todos(): BenchTask[];
/**
* get a task based on the task name
*/
getTask(name: string): BenchTask | undefined;
}
export declare type BenchFunction = (this: BenchFactory) => Promise<void> | void;
export declare interface Benchmark extends RunnerCustomCase {
meta: {
benchmark: true;
result?: BenchTaskResult;
};
}
export declare type BenchmarkAPI = ChainableBenchmarkAPI & {
skipIf: (condition: any) => ChainableBenchmarkAPI;
runIf: (condition: any) => ChainableBenchmarkAPI;
};
export declare interface BenchmarkResult extends BenchTaskResult {
name: string;
rank: number;
sampleCount: number;
median: number;
}
export declare type BenchOptions = {
/**
* time needed for running a benchmark task (milliseconds) @default 500
*/
time?: number;
/**
* number of times that a task should run if even the time option is finished @default 10
*/
iterations?: number;
/**
* function to get the current timestamp in milliseconds
*/
now?: () => number;
/**
* An AbortSignal for aborting the benchmark
*/
signal?: AbortSignal;
/**
* Throw if a task fails (events will not work if true)
*/
throws?: boolean;
/**
* warmup time (milliseconds) @default 100ms
*/
warmupTime?: number;
/**
* warmup iterations @default 5
*/
warmupIterations?: number;
/**
* setup function to run before each benchmark task (cycle)
*/
setup?: Hook;
/**
* teardown function to run after each benchmark task (cycle)
*/
teardown?: Hook;
};
/**
* A class that represents each benchmark task in Tinybench. It keeps track of the
* results, name, Bench instance, the task function and the number times the task
* function has been executed.
*/
export declare class BenchTask extends EventTarget {
bench: BenchFactory;
/**
* task name
*/
name: string;
fn: Fn;
runs: number;
/**
* the result object
*/
result?: BenchTaskResult;
/**
* Task options
*/
opts: FnOptions;
constructor(bench: BenchFactory, name: string, fn: Fn, opts?: FnOptions);
private loop;
/**
* run the current task and write the results in `Task.result` object
*/
run(): Promise<this>;
/**
* warmup the current task
*/
warmup(): Promise<void>;
addEventListener<K extends TaskEvents, T = TaskEventsMap[K]>(type: K, listener: T, options?: AddEventListenerOptionsArgument): void;
removeEventListener<K extends TaskEvents, T = TaskEventsMap[K]>(type: K, listener: T, options?: RemoveEventListenerOptionsArgument): void;
/**
* change the result object values
*/
setResult(result: Partial<BenchTaskResult>): void;
/**
* reset the task to make the `Task.runs` a zero-value and remove the `Task.result`
* object
*/
reset(): void;
}
/**
* the benchmark task result object
*/
export declare type BenchTaskResult = {
error?: unknown;
/**
* The amount of time in milliseconds to run the benchmark task (cycle).
*/
totalTime: number;
/**
* the minimum value in the samples
*/
min: number;
/**
* the maximum value in the samples
*/
max: number;
/**
* the number of operations per second
*/
hz: number;
/**
* how long each operation takes (ms)
*/
period: number;
/**
* task samples of each task iteration time (ms)
*/
samples: number[];
/**
* samples mean/average (estimate of the population mean)
*/
mean: number;
/**
* samples variance (estimate of the population variance)
*/
variance: number;
/**
* samples standard deviation (estimate of the population standard deviation)
*/
sd: number;
/**
* standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean)
*/
sem: number;
/**
* degrees of freedom
*/
df: number;
/**
* critical value of the samples
*/
critical: number;
/**
* margin of error
*/
moe: number;
/**
* relative margin of error
*/
rme: number;
/**
* p75 percentile
*/
p75: number;
/**
* p99 percentile
*/
p99: number;
/**
* p995 percentile
*/
p995: number;
/**
* p999 percentile
*/
p999: number;
};
declare type BirpcFn<T> = PromisifyFn<T> & {
/**
* Send event without asking for response
*/
asEvent: (...args: ArgumentsType_3<T>) => void;
};
declare type BirpcReturn<RemoteFunctions, LocalFunctions = Record<string, never>> = {
[K in keyof RemoteFunctions]: BirpcFn<RemoteFunctions[K]>;
} & {
$functions: LocalFunctions;
$close: () => void;
};
export declare interface BrowserUI {
setCurrentFileId: (fileId: string) => void;
setIframeViewport: (width: number, height: number) => Promise<void>;
}
declare type BuiltinEnvironment = 'node' | 'jsdom' | 'happy-dom' | 'edge-runtime';
export declare type CancelReason = 'keyboard-input' | 'test-failure' | (string & Record<string, never>);
export { chai_2 as chai }
declare type ChainableBenchmarkAPI = ChainableFunction<'skip' | 'only' | 'todo', (name: string | Function, fn?: BenchFunction, options?: BenchOptions) => void>;
declare type ChainableFunction<T extends string, F extends (...args: any) => any, C = object> = F & {
[x in T]: ChainableFunction<T, F, C>;
} & {
fn: (this: Record<T, any>, ...args: Parameters<F>) => ReturnType<F>;
} & C;
declare type ChainableSuiteAPI<ExtraContext = object> = ChainableFunction<'concurrent' | 'sequential' | 'only' | 'skip' | 'todo' | 'shuffle', SuiteCollectorCallable<ExtraContext>, {
each: TestEachFunction;
}>;
declare type ChainableTestAPI<ExtraContext = object> = ChainableFunction<'concurrent' | 'sequential' | 'only' | 'skip' | 'todo' | 'fails', TestCollectorCallable<ExtraContext>, {
each: TestEachFunction;
for: TestForFunction<ExtraContext>;
}>;
declare type Classes<T> = {
[K in keyof T]: T[K] extends new (...args: any[]) => any ? K : never;
}[keyof T] & (string | symbol);
declare type ColorName = keyof typeof colorsMap;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
declare interface Colors {
comment: {
close: string;
open: string;
};
content: {
close: string;
open: string;
};
prop: {
close: string;
open: string;
};
tag: {
close: string;
open: string;
};
value: {
close: string;
open: string;
};
}
declare type Colors_2 = ColorsMethods & {
isColorSupported: boolean;
reset: (input: unknown) => string;
};
declare const colorsMap: {
readonly reset: readonly [0, 0];
readonly bold: readonly [1, 22, "\u001B[22m\u001B[1m"];
readonly dim: readonly [2, 22, "\u001B[22m\u001B[2m"];
readonly italic: readonly [3, 23];
readonly underline: readonly [4, 24];
readonly inverse: readonly [7, 27];
readonly hidden: readonly [8, 28];
readonly strikethrough: readonly [9, 29];
readonly black: readonly [30, 39];
readonly red: readonly [31, 39];
readonly green: readonly [32, 39];
readonly yellow: readonly [33, 39];
readonly blue: readonly [34, 39];
readonly magenta: readonly [35, 39];
readonly cyan: readonly [36, 39];
readonly white: readonly [37, 39];
readonly gray: readonly [90, 39];
readonly bgBlack: readonly [40, 49];
readonly bgRed: readonly [41, 49];
readonly bgGreen: readonly [42, 49];
readonly bgYellow: readonly [43, 49];
readonly bgBlue: readonly [44, 49];
readonly bgMagenta: readonly [45, 49];
readonly bgCyan: readonly [46, 49];
readonly bgWhite: readonly [47, 49];
readonly blackBright: readonly [90, 39];
readonly redBright: readonly [91, 39];
readonly greenBright: readonly [92, 39];
readonly yellowBright: readonly [93, 39];
readonly blueBright: readonly [94, 39];
readonly magentaBright: readonly [95, 39];
readonly cyanBright: readonly [96, 39];
readonly whiteBright: readonly [97, 39];
readonly bgBlackBright: readonly [100, 49];
readonly bgRedBright: readonly [101, 49];
readonly bgGreenBright: readonly [102, 49];
readonly bgYellowBright: readonly [103, 49];
readonly bgBlueBright: readonly [104, 49];
readonly bgMagentaBright: readonly [105, 49];
readonly bgCyanBright: readonly [106, 49];
readonly bgWhiteBright: readonly [107, 49];
};
declare type ColorsMethods = {
[Key in ColorName]: Formatter;
};
declare type CompareKeys = ((a: string, b: string) => number) | null | undefined;
declare interface Config {
callToJSON: boolean;
compareKeys: CompareKeys;
colors: Colors;
escapeRegex: boolean;
escapeString: boolean;
indent: string;
maxDepth: number;
maxWidth: number;
min: boolean;
plugins: Plugins;
printBasicPrototype: boolean;
printFunctionName: boolean;
spacingInner: string;
spacingOuter: string;
}
/** @deprecated do not use, internal helper */
export declare type Constructable = Constructable_4;
declare interface Constructable_2 {
new (...args: any[]): any;
}
declare interface Constructable_3 {
new (...args: any[]): any;
}
declare interface Constructable_4 {
new (...args: any[]): any;
}
/**
* A union type of the parameters allowed for any overload
* of constructor {@linkcode ConstructorType}.
*/
declare type ConstructorOverloadParameters<ConstructorType> = ConstructorOverloadsUnion<ConstructorType> extends InferConstructor<infer Ctor> ? ConstructorParameters<Ctor> : never;
/**
* Get a union of overload variants for a constructor
* {@linkcode ConstructorType}. Does a check for whether we can do the
* one-shot 10-overload matcher (which works for ts\>5.3), and if not,
* falls back to the more complicated utility.
*/
declare type ConstructorOverloadsUnion<ConstructorType> = IsNever<TSPost53ConstructorOverloadsInfoUnion<new (a: 1) => any>> extends true ? TSPre53ConstructorOverloadsInfoUnion<ConstructorType> : TSPost53ConstructorOverloadsInfoUnion<ConstructorType>;
export declare interface ContextRPC {
pool: string;
worker: string;
workerId: number;
config: SerializedConfig;
projectName: string;
files: string[];
environment: ContextTestEnvironment;
providedContext: Record<string, any>;
invalidates?: string[];
}
export declare interface ContextTestEnvironment {
name: string;
transformMode?: TransformMode;
options: Record<string, any> | null;
}
declare function createColors(isTTY?: boolean): Colors_2;
export declare function createExpect(test?: TaskPopulated): ExpectStatic;
/** @deprecated use `RunnerCustomCase` instead */
export declare type Custom = RunnerCustomCase;
/**
* For versions of TypeScript below 5.3, we need to check for 10 overloads,
* then 9, then 8, etc., to get a union of the overload variants.
*/
declare type DecreasingConstructorOverloadsInfoUnion<ConstructorType> = ConstructorType extends {
new (...args: infer A1): infer R1;
new (...args: infer A2): infer R2;
new (...args: infer A3): infer R3;
new (...args: infer A4): infer R4;
new (...args: infer A5): infer R5;
new (...args: infer A6): infer R6;
new (...args: infer A7): infer R7;
new (...args: infer A8): infer R8;
new (...args: infer A9): infer R9;
new (...args: infer A10): infer R10;
} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4) | (new (...p: A5) => R5) | (new (...p: A6) => R6) | (new (...p: A7) => R7) | (new (...p: A8) => R8) | (new (...p: A9) => R9) | (new (...p: A10) => R10) : ConstructorType extends {
new (...args: infer A1): infer R1;
new (...args: infer A2): infer R2;
new (...args: infer A3): infer R3;
new (...args: infer A4): infer R4;
new (...args: infer A5): infer R5;
new (...args: infer A6): infer R6;
new (...args: infer A7): infer R7;
new (...args: infer A8): infer R8;
new (...args: infer A9): infer R9;
} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4) | (new (...p: A5) => R5) | (new (...p: A6) => R6) | (new (...p: A7) => R7) | (new (...p: A8) => R8) | (new (...p: A9) => R9) : ConstructorType extends {
new (...args: infer A1): infer R1;
new (...args: infer A2): infer R2;
new (...args: infer A3): infer R3;
new (...args: infer A4): infer R4;
new (...args: infer A5): infer R5;
new (...args: infer A6): infer R6;
new (...args: infer A7): infer R7;
new (...args: infer A8): infer R8;
} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4) | (new (...p: A5) => R5) | (new (...p: A6) => R6) | (new (...p: A7) => R7) | (new (...p: A8) => R8) : ConstructorType extends {
new (...args: infer A1): infer R1;
new (...args: infer A2): infer R2;
new (...args: infer A3): infer R3;
new (...args: infer A4): infer R4;
new (...args: infer A5): infer R5;
new (...args: infer A6): infer R6;
new (...args: infer A7): infer R7;
} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4) | (new (...p: A5) => R5) | (new (...p: A6) => R6) | (new (...p: A7) => R7) : ConstructorType extends {
new (...args: infer A1): infer R1;
new (...args: infer A2): infer R2;
new (...args: infer A3): infer R3;
new (...args: infer A4): infer R4;
new (...args: infer A5): infer R5;
new (...args: infer A6): infer R6;
} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4) | (new (...p: A5) => R5) | (new (...p: A6) => R6) : ConstructorType extends {
new (...args: infer A1): infer R1;
new (...args: infer A2): infer R2;
new (...args: infer A3): infer R3;
new (...args: infer A4): infer R4;
new (...args: infer A5): infer R5;
} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4) | (new (...p: A5) => R5) : ConstructorType extends {
new (...args: infer A1): infer R1;
new (...args: infer A2): infer R2;
new (...args: infer A3): infer R3;
new (...args: infer A4): infer R4;
} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4) : ConstructorType extends {
new (...args: infer A1): infer R1;
new (...args: infer A2): infer R2;
new (...args: infer A3): infer R3;
} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) : ConstructorType extends {
new (...args: infer A1): infer R1;
new (...args: infer A2): infer R2;
} ? (new (...p: A1) => R1) | (new (...p: A2) => R2) : ConstructorType extends new (...args: infer A1) => infer R1 ? (new (...p: A1) => R1) : never;
/**
* For versions of TypeScript below 5.3, we need to check for 10 overloads,
* then 9, then 8, etc., to get a union of the overload variants.
*/
declare type DecreasingOverloadsInfoUnion<F> = F extends {
(...args: infer A1): infer R1;
(...args: infer A2): infer R2;
(...args: infer A3): infer R3;
(...args: infer A4): infer R4;
(...args: infer A5): infer R5;
(...args: infer A6): infer R6;
(...args: infer A7): infer R7;
(...args: infer A8): infer R8;
(...args: infer A9): infer R9;
(...args: infer A10): infer R10;
} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) | ((...p: A5) => R5) | ((...p: A6) => R6) | ((...p: A7) => R7) | ((...p: A8) => R8) | ((...p: A9) => R9) | ((...p: A10) => R10) : F extends {
(...args: infer A1): infer R1;
(...args: infer A2): infer R2;
(...args: infer A3): infer R3;
(...args: infer A4): infer R4;
(...args: infer A5): infer R5;
(...args: infer A6): infer R6;
(...args: infer A7): infer R7;
(...args: infer A8): infer R8;
(...args: infer A9): infer R9;
} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) | ((...p: A5) => R5) | ((...p: A6) => R6) | ((...p: A7) => R7) | ((...p: A8) => R8) | ((...p: A9) => R9) : F extends {
(...args: infer A1): infer R1;
(...args: infer A2): infer R2;
(...args: infer A3): infer R3;
(...args: infer A4): infer R4;
(...args: infer A5): infer R5;
(...args: infer A6): infer R6;
(...args: infer A7): infer R7;
(...args: infer A8): infer R8;
} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) | ((...p: A5) => R5) | ((...p: A6) => R6) | ((...p: A7) => R7) | ((...p: A8) => R8) : F extends {
(...args: infer A1): infer R1;
(...args: infer A2): infer R2;
(...args: infer A3): infer R3;
(...args: infer A4): infer R4;
(...args: infer A5): infer R5;
(...args: infer A6): infer R6;
(...args: infer A7): infer R7;
} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) | ((...p: A5) => R5) | ((...p: A6) => R6) | ((...p: A7) => R7) : F extends {
(...args: infer A1): infer R1;
(...args: infer A2): infer R2;
(...args: infer A3): infer R3;
(...args: infer A4): infer R4;
(...args: infer A5): infer R5;
(...args: infer A6): infer R6;
} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) | ((...p: A5) => R5) | ((...p: A6) => R6) : F extends {
(...args: infer A1): infer R1;
(...args: infer A2): infer R2;
(...args: infer A3): infer R3;
(...args: infer A4): infer R4;
(...args: infer A5): infer R5;
} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) | ((...p: A5) => R5) : F extends {
(...args: infer A1): infer R1;
(...args: infer A2): infer R2;
(...args: infer A3): infer R3;
(...args: infer A4): infer R4;
} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) : F extends {
(...args: infer A1): infer R1;
(...args: infer A2): infer R2;
(...args: infer A3): infer R3;
} ? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) : F extends {
(...args: infer A1): infer R1;
(...args: infer A2): infer R2;
} ? ((...p: A1) => R1) | ((...p: A2) => R2) : F extends (...args: infer A1) => infer R1 ? ((...p: A1) => R1) : never;
/**
* Represents a deeply branded type.
*
* Recursively walk a type and replace it with a branded type related to the
* original. This is useful for equality-checking stricter than
* `A extends B ? B extends A ? true : false : false`, because it detects the
* difference between a few edge-case types that vanilla TypeScript
* doesn't by default:
* - `any` vs `unknown`
* - `{ readonly a: string }` vs `{ a: string }`
* - `{ a?: string }` vs `{ a: string | undefined }`
*
* __Note__: not very performant for complex types - this should only be used
* when you know you need it. If doing an equality check, it's almost always
* better to use {@linkcode StrictEqualUsingTSInternalIdenticalToOperator}.
*/
declare type DeepBrand<T> = IsNever<T> extends true ? {
type: 'never';
} : IsAny<T> extends true ? {
type: 'any';
} : IsUnknown<T> extends true ? {
type: 'unknown';
} : T extends string | number | boolean | symbol | bigint | null | undefined | void ? {
type: 'primitive';
value: T;
} : T extends new (...args: any[]) => any ? {
type: 'constructor';
params: ConstructorOverloadParameters<T>;
instance: DeepBrand<InstanceType<Extract<T, new (...args: any) => any>>>;
} : T extends (...args: infer P) => infer R ? NumOverloads<T> extends 1 ? {
type: 'function';
params: DeepBrand<P>;
return: DeepBrand<R>;
this: DeepBrand<ThisParameterType<T>>;
props: DeepBrand<Omit<T, keyof Function>>;
} : UnionToTuple<OverloadsInfoUnion<T>> extends infer OverloadsTuple ? {
type: 'overloads';
overloads: {
[K in keyof OverloadsTuple]: DeepBrand<OverloadsTuple[K]>;
};
} : never : T extends any[] ? {
type: 'array';
items: {
[K in keyof T]: T[K];
};
} : {
type: 'object';
properties: {
[K in keyof T]: DeepBrand<T[K]>;
};
readonly: ReadonlyKeys<T>;
required: RequiredKeys<T>;
optional: OptionalKeys<T>;
constructorParams: DeepBrand<ConstructorOverloadParameters<T>>;
};
declare const _default: Colors_2;
/**
* Creates a suite of tests, allowing for grouping and hierarchical organization of tests.
* Suites can contain both tests and other suites, enabling complex test structures.
*
* @param {string} name - The name of the suite, used for identification and reporting.
* @param {Function} fn - A function that defines the tests and suites within this suite.
* @example
* ```ts
* // Define a suite with two tests
* describe('Math operations', () => {
* test('should add two numbers', () => {
* expect(add(1, 2)).toBe(3);
* });
*
* test('should subtract two numbers', () => {
* expect(subtract(5, 2)).toBe(3);
* });
* });
* ```
* @example
* ```ts
* // Define nested suites
* describe('String operations', () => {
* describe('Trimming', () => {
* test('should trim whitespace from start and end', () => {
* expect(' hello '.trim()).toBe('hello');
* });
* });
*
* describe('Concatenation', () => {
* test('should concatenate two strings', () => {
* expect('hello' + ' ' + 'world'