UNPKG

@rstest/core

Version:
1,501 lines (1,400 loc) 92.8 kB
import type { config } from 'chai'; import type { RsbuildConfig } from '@rsbuild/core'; import type { Writable } from 'node:stream'; /** * 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; declare type AfterAllListener = (ctx: SuiteContext) => MaybePromise<void>; declare type AfterEachListener = (ctx: TestContext) => MaybePromise<void>; declare interface Assertion<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 interface Assertion_2<T = any> extends Assertion<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 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>; declare type BeforeAllListener = (ctx: SuiteContext) => MaybePromise<void | AfterAllListener>; declare type BeforeEachListener = (ctx: TestContext) => MaybePromise<void | AfterEachListener>; declare interface BranchMapping { loc: Range_2; type: string; locations: Range_2[]; line: number; } declare type BuiltInReporterNames = keyof typeof reportersMap; declare type BuiltinReporterOptions = { default: DefaultReporterOptions; }; declare type ChaiConfig = Partial<Omit<typeof config, 'useProxy' | 'proxyExcludedKeys' | 'deepEqual'>>; declare interface CloverOptions extends FileOptions, ProjectOptions {} declare interface CoberturaOptions extends FileOptions, ProjectOptions {} /** * 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; } /** * Base class for writing content */ declare class ContentWriter { /** * returns the colorized version of a string. Typically, * content writers that write to files will return the * same string and ones writing to a tty will wrap it in * appropriate escape sequences. */ colorize(str: string, clazz?: string): string; /** * writes a string appended with a newline to the destination */ println(str: string): void; /** * closes this content writer. Should be called after all writes are complete. */ close(): void; } declare interface Context { data: any; dir: string; sourceFinder(filepath: string): string; watermarks: Watermarks; writer: FileWriter; /** * returns the coverage class given a coverage * types and a percentage value. */ classForPercent(type: keyof Watermarks, value: number): string; /** * returns the source code for the specified file path or throws if * the source could not be found. */ getSource(filepath: string): string; getTree(summarizer?: Summarizers): Tree; /** * returns a full visitor given a partial one. */ getVisitor<N extends Node_2 = Node_2>(visitor: Partial<Visitor<N>>): Visitor<N>; /** * returns a FileWriter implementation for reporting use. Also available * as the `writer` property on the context. */ getWriter(): FileWriter; /** * returns an XML writer for the supplied content writer */ getXmlWriter(contentWriter: ContentWriter): XmlWriter; } 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 Coverage { covered: number; total: number; coverage: number; } declare interface CoverageMapData { [key: string]: FileCoverage | FileCoverageData; } declare type CoverageOptions = { /** * Enable coverage collection. * @default false */ enabled?: boolean; /** * A list of glob patterns that should be included for coverage collection. * Only collect coverage for tested files by default. * * @default undefined */ include?: string[]; /** * A list of glob patterns that should be excluded from coverage collection. * * This option accepts an array of wax(https://crates.io/crates/wax)-compatible glob patterns * * @default ['**\/node_modules/**', * '**\/dist/**', * '**\/test/**', * '**\/__tests__/**', * '**\/*.{test,spec}.?(c|m)[jt]s?(x)', * '**\/__mocks__/**' * ] */ exclude?: string[]; /** * The provider to use for coverage collection. * @default 'istanbul' */ provider?: 'istanbul'; /** * The reporters to use for coverage collection. * Supports built-in istanbul reporters and custom reporters (e.g., '@canyonjs/report-html'). * @default ['text', 'html', 'clover', 'json'] * @example * // Built-in reporters * reporters: ['text', 'html', ['json', { file: 'coverage.json' }]] * * // Custom reporters * reporters: ['@canyonjs/report-html', ['custom-reporter', { outputDir: './reports' }]] * * // Mixed usage * reporters: ['text', '@canyonjs/report-html', ['html', { subdir: 'html-report' }]] */ reporters?: SupportedReporter[]; /** * The directory to store coverage reports. * @default './coverage' */ reportsDirectory?: string; /** * Whether to clean the coverage directory before running tests. * @default true */ clean?: boolean; /** * Coverage thresholds * * @default undefined */ thresholds?: CoverageThresholds; /** * Whether to report coverage when tests fail. * @default false */ reportOnFailure?: boolean; }; declare class CoverageSummary { constructor(data: CoverageSummary | CoverageSummaryData); merge(obj: CoverageSummary): CoverageSummary; toJSON(): CoverageSummaryData; isEmpty(): boolean; data: CoverageSummaryData; lines: Totals; statements: Totals; branches: Totals; functions: Totals; } declare interface CoverageSummaryData { lines: Totals; statements: Totals; branches: Totals; functions: Totals; } declare type CoverageThreshold = { /** Threshold for statements */ statements?: number; /** Threshold for functions */ functions?: number; /** Threshold for branches */ branches?: number; /** Threshold for lines */ lines?: number; }; declare type CoverageThresholds = CoverageThreshold | (CoverageThreshold & ThresholdGlobRecord); 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; } /** Custom reporter configuration for non-istanbul reporters */ declare type CustomReporter = string | [string, Record<string, unknown>]; 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; private testState; constructor({ rootPath, options, config, testState, }: { rootPath: string; config: NormalizedConfig; options: DefaultReporterOptions; testState: RstestTestState; }); onTestFileStart(): void; onTestFileResult(test: TestFileResult): void; onTestCaseResult(): void; onUserConsoleLog(log: UserConsoleLog): void; onExit(): Promise<void>; onTestRunEnd({ results, testResults, duration, getSourcemap, snapshotSummary, filterRerunTestPaths, unhandledErrors, }: { results: TestFileResult[]; testResults: TestResult[]; duration: Duration; snapshotSummary: SnapshotSummary; getSourcemap: GetSourcemap; unhandledErrors?: Error[]; filterRerunTestPaths?: string[]; }): Promise<void>; } declare type DefaultReporterOptions = { /** * prints out summary of all tests * @default true */ summary?: boolean; /** * logger which write messages to * @default process.stdout/process.stderr */ logger?: Options['logger']; }; 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; <T>(cases: readonly T[]): (description: string, fn: (param: 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; /** The test file output path */ declare type DistPath = string; declare type Duration = { totalTime: number; buildTime: number; testTime: number; }; declare interface EncodedSourceMap extends SourceMapV3 { mappings: string; } declare type EncodedSourceMapXInput = EncodedSourceMap & XInput; declare type EntryInfo = { distPath: DistPath; chunks: (string | number)[]; testPath: TestPath; files?: string[]; }; declare type EnvironmentName = 'node' | 'jsdom' | 'happy-dom'; declare type EnvironmentWithOptions = { name: EnvironmentName; options?: Record<string, any>; }; 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_2<T>; unreachable: (message?: string) => never; soft: <T>(actual: T, message?: string) => Assertion_2<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<T>; extend: (expects: MatchersObject) => void; anything: () => any; any: (constructor: unknown) => any; getState: () => MatcherState; setState: (state: Partial<MatcherState>) => void; not: AsymmetricMatchersContaining; } declare type ExtendConfig = Omit<RstestConfig, 'projects'>; declare type ExtendConfigFn = (userConfig: Readonly<RstestConfig>) => MaybePromise<ExtendConfig>; declare class FileCoverage implements FileCoverageData { constructor(data: string | FileCoverage | FileCoverageData); merge(other: FileCoverageData): void; getBranchCoverageByLine(): { [line: number]: Coverage }; getLineCoverage(): { [line: number]: number }; getUncoveredLines(): number[]; resetHits(): void; computeBranchTotals(): Totals; computeSimpleTotals(): Totals; toSummary(): CoverageSummary; toJSON(): object; data: FileCoverageData; path: string; statementMap: { [key: string]: Range_2 }; fnMap: { [key: string]: FunctionMapping }; branchMap: { [key: string]: BranchMapping }; s: { [key: string]: number }; f: { [key: string]: number }; b: { [key: string]: number[] }; } declare interface FileCoverageData { path: string; statementMap: { [key: string]: Range_2 }; fnMap: { [key: string]: FunctionMapping }; branchMap: { [key: string]: BranchMapping }; s: { [key: string]: number }; f: { [key: string]: number }; b: { [key: string]: number[] }; } declare interface FileOptions { file: string; } /** * utility for writing files under a specific directory */ declare class FileWriter { constructor(baseDir: string); static startCapture(): void; static stopCapture(): void; static getOutput(): string; static resetOutput(): void; /** * returns a FileWriter that is rooted at the supplied subdirectory */ writeForDir(subdir: string): FileWriter; /** * copies a file from a source directory to a destination name */ copyFile(source: string, dest: string, header?: string): void; /** * returns a content writer for writing content to the supplied file. */ writeFile(file: string | null): ContentWriter; } 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; expected?: string; actual?: string; }; declare interface Formatter { (input?: unknown): string; open: string; close: string; } declare interface FunctionMapping { name: string; decl: Range_2; loc: Range_2; line: number; } 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) => Promise<SourceMapInput | null>; declare class GithubActionsReporter { private onWritePath; private rootPath; constructor({ options, rootPath, }: { rootPath: string; options: { onWritePath: (path: string) => string; }; }); private log; onTestRunEnd({ results, testResults, getSourcemap, }: { results: TestFileResult[]; testResults: TestResult[]; duration: Duration; snapshotSummary: SnapshotSummary; getSourcemap: GetSourcemap; filterRerunTestPaths?: string[]; }): Promise<void>; } declare interface HtmlOptions { verbose: boolean; skipEmpty: boolean; subdir: string; linkMapper: LinkMapper; } declare interface HtmlSpaOptions extends HtmlOptions { metricsToShow: Array<"lines" | "branches" | "functions" | "statements">; } declare type Indent = (arg0: string) => string; /** * A list of glob patterns or files that match your test projects. * * eg. ['packages/*', 'examples/node/rstest.config.ts'] */ /** * Inline project config must include a name. */ declare type InlineProjectConfig = ProjectConfig & { name: string; }; declare interface InlineSnapshotMatcher<T> { <U extends { [P in keyof T]: any; }>(properties: Partial<U>, snapshot?: string, message?: string): void; (message?: string): void; } 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 type JsonOptions = FileOptions; declare type JsonSummaryOptions = FileOptions; declare class JUnitReporter implements Reporter { private rootPath; private outputPath?; constructor({ rootPath, options: { outputPath }, }: { rootPath: string; options?: { outputPath?: string; }; }); private sanitizeXml; private escapeXml; private createJUnitTestCase; private createJUnitTestSuite; private generateJUnitXml; onTestRunEnd({ results, testResults, duration, getSourcemap, }: { getSourcemap: GetSourcemap; results: TestFileResult[]; testResults: TestResult[]; duration: Duration; }): Promise<void>; } declare interface LcovOnlyOptions extends FileOptions, ProjectOptions {} declare interface LcovOptions extends FileOptions, ProjectOptions {} declare interface LinkMapper { getPath(node: string | Node_2): string; relativePath(source: string | Node_2, target: string | Node_2): string; assetPath(node: Node_2, name: string): string; } declare type Location_2 = { line: number; column: number; }; declare interface Location_3 { line: number; column: number; } 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>; 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 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