UNPKG

@rstest/core

Version:
1,383 lines (1,294 loc) 81.9 kB
import type { assert as assert_2 } from 'chai'; import type { RsbuildConfig } from '@rsbuild/core'; /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ declare function addSerializer(plugin: Plugin_2): void; export declare const afterAll: Rstest['afterAll']; declare type AfterAllListener = (ctx: SuiteContext) => MaybePromise<void>; export declare const afterEach: Rstest['afterEach']; declare type AfterEachListener = () => MaybePromise<void>; export declare const assert: Rstest['assert']; export declare interface Assertion<T = any> extends Assertion_2<T> { matchSnapshot: SnapshotMatcher<T>; toMatchSnapshot: SnapshotMatcher<T>; toMatchInlineSnapshot: InlineSnapshotMatcher<T>; /** * Checks that an error thrown by a function matches a previously recorded snapshot. * * @param message - Optional custom error message. * * @example * expect(functionWithError).toThrowErrorMatchingSnapshot(); */ toThrowErrorMatchingSnapshot: (message?: string) => void; /** * Checks that an error thrown by a function matches an inline snapshot within the test file. * Useful for keeping snapshots close to the test code. * * @param snapshot - Optional inline snapshot string to match. * @param message - Optional custom error message. * * @example * const throwError = () => { throw new Error('Error occurred') }; * expect(throwError).toThrowErrorMatchingInlineSnapshot(`"Error occurred"`); */ toThrowErrorMatchingInlineSnapshot: (snapshot?: string, message?: string) => void; /** * Compares the received value to a snapshot saved in a specified file. * Useful for cases where snapshot content is large or needs to be shared across tests. * * @param filepath - Path to the snapshot file. * @param message - Optional custom error message. * * @example * await expect(largeData).toMatchFileSnapshot('path/to/snapshot.json'); */ toMatchFileSnapshot: (filepath: string, message?: string) => Promise<void>; /** * Verifies that a promise resolves. * * @example * await expect(someAsyncFunc).resolves.toBe(42); */ resolves: PromisifyAssertion_2<T>; /** * Verifies that a promise rejects. * * @example * await expect(someAsyncFunc).rejects.toThrow('error'); */ rejects: PromisifyAssertion_2<T>; } declare interface Assertion_2<T = any> extends VitestAssertion<Chai.Assertion, T>, JestAssertion<T>, Matchers<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; /** * Ensure that a mock function is called with specific arguments and called * exactly once. * * @example * expect(mockFunc).toHaveBeenCalledExactlyOnceWith('arg1', 42); */ toHaveBeenCalledExactlyOnceWith: <E extends any[]>(...args: E) => void; /** * This assertion checks if a `Mock` was called before another `Mock`. * @param mock - A mock function created by `vi.spyOn` or `vi.fn` * @param failIfNoFirstInvocation - Fail if the first mock was never called * @example * const mock1 = vi.fn() * const mock2 = vi.fn() * * mock1() * mock2() * mock1() * * expect(mock1).toHaveBeenCalledBefore(mock2) */ toHaveBeenCalledBefore: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void; /** * This assertion checks if a `Mock` was called after another `Mock`. * @param mock - A mock function created by `vi.spyOn` or `vi.fn` * @param failIfNoFirstInvocation - Fail if the first mock was never called * @example * const mock1 = vi.fn() * const mock2 = vi.fn() * * mock2() * mock1() * mock2() * * expect(mock1).toHaveBeenCalledAfter(mock2) */ toHaveBeenCalledAfter: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => 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>; } declare abstract class AsymmetricMatcher< T, State extends MatcherState = MatcherState > implements AsymmetricMatcherInterface { protected sample: T; protected inverse: boolean; // should have "jest" to be compatible with its ecosystem $$typeof: symbol; constructor(sample: T, inverse?: boolean); protected getMatcherContext(expect?: Chai.ExpectStatic): State; abstract asymmetricMatch(other: unknown): boolean; abstract toString(): string; getExpectedType?(): string; toAsymmetricMatcher?(): string; } declare interface AsymmetricMatcherInterface { asymmetricMatch: (other: unknown) => boolean; toString: () => string; getExpectedType?: () => string; toAsymmetricMatcher?: () => string; } declare interface AsymmetricMatchersContaining extends CustomMatcher { /** * 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: DeeplyAllowMatchers<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<DeeplyAllowMatchers<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>; export declare const beforeAll: Rstest['beforeAll']; declare type BeforeAllListener = (ctx: SuiteContext) => MaybePromise<void | AfterAllListener>; export declare const beforeEach: Rstest['beforeEach']; declare type BeforeEachListener = () => MaybePromise<void | AfterEachListener>; declare type BuiltInReporterNames = keyof typeof reportersMap; declare type BuiltinReporterOptions = { default: DefaultReporterOptions; }; /** * 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 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; } declare interface Constructable { new (...args: any[]): any; } declare class CounterMap<K> extends DefaultMap<K, number> { constructor(); // compat for jest-image-snapshot https://github.com/vitest-dev/vitest/issues/7322 // `valueOf` and `Snapshot.added` setter allows // snapshotState.added = snapshotState.added + 1 // to function as // snapshotState.added.total_ = snapshotState.added.total() + 1 _total: number | undefined; valueOf(): number; increment(key: K): void; total(): number; } declare interface CustomMatcher { /** * 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'); * expect(age).toEqual(expect.toSatisfy(val => val >= 18, 'Age must be at least 18')); */ toSatisfy: (matcher: (value: any) => boolean, message?: string) => any; /** * Matches if the received value is one of the values in the expected array. * * @example * expect(1).toBeOneOf([1, 2, 3]) * expect('foo').toBeOneOf([expect.any(String)]) * expect({ a: 1 }).toEqual({ a: expect.toBeOneOf(['1', '2', '3']) }) */ toBeOneOf: <T>(sample: Array<T>) => any; } declare interface DecodedSourceMap extends SourceMapV3 { mappings: SourceMapSegment[][]; } declare type DecodedSourceMapXInput = DecodedSourceMap & XInput; declare type DeeplyAllowMatchers<T> = T extends Array<infer Element> ? WithAsymmetricMatcher<T> | DeeplyAllowMatchers<Element>[] : T extends object ? WithAsymmetricMatcher<T> | { [K in keyof T] : DeeplyAllowMatchers<T[K]> } : WithAsymmetricMatcher<T>; /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ declare class DefaultMap< K, V > extends Map<K, V> { private defaultFn; constructor(defaultFn: (key: K) => V, entries?: Iterable<readonly [K, V]>); get(key: K): V; } declare class DefaultReporter implements Reporter { protected rootPath: string; protected config: NormalizedConfig; private options; protected statusRenderer: StatusRenderer | undefined; constructor({ rootPath, options, config, }: { rootPath: string; config: NormalizedConfig; options: DefaultReporterOptions; }); onTestFileStart(test: TestFileInfo): void; onTestFileResult(test: TestFileResult): void; onTestCaseResult(_result: TestResult): void; onUserConsoleLog(log: UserConsoleLog): void; onExit(): Promise<void>; onTestRunEnd({ results, testResults, duration, getSourcemap, snapshotSummary, }: { results: TestFileResult[]; testResults: TestResult[]; duration: Duration; snapshotSummary: SnapshotSummary; getSourcemap: GetSourcemap; }): Promise<void>; } declare type DefaultReporterOptions = { /** * prints out summary of all tests * @default true */ summary?: boolean; }; /** * This function helps you to autocomplete configuration types. * It accepts a Rsbuild config object, or a function that returns a config. */ export declare function defineConfig(config: RstestConfig): RstestConfig; export declare function defineConfig(config: RstestConfigSyncFn): RstestConfigSyncFn; export declare function defineConfig(config: RstestConfigAsyncFn): RstestConfigAsyncFn; export declare function defineConfig(config: RstestConfigExport): RstestConfigExport; export declare const describe: Rstest['describe']; declare type DescribeAPI = DescribeFn & { each: DescribeEachFn; for: DescribeForFn; only: DescribeAPI; skip: DescribeAPI; runIf: (condition: boolean) => DescribeAPI; skipIf: (condition: boolean) => DescribeAPI; todo: DescribeAPI; concurrent: DescribeAPI; sequential: DescribeAPI; }; declare interface DescribeEachFn { <T extends Record<string, unknown>>(cases: readonly T[]): (description: string, fn?: (param: T) => MaybePromise<void>) => void; <T extends readonly [unknown, ...unknown[]]>(cases: readonly T[]): (description: string, fn: (...args: [...T]) => MaybePromise<void>) => void; } declare type DescribeFn = (description: string, fn?: () => void) => void; declare type DescribeForFn = <T>(cases: readonly T[]) => (description: string, fn?: (param: T) => MaybePromise<void>) => void; /** * @param a Expected value * @param b Received value * @param options Diff options * @returns {string | null} a string diff */ declare function diff(a: any, b: any, options?: DiffOptions): string | undefined; declare interface DiffOptions { aAnnotation?: string; aColor?: DiffOptionsColor; aIndicator?: string; bAnnotation?: string; bColor?: DiffOptionsColor; bIndicator?: string; changeColor?: DiffOptionsColor; changeLineTrailingSpaceColor?: DiffOptionsColor; commonColor?: DiffOptionsColor; commonIndicator?: string; commonLineTrailingSpaceColor?: DiffOptionsColor; contextLines?: number; emptyFirstOrLastLinePlaceholder?: string; expand?: boolean; includeChangeCounts?: boolean; omitAnnotationLines?: boolean; patchColor?: DiffOptionsColor; printBasicPrototype?: boolean; maxDepth?: number; compareKeys?: CompareKeys; truncateThreshold?: number; truncateAnnotation?: string; truncateAnnotationColor?: DiffOptionsColor; } /** * 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 type DiffOptionsColor = (arg: string) => string; declare type Duration = { totalTime: number; buildTime: number; testTime: number; }; declare interface EncodedSourceMap extends SourceMapV3 { mappings: string; } declare type EncodedSourceMapXInput = EncodedSourceMap & XInput; export declare const expect: Rstest['expect']; declare type ExpectationResult = SyncExpectationResult | AsyncExpectationResult; declare interface ExpectPollOptions { /** * @default 50 */ interval?: number; /** * @default 1000 */ timeout?: number; message?: string; } declare interface ExpectStatic extends ExpectStatic_2 { <T>(actual: T, message?: string): Assertion<T>; unreachable: (message?: string) => never; soft: <T>(actual: T, message?: string) => Assertion<T>; poll: <T>(actual: () => T, options?: ExpectPollOptions) => Omit<PromisifyAssertion_2<Awaited<T>>, 'rejects' | 'resolves' | 'toThrow' | 'toThrowError' | 'throw' | 'throws' | 'matchSnapshot' | 'toMatchSnapshot' | 'toMatchInlineSnapshot' | 'toThrowErrorMatchingSnapshot' | 'toThrowErrorMatchingInlineSnapshot'>; addEqualityTesters: (testers: Tester[]) => void; assertions: (expected: number) => void; hasAssertions: () => void; addSnapshotSerializer: typeof addSerializer; getState: () => MatcherState_2; setState: (state: Partial<MatcherState_2>) => void; } declare interface ExpectStatic_2 extends Chai.ExpectStatic, Matchers, AsymmetricMatchersContaining { <T>(actual: T, message?: string): Assertion_2<T>; extend: (expects: MatchersObject) => void; anything: () => any; any: (constructor: unknown) => any; getState: () => MatcherState; setState: (state: Partial<MatcherState>) => void; not: AsymmetricMatchersContaining; } /** * Names of clock methods that may be faked by install. */ declare type FakeMethod = | "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date" | "nextTick" | "hrtime" | "requestAnimationFrame" | "cancelAnimationFrame" | "requestIdleCallback" | "cancelIdleCallback" | "performance" | "queueMicrotask"; declare interface FakeTimerInstallOpts { /** * Installs fake timers with the specified unix epoch (default: 0) */ now?: number | Date | undefined; /** * An array with names of global methods and APIs to fake. By default, `@sinonjs/fake-timers` does not replace `nextTick()` and `queueMicrotask()`. * For instance, `FakeTimers.install({ toFake: ['setTimeout', 'nextTick'] })` will fake only `setTimeout()` and `nextTick()` */ toFake?: FakeMethod[] | undefined; /** * The maximum number of timers that will be run when calling runAll() (default: 1000) */ loopLimit?: number | undefined; /** * Tells @sinonjs/fake-timers to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by * 20ms for every 20ms change in the real system time) (default: false) */ shouldAdvanceTime?: boolean | undefined; /** * Relevant only when using with shouldAdvanceTime: true. increment mocked time by advanceTimeDelta ms every advanceTimeDelta ms change * in the real system time (default: 20) */ advanceTimeDelta?: number | undefined; /** * Tells FakeTimers to clear 'native' (i.e. not fake) timers by delegating to their respective handlers. These are not cleared by * default, leading to potentially unexpected behavior if timers existed prior to installing FakeTimers. (default: false) */ shouldClearNativeTimers?: boolean | undefined; } declare type Fixture<T, K extends keyof T, ExtraContext = object> = ((...args: any) => any) extends T[K] ? T[K] extends any ? FixtureFn<T, K, Omit<ExtraContext, Exclude<keyof T, K>>> : never : T[K] | (T[K] extends any ? FixtureFn<T, K, Omit<ExtraContext, Exclude<keyof T, K>>> : never); declare type FixtureFn<T, K extends keyof T, ExtraContext> = (context: Omit<T, K> & ExtraContext, use: Use<T[K]>) => Promise<void>; declare interface FixtureOptions { /** * Whether to automatically set up current fixture, even though it's not being used in tests. */ auto?: boolean; } declare type Fixtures<T extends Record<string, any> = object, ExtraContext = object> = { [K in keyof T]: Fixture<T, K, ExtraContext & TestContext> | [Fixture<T, K, ExtraContext & TestContext>, FixtureOptions?]; }; declare type FormattedError = { fullStack?: boolean; message: string; name?: string; stack?: string; diff?: string; }; declare interface Formatter { (input?: unknown): string; open: string; close: string; } declare type FunctionLike = (...args: any) => any; declare type GeneratedColumn = number; declare function getMatcherUtils(): { EXPECTED_COLOR: Formatter RECEIVED_COLOR: Formatter INVERTED_COLOR: Formatter BOLD_WEIGHT: Formatter DIM_COLOR: Formatter diff: typeof diff matcherHint: typeof matcherHint printReceived: typeof printReceived printExpected: typeof printExpected printDiffOrStringify: typeof printDiffOrStringify printWithType: typeof printWithType }; declare type GetSourcemap = (sourcePath: string) => SourceMapInput | null; declare class GithubActionsReporter { private onWritePath; private rootPath; constructor({ options, rootPath, }: { rootPath: string; options: { onWritePath: (path: string) => string; }; }); onTestRunEnd({ results, testResults, getSourcemap, }: { results: TestFileResult[]; testResults: TestResult[]; duration: Duration; snapshotSummary: SnapshotSummary; getSourcemap: GetSourcemap; }): Promise<void>; } declare type Indent = (arg0: string) => string; declare interface InlineSnapshotMatcher<T> { <U extends { [P in keyof T]: any; }>(properties: Partial<U>, snapshot?: string, message?: string): void; (message?: string): void; } export declare const it: Rstest['it']; declare interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher { /** * Used when you want to check that two objects have the same value. * This matcher recursively checks the equality of all fields, rather than checking for object identity. * * @example * expect(user).toEqual({ name: 'Alice', age: 30 }); */ toEqual: <E>(expected: E) => void; /** * Use to test that objects have the same types as well as structure. * * @example * expect(user).toStrictEqual({ name: 'Alice', age: 30 }); */ toStrictEqual: <E>(expected: E) => void; /** * Checks that a value is what you expect. It calls `Object.is` to compare values. * Don't use `toBe` with floating-point numbers. * * @example * expect(result).toBe(42); * expect(status).toBe(true); */ toBe: <E>(expected: E) => void; /** * Check that a string matches a regular expression. * * @example * expect(message).toMatch(/hello/); * expect(greeting).toMatch('world'); */ toMatch: (expected: string | RegExp) => void; /** * Used to check that a JavaScript object matches a subset of the properties of an object * * @example * expect(user).toMatchObject({ * name: 'Alice', * address: { city: 'Wonderland' } * }); */ toMatchObject: <E extends object | any[]>(expected: E) => void; /** * Used when you want to check that an item is in a list. * For testing the items in the list, this uses `===`, a strict equality check. * * @example * expect(items).toContain('apple'); * expect(numbers).toContain(5); */ toContain: <E>(item: E) => void; /** * Used when you want to check that an item is in a list. * For testing the items in the list, this matcher recursively checks the * equality of all fields, rather than checking for object identity. * * @example * expect(items).toContainEqual({ name: 'apple', quantity: 1 }); */ toContainEqual: <E>(item: E) => void; /** * Use when you don't care what a value is, you just want to ensure a value * is true in a boolean context. In JavaScript, there are six falsy values: * `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy. * * @example * expect(user.isActive).toBeTruthy(); */ toBeTruthy: () => void; /** * When you don't care what a value is, you just want to * ensure a value is false in a boolean context. * * @example * expect(user.isActive).toBeFalsy(); */ toBeFalsy: () => void; /** * For comparing floating point numbers. * * @example * expect(score).toBeGreaterThan(10); */ toBeGreaterThan: (num: number | bigint) => void; /** * For comparing floating point numbers. * * @example * expect(score).toBeGreaterThanOrEqual(10); */ toBeGreaterThanOrEqual: (num: number | bigint) => void; /** * For comparing floating point numbers. * * @example * expect(score).toBeLessThan(10); */ toBeLessThan: (num: number | bigint) => void; /** * For comparing floating point numbers. * * @example * expect(score).toBeLessThanOrEqual(10); */ toBeLessThanOrEqual: (num: number | bigint) => void; /** * Used to check that a variable is NaN. * * @example * expect(value).toBeNaN(); */ toBeNaN: () => void; /** * Used to check that a variable is undefined. * * @example * expect(value).toBeUndefined(); */ toBeUndefined: () => void; /** * This is the same as `.toBe(null)` but the error messages are a bit nicer. * So use `.toBeNull()` when you want to check that something is null. * * @example * expect(value).toBeNull(); */ toBeNull: () => void; /** * Ensure that a variable is not undefined. * * @example * expect(value).toBeDefined(); */ toBeDefined: () => void; /** * Ensure that an object is an instance of a class. * This matcher uses `instanceof` underneath. * * @example * expect(new Date()).toBeInstanceOf(Date); */ toBeInstanceOf: <E>(expected: E) => void; /** * Used to check that an object has a `.length` property * and it is set to a certain numeric value. * * @example * expect([1, 2, 3]).toHaveLength(3); * expect('hello').toHaveLength(5); */ toHaveLength: (length: number) => void; /** * Use to check if a property at the specified path exists on an object. * For checking deeply nested properties, you may use dot notation or an array containing * the path segments for deep references. * * Optionally, you can provide a value to check if it matches the value present at the path * on the target object. This matcher uses 'deep equality' (like `toEqual()`) and recursively checks * the equality of all fields. * * @example * expect(user).toHaveProperty('address.city', 'New York'); * expect(config).toHaveProperty(['settings', 'theme'], 'dark'); */ toHaveProperty: <E>(property: string | (string | number)[], value?: E) => void; /** * Using exact equality with floating point numbers is a bad idea. * Rounding means that intuitive things fail. * The default for `precision` is 2. * * @example * expect(price).toBeCloseTo(9.99, 2); */ toBeCloseTo: (number: number, numDigits?: number) => void; /** * Ensures that a mock function is called an exact number of times. * * Also under the alias `expect.toBeCalledTimes`. * * @example * expect(mockFunc).toHaveBeenCalledTimes(2); */ toHaveBeenCalledTimes: (times: number) => void; /** * Ensures that a mock function is called an exact number of times. * * Alias for `expect.toHaveBeenCalledTimes`. * * @example * expect(mockFunc).toBeCalledTimes(2); */ toBeCalledTimes: (times: number) => void; /** * Ensures that a mock function is called. * * Also under the alias `expect.toBeCalled`. * * @example * expect(mockFunc).toHaveBeenCalled(); */ toHaveBeenCalled: () => void; /** * Ensures that a mock function is called. * * Alias for `expect.toHaveBeenCalled`. * * @example * expect(mockFunc).toBeCalled(); */ toBeCalled: () => void; /** * Ensure that a mock function is called with specific arguments. * * Also under the alias `expect.toBeCalledWith`. * * @example * expect(mockFunc).toHaveBeenCalledWith('arg1', 42); */ toHaveBeenCalledWith: <E extends any[]>(...args: E) => void; /** * Ensure that a mock function is called with specific arguments. * * Alias for `expect.toHaveBeenCalledWith`. * * @example * expect(mockFunc).toBeCalledWith('arg1', 42); */ toBeCalledWith: <E extends any[]>(...args: E) => void; /** * Ensure that a mock function is called with specific arguments on an Nth call. * * Also under the alias `expect.nthCalledWith`. * * @example * expect(mockFunc).toHaveBeenNthCalledWith(2, 'secondArg'); */ toHaveBeenNthCalledWith: <E extends any[]>(n: number, ...args: E) => void; /** * Ensure that a mock function is called with specific arguments on an Nth call. * * Alias for `expect.toHaveBeenNthCalledWith`. * * @example * expect(mockFunc).nthCalledWith(2, 'secondArg'); */ nthCalledWith: <E extends any[]>(nthCall: number, ...args: E) => void; /** * If you have a mock function, you can use `.toHaveBeenLastCalledWith` * to test what arguments it was last called with. * * Also under the alias `expect.lastCalledWith`. * * @example * expect(mockFunc).toHaveBeenLastCalledWith('lastArg'); */ toHaveBeenLastCalledWith: <E extends any[]>(...args: E) => void; /** * If you have a mock function, you can use `.lastCalledWith` * to test what arguments it was last called with. * * Alias for `expect.toHaveBeenLastCalledWith`. * * @example * expect(mockFunc).lastCalledWith('lastArg'); */ lastCalledWith: <E extends any[]>(...args: E) => void; /** * Used to test that a function throws when it is called. * * Also under the alias `expect.toThrowError`. * * @example * expect(() => functionWithError()).toThrow('Error message'); * expect(() => parseJSON('invalid')).toThrow(SyntaxError); */ toThrow: (expected?: string | Constructable | RegExp | Error) => void; /** * Used to test that a function throws when it is called. * * Alias for `expect.toThrow`. * * @example * expect(() => functionWithError()).toThrowError('Error message'); * expect(() => parseJSON('invalid')).toThrowError(SyntaxError); */ toThrowError: (expected?: string | Constructable | RegExp | Error) => void; /** * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time * * Alias for `expect.toHaveReturned`. * * @example * expect(mockFunc).toReturn(); */ toReturn: () => void; /** * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time * * Also under the alias `expect.toReturn`. * * @example * expect(mockFunc).toHaveReturned(); */ toHaveReturned: () => void; /** * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. * Any calls to the mock function that throw an error are not counted toward the number of times the function returned. * * Alias for `expect.toHaveReturnedTimes`. * * @example * expect(mockFunc).toReturnTimes(3); */ toReturnTimes: (times: number) => void; /** * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. * Any calls to the mock function that throw an error are not counted toward the number of times the function returned. * * Also under the alias `expect.toReturnTimes`. * * @example * expect(mockFunc).toHaveReturnedTimes(3); */ toHaveReturnedTimes: (times: number) => void; /** * Use to ensure that a mock function returned a specific value. * * Alias for `expect.toHaveReturnedWith`. * * @example * expect(mockFunc).toReturnWith('returnValue'); */ toReturnWith: <E>(value: E) => void; /** * Use to ensure that a mock function returned a specific value. * * Also under the alias `expect.toReturnWith`. * * @example * expect(mockFunc).toHaveReturnedWith('returnValue'); */ toHaveReturnedWith: <E>(value: E) => void; /** * Use to test the specific value that a mock function last returned. * If the last call to the mock function threw an error, then this matcher will fail * no matter what value you provided as the expected return value. * * Also under the alias `expect.lastReturnedWith`. * * @example * expect(mockFunc).toHaveLastReturnedWith('lastValue'); */ toHaveLastReturnedWith: <E>(value: E) => void; /** * Use to test the specific value that a mock function last returned. * If the last call to the mock function threw an error, then this matcher will fail * no matter what value you provided as the expected return value. * * Alias for `expect.toHaveLastReturnedWith`. * * @example * expect(mockFunc).lastReturnedWith('lastValue'); */ lastReturnedWith: <E>(value: E) => void; /** * Use to test the specific value that a mock function returned for the nth call. * If the nth call to the mock function threw an error, then this matcher will fail * no matter what value you provided as the expected return value. * * Also under the alias `expect.nthReturnedWith`. * * @example * expect(mockFunc).toHaveNthReturnedWith(2, 'nthValue'); */ toHaveNthReturnedWith: <E>(nthCall: number, value: E) => void; /** * Use to test the specific value that a mock function returned for the nth call. * If the nth call to the mock function threw an error, then this matcher will fail * no matter what value you provided as the expected return value. * * Alias for `expect.toHaveNthReturnedWith`. * * @example * expect(mockFunc).nthReturnedWith(2, 'nthValue'); */ nthReturnedWith: <E>(nthCall: number, value: E) => void; } declare function matcherHint(matcherName: string, received?: string, expected?: string, options?: MatcherHintOptions): string; declare interface MatcherHintOptions { comment?: string; expectedColor?: Formatter; isDirectExpectCall?: boolean; isNot?: boolean; promise?: string; receivedColor?: Formatter; secondArgument?: string; secondArgumentColor?: Formatter; } declare interface Matchers<T = any> {} declare type MatchersObject<T extends MatcherState = MatcherState> = Record<string, RawMatcherFn<T>> & ThisType<T> & { [K in keyof Matchers<T>]? : RawMatcherFn<T, Parameters<Matchers<T>[K]>> }; declare interface MatcherState { customTesters: Array<Tester>; assertionCalls: number; currentTestName?: string; dontThrow?: () => void; error?: Error; equals: (a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean) => boolean; expand?: boolean; expectedAssertionsNumber?: number | null; expectedAssertionsNumberErrorGen?: (() => Error) | null; isExpectingAssertions?: boolean; isExpectingAssertionsError?: Error | null; isNot: boolean; // environment: VitestEnvironment promise: string; // snapshotState: SnapshotState suppressedErrors: Array<Error>; testPath?: string; utils: ReturnType<typeof getMatcherUtils> & { diff: typeof diff stringify: typeof stringify iterableEquality: Tester subsetEquality: Tester }; soft?: boolean; poll?: boolean; } declare interface MatcherState_2 extends MatcherState { environment: string; snapshotState: SnapshotState; } declare type MaybePromise<T> = T | Promise<T>; export declare interface Mock<T extends FunctionLike = FunctionLike> extends MockInstance_2<T> { new (...args: Parameters<T>): ReturnType<T>; (...args: Parameters<T>): ReturnType<T>; } declare interface MockContext<T extends Procedure> { /** * This is an array containing all arguments for each call. One item of the array is the arguments of that call. * * @see https://vitest.dev/api/mock#mock-calls * @example * const fn = vi.fn() * * fn('arg1', 'arg2') * fn('arg3') * * fn.mock.calls === [ * ['arg1', 'arg2'], // first call * ['arg3'], // second call * ] */ calls: Parameters<T>[]; /** * This is an array containing all instances that were instantiated when mock was called with a `new` keyword. Note that this is an actual context (`this`) of the function, not a return value. * @see https://vitest.dev/api/mock#mock-instances */ instances: ReturnType<T>[]; /** * An array of `this` values that were used during each call to the mock function. * @see https://vitest.dev/api/mock#mock-contexts */ contexts: ThisParameterType<T>[]; /** * The order of mock's execution. This returns an array of numbers which are shared between all defined mocks. * * @see https://vitest.dev/api/mock#mock-invocationcallorder * @example * const fn1 = vi.fn() * const fn2 = vi.fn() * * fn1() * fn2() * fn1() * * fn1.mock.invocationCallOrder === [1, 3] * fn2.mock.invocationCallOrder === [2] */ invocationCallOrder: number[]; /** * This is an array containing all values that were `returned` from the function. * * The `value` property contains the returned value or thrown error. If the function returned a `Promise`, then `result` will always be `'return'` even if the promise was rejected. * * @see https://vitest.dev/api/mock#mock-results * @example * const fn = vi.fn() * .mockReturnValueOnce('result') * .mockImplementationOnce(() => { throw new Error('thrown error') }) * * const result = fn() * * try { * fn() * } * catch {} * * fn.mock.results === [ * { * type: 'return', * value: 'result', * }, * { * type: 'throw', * value: Error, * }, * ] */ results: MockResult<ReturnType<T>>[]; /** * An array containing all values that were `resolved` or `rejected` from the function. * * This array will be empty if the function was never resolved or rejected. * * @see https://vitest.dev/api/mock#mock-settledresults * @example * const fn = vi.fn().mockResolvedValueOnce('result') * * const result = fn() * * fn.mock.settledResults === [] * fn.mock.results === [ * { * type: 'return', * value: Promise<'result'>, * }, * ] * * await result * * fn.mock.settledResults === [ * { * type: 'fulfilled', * value: 'result', * }, * ] */ settledResults: MockSettledResult<Awaited<ReturnType<T>>>[]; /** * This contains the arguments of the last call. If spy wasn't called, will return `undefined`. * @see https://vitest.dev/api/mock#mock-lastcall */ lastCall: Parameters<T> | undefined; } declare type MockContext_2<T extends FunctionLike = FunctionLike> = { /** * List of the call arguments of all calls that have been made to the mock. */ calls: Parameters<T>[]; /** * List of all the object instances that have been instantiated from the mock. */ instances: ReturnType<T>[]; /** * List of all the function contexts that have been applied to calls to the mock. */ contexts: ThisParameterType<T>[]; /** * The order of mock's execution. * This returns an array of numbers which are shared between all defined mocks. * The index is starting with `1`. */ invocationCallOrder: number[]; /** * List of the call arguments of the last call that was made to the mock. * If the function was not called, it will return `undefined`. */ lastCall: Parameters<T> | undefined; /** * List of the results of all calls that have been made to the mock. */ results: MockResult_2<ReturnType<T>>[]; /** * List of the results of all values that were `resolved` or `rejected` from the function. */ settledResults: MockSettledResult_2<Awaited<ReturnType<T>>>[]; }; declare type MockFactory<T = unknown> = () => MaybePromise<Partial<T>>; declare type MockFn = <T extends FunctionLike = FunctionLike>(fn?: T) => Mock<T>; declare interface MockInstance<T extends Procedure = Procedure> extends Disposable { /** * Use it to return the name assigned to the mock with the `.mockName(name)` method. By default, it will return `vi.fn()`. * @see https://vitest.dev/api/mock#getmockname */ getMockName(): string; /** * Sets the internal mock name. This is useful for identifying the mock when an assertion fails. * @see https://vitest.dev/api/mock#mockname */ mockName(name: string): this; /** * Current context of the mock. It stores information about all invocation calls, instances, and results. */ mock: MockContext<T>; /** * Clears all information about every call. After calling it, all properties on `.mock` will return to their initial state. This method does not reset implementations. It is useful for cleaning up mocks between different assertions. * * To automatically call this method before each test, enable the [`clearMocks`](https://vitest.dev/config/#clearmocks) setting in the configuration. * @see https://vitest.dev/api/mock#mockclear */ mockClear(): this; /** * Does what `mockClear` does and resets inner implementation to the original function. This also resets all "once" implementations. * * Note that resetting a mock from `vi.fn()` will set implementation to an empty function that returns `undefined`. * Resetting a mock from `vi.fn(impl)` will set implementation to `impl`. It is useful for completely resetting a mock to its default state. * * To automatically call this method before each test, enable the [`mockReset`](https://vitest.dev/config/#mockreset) setting in the configuration. * @see https://vitest.dev/api/mock#mockreset */ mockReset(): this; /** * Does what `mockReset` does and restores original descriptors of spied-on objects. * * Note that restoring mock from `vi.fn()` will set implementation to an empty function that returns `undefined`. Restoring a `vi.fn(impl)` will restore implementation to `impl`. * @see https://vitest.dev/api/mock#mockrestore */ mockRestore(): void; /** * Returns current permanent mock implementation if there is one. * * If mock was created with `vi.fn`, it will consider passed down method as a mock implementation. * * If mock was created with `vi.spyOn`, it will return `undefined` unless a custom implementation was provided. */ getMockImplementation(): NormalizedProcedure<T> | undefined; /** * Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function. * @see https://vitest.dev/api/mock#mockimplementation * @example * const increment = vi.fn().mockImplementation(count => count + 1); * expect(increment(3)).toBe(4); */ mockImplementation(fn: NormalizedProcedure<T>): this; /** * Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function. This method can be chained to produce different results for multiple function calls. * * When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called. * @see https://vitest.dev/api/mock#mockimplementationonce * @example * const fn = vi.fn(count => count).mockImplementationOnce(count => count + 1); * expect(fn(3)).toBe(4); * expect(fn(3)).toBe(3); */ mockImplementationOnce(fn: NormalizedProcedure<T>): this; /** * Overrides the original mock implementation temporarily while the callback is being executed. * * Note that this method takes precedence over the [`mockImplementationOnce`](https://vitest.dev/api/mock#mockimplementationonce). * @see https://vitest.dev/api/mock#withimplementation * @example * const myMockFn = vi.fn(() => 'original') * * myMockFn.withImplementation(() => 'temp', () => { * myMockFn() // 'temp' * }) * * myMockFn() // 'original' */ withImplementation<T2>(fn: NormalizedProcedure<T>, cb: () => T2): T2 extends Promise<unknown> ? Promise<this> : this; /** * Use this if you need to return the `this` context from the method without invoking the actual implementation. * @see https://vitest.dev/api/mock#mockreturnthis */ mockReturnThis(): this; /** * Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function. * @see https://vitest.dev/api/mock#mockreturnvalue * @example * const mock = vi.fn() * mock.mockReturnValue(42) * mock() // 42 * mock.mockReturnValue(43) * mock() // 43 */ mockReturnValue(value: ReturnType<T>): this; /** * Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function. * * When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called. * @example * const myMockFn = vi * .fn() * .mockReturnValue('default') * .mockReturnValueOnce('first call') * .mockReturnValueOnce('second call') * * // 'first call', 'second call', 'default' * console.log(myMockFn(), myMockFn(), myMockFn()) */ mockReturnValueOnce(value: ReturnType<T>): this; /** * Accepts a value that will be resolved when the async function is called. TypeScript will only accept values that match the return type of the original function. * @example * const asyncMock = vi.fn().mockResolvedValue(42) * asyncMock() // Promise<42> */ mockResolvedValue(value: Awaited<ReturnType<T>>): this; /** * Accepts a value that will be resolved during the next function call. TypeScript will only accept values that match the return type of the original function. If chained, each consecutive call will resolve the specified value.