global-e98f203b.d.ts 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245
  1. import { ViteDevServer, TransformResult as TransformResult$1, UserConfig as UserConfig$1, CommonServerOptions, AliasOptions } from 'vite';
  2. import { Task as Task$1, Options, TaskResult as TaskResult$1, Bench } from 'tinybench';
  3. import { Stats } from 'fs';
  4. import { MessagePort } from 'worker_threads';
  5. /**
  6. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  7. *
  8. * This source code is licensed under the MIT license found in the
  9. * LICENSE file in the root directory of this source tree.
  10. */
  11. declare type Colors = {
  12. comment: {
  13. close: string;
  14. open: string;
  15. };
  16. content: {
  17. close: string;
  18. open: string;
  19. };
  20. prop: {
  21. close: string;
  22. open: string;
  23. };
  24. tag: {
  25. close: string;
  26. open: string;
  27. };
  28. value: {
  29. close: string;
  30. open: string;
  31. };
  32. };
  33. declare type Indent = (arg0: string) => string;
  34. declare type Refs = Array<unknown>;
  35. declare type Print = (arg0: unknown) => string;
  36. declare type ThemeReceived = {
  37. comment?: string;
  38. content?: string;
  39. prop?: string;
  40. tag?: string;
  41. value?: string;
  42. };
  43. declare type CompareKeys = ((a: string, b: string) => number) | undefined;
  44. interface PrettyFormatOptions {
  45. callToJSON?: boolean;
  46. compareKeys?: CompareKeys;
  47. escapeRegex?: boolean;
  48. escapeString?: boolean;
  49. highlight?: boolean;
  50. indent?: number;
  51. maxDepth?: number;
  52. min?: boolean;
  53. plugins?: Plugins;
  54. printBasicPrototype?: boolean;
  55. printFunctionName?: boolean;
  56. theme?: ThemeReceived;
  57. }
  58. declare type OptionsReceived = PrettyFormatOptions;
  59. declare type Config = {
  60. callToJSON: boolean;
  61. compareKeys: CompareKeys;
  62. colors: Colors;
  63. escapeRegex: boolean;
  64. escapeString: boolean;
  65. indent: string;
  66. maxDepth: number;
  67. min: boolean;
  68. plugins: Plugins;
  69. printBasicPrototype: boolean;
  70. printFunctionName: boolean;
  71. spacingInner: string;
  72. spacingOuter: string;
  73. };
  74. declare type Printer = (val: unknown, config: Config, indentation: string, depth: number, refs: Refs, hasCalledToJSON?: boolean) => string;
  75. declare type Test$1 = (arg0: any) => boolean;
  76. declare type NewPlugin = {
  77. serialize: (val: any, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer) => string;
  78. test: Test$1;
  79. };
  80. declare type PluginOptions = {
  81. edgeSpacing: string;
  82. min: boolean;
  83. spacing: string;
  84. };
  85. declare type OldPlugin = {
  86. print: (val: unknown, print: Print, indent: Indent, options: PluginOptions, colors: Colors) => string;
  87. test: Test$1;
  88. };
  89. declare type Plugin = NewPlugin | OldPlugin;
  90. declare type Plugins = Array<Plugin>;
  91. // Type definitions for @sinonjs/fake-timers 8.1
  92. // Project: https://github.com/sinonjs/fake-timers
  93. // Definitions by: Wim Looman <https://github.com/Nemo157>
  94. // Rogier Schouten <https://github.com/rogierschouten>
  95. // Yishai Zehavi <https://github.com/zyishai>
  96. // Remco Haszing <https://github.com/remcohaszing>
  97. // Jaden Simon <https://github.com/JadenSimon>
  98. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  99. // TypeScript Version: 2.3
  100. /**
  101. * Names of clock methods that may be faked by install.
  102. */
  103. type FakeMethod =
  104. | 'setTimeout'
  105. | 'clearTimeout'
  106. | 'setImmediate'
  107. | 'clearImmediate'
  108. | 'setInterval'
  109. | 'clearInterval'
  110. | 'Date'
  111. | 'nextTick'
  112. | 'hrtime'
  113. | 'requestAnimationFrame'
  114. | 'cancelAnimationFrame'
  115. | 'requestIdleCallback'
  116. | 'cancelIdleCallback'
  117. | 'performance'
  118. | 'queueMicrotask';
  119. interface FakeTimerInstallOpts {
  120. /**
  121. * Installs fake timers with the specified unix epoch (default: 0)
  122. */
  123. now?: number | Date | undefined;
  124. /**
  125. * An array with names of global methods and APIs to fake. By default, `@sinonjs/fake-timers` does not replace `nextTick()` and `queueMicrotask()`.
  126. * For instance, `FakeTimers.install({ toFake: ['setTimeout', 'nextTick'] })` will fake only `setTimeout()` and `nextTick()`
  127. */
  128. toFake?: FakeMethod[] | undefined;
  129. /**
  130. * The maximum number of timers that will be run when calling runAll() (default: 1000)
  131. */
  132. loopLimit?: number | undefined;
  133. /**
  134. * 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
  135. * 20ms for every 20ms change in the real system time) (default: false)
  136. */
  137. shouldAdvanceTime?: boolean | undefined;
  138. /**
  139. * Relevant only when using with shouldAdvanceTime: true. increment mocked time by advanceTimeDelta ms every advanceTimeDelta ms change
  140. * in the real system time (default: 20)
  141. */
  142. advanceTimeDelta?: number | undefined;
  143. /**
  144. * Tells FakeTimers to clear 'native' (i.e. not fake) timers by delegating to their respective handlers. These are not cleared by
  145. * default, leading to potentially unexpected behavior if timers existed prior to installing FakeTimers. (default: false)
  146. */
  147. shouldClearNativeTimers?: boolean | undefined;
  148. }
  149. interface UpdatePayload {
  150. type: 'update'
  151. updates: Update[]
  152. }
  153. interface Update {
  154. type: 'js-update' | 'css-update'
  155. path: string
  156. acceptedPath: string
  157. timestamp: number
  158. /**
  159. * @experimental internal
  160. */
  161. explicitImportRequired?: boolean | undefined
  162. }
  163. interface PrunePayload {
  164. type: 'prune'
  165. paths: string[]
  166. }
  167. interface FullReloadPayload {
  168. type: 'full-reload'
  169. path?: string
  170. }
  171. interface ErrorPayload {
  172. type: 'error'
  173. err: {
  174. [name: string]: any
  175. message: string
  176. stack: string
  177. id?: string
  178. frame?: string
  179. plugin?: string
  180. pluginCode?: string
  181. loc?: {
  182. file?: string
  183. line: number
  184. column: number
  185. }
  186. }
  187. }
  188. interface CustomEventMap {
  189. 'vite:beforeUpdate': UpdatePayload
  190. 'vite:beforePrune': PrunePayload
  191. 'vite:beforeFullReload': FullReloadPayload
  192. 'vite:error': ErrorPayload
  193. }
  194. type InferCustomEventPayload<T extends string> =
  195. T extends keyof CustomEventMap ? CustomEventMap[T] : any
  196. type ModuleNamespace = Record<string, any> & {
  197. [Symbol.toStringTag]: 'Module'
  198. }
  199. interface ViteHotContext {
  200. readonly data: any
  201. accept(): void
  202. accept(cb: (mod: ModuleNamespace | undefined) => void): void
  203. accept(dep: string, cb: (mod: ModuleNamespace | undefined) => void): void
  204. accept(
  205. deps: readonly string[],
  206. cb: (mods: Array<ModuleNamespace | undefined>) => void
  207. ): void
  208. acceptExports(exportNames: string | readonly string[]): void
  209. acceptExports(
  210. exportNames: string | readonly string[],
  211. cb: (mod: ModuleNamespace | undefined) => void
  212. ): void
  213. dispose(cb: (data: any) => void): void
  214. decline(): void
  215. invalidate(): void
  216. on<T extends string>(
  217. event: T,
  218. cb: (payload: InferCustomEventPayload<T>) => void
  219. ): void
  220. send<T extends string>(event: T, data?: InferCustomEventPayload<T>): void
  221. }
  222. declare class ModuleCacheMap extends Map<string, ModuleCache$1> {
  223. normalizePath(fsPath: string): string;
  224. /**
  225. * Assign partial data to the map
  226. */
  227. update(fsPath: string, mod: Partial<ModuleCache$1>): this;
  228. set(fsPath: string, mod: ModuleCache$1): this;
  229. get(fsPath: string): ModuleCache$1;
  230. delete(fsPath: string): boolean;
  231. /**
  232. * Invalidate modules that dependent on the given modules, up to the main entry
  233. */
  234. invalidateDepTree(ids: string[] | Set<string>, invalidated?: Set<string>): Set<string>;
  235. /**
  236. * Invalidate dependency modules of the given modules, down to the bottom-level dependencies
  237. */
  238. invalidateSubDepTree(ids: string[] | Set<string>, invalidated?: Set<string>): Set<string>;
  239. }
  240. declare class ViteNodeRunner {
  241. options: ViteNodeRunnerOptions;
  242. root: string;
  243. debug: boolean;
  244. /**
  245. * Holds the cache of modules
  246. * Keys of the map are filepaths, or plain package names
  247. */
  248. moduleCache: ModuleCacheMap;
  249. constructor(options: ViteNodeRunnerOptions);
  250. executeFile(file: string): Promise<any>;
  251. executeId(id: string): Promise<any>;
  252. /** @internal */
  253. cachedRequest(rawId: string, callstack: string[]): Promise<any>;
  254. /** @internal */
  255. directRequest(id: string, fsPath: string, _callstack: string[]): Promise<any>;
  256. prepareContext(context: Record<string, any>): Record<string, any>;
  257. shouldResolveId(dep: string): boolean;
  258. /**
  259. * Define if a module should be interop-ed
  260. * This function mostly for the ability to override by subclass
  261. */
  262. shouldInterop(path: string, mod: any): boolean;
  263. /**
  264. * Import a module and interop it
  265. */
  266. interopedImport(path: string): Promise<any>;
  267. hasNestedDefault(target: any): any;
  268. }
  269. interface DepsHandlingOptions {
  270. external?: (string | RegExp)[];
  271. inline?: (string | RegExp)[] | true;
  272. /**
  273. * Try to guess the CJS version of a package when it's invalid ESM
  274. * @default false
  275. */
  276. fallbackCJS?: boolean;
  277. }
  278. interface StartOfSourceMap {
  279. file?: string;
  280. sourceRoot?: string;
  281. }
  282. interface RawSourceMap extends StartOfSourceMap {
  283. version: string;
  284. sources: string[];
  285. names: string[];
  286. sourcesContent?: string[];
  287. mappings: string;
  288. }
  289. interface FetchResult {
  290. code?: string;
  291. externalize?: string;
  292. map?: RawSourceMap;
  293. }
  294. declare type HotContext = Omit<ViteHotContext, 'acceptDeps' | 'decline'>;
  295. declare type FetchFunction = (id: string) => Promise<FetchResult>;
  296. declare type ResolveIdFunction$1 = (id: string, importer?: string) => Promise<ViteNodeResolveId | null>;
  297. declare type CreateHotContextFunction = (runner: ViteNodeRunner, url: string) => HotContext;
  298. interface ModuleCache$1 {
  299. promise?: Promise<any>;
  300. exports?: any;
  301. code?: string;
  302. /**
  303. * Module ids that imports this module
  304. */
  305. importers?: Set<string>;
  306. }
  307. interface ViteNodeRunnerOptions {
  308. root: string;
  309. fetchModule: FetchFunction;
  310. resolveId?: ResolveIdFunction$1;
  311. createHotContext?: CreateHotContextFunction;
  312. base?: string;
  313. moduleCache?: ModuleCacheMap;
  314. interopDefault?: boolean;
  315. requestStubs?: Record<string, any>;
  316. debug?: boolean;
  317. }
  318. interface ViteNodeResolveId {
  319. external?: boolean | 'absolute' | 'relative';
  320. id: string;
  321. meta?: Record<string, any> | null;
  322. moduleSideEffects?: boolean | 'no-treeshake' | null;
  323. syntheticNamedExports?: boolean | string | null;
  324. }
  325. interface ViteNodeServerOptions {
  326. /**
  327. * Inject inline sourcemap to modules
  328. * @default 'inline'
  329. */
  330. sourcemap?: 'inline' | boolean;
  331. /**
  332. * Deps handling
  333. */
  334. deps?: DepsHandlingOptions;
  335. /**
  336. * Transform method for modules
  337. */
  338. transformMode?: {
  339. ssr?: RegExp[];
  340. web?: RegExp[];
  341. };
  342. debug?: DebuggerOptions;
  343. }
  344. interface DebuggerOptions {
  345. /**
  346. * Dump the transformed module to filesystem
  347. * Passing a string will dump to the specified path
  348. */
  349. dumpModules?: boolean | string;
  350. /**
  351. * Read dumpped module from filesystem whenever exists.
  352. * Useful for debugging by modifying the dump result from the filesystem.
  353. */
  354. loadDumppedModules?: boolean;
  355. }
  356. declare class Debugger {
  357. options: DebuggerOptions;
  358. dumpDir: string | undefined;
  359. initPromise: Promise<void> | undefined;
  360. externalizeMap: Map<string, string>;
  361. constructor(root: string, options: DebuggerOptions);
  362. clearDump(): Promise<void>;
  363. encodeId(id: string): string;
  364. recordExternalize(id: string, path: string): Promise<void>;
  365. dumpFile(id: string, result: TransformResult$1 | null): Promise<void>;
  366. loadDump(id: string): Promise<TransformResult$1 | null>;
  367. writeInfo(): Promise<void>;
  368. }
  369. declare class ViteNodeServer {
  370. server: ViteDevServer;
  371. options: ViteNodeServerOptions;
  372. private fetchPromiseMap;
  373. private transformPromiseMap;
  374. fetchCache: Map<string, {
  375. duration?: number | undefined;
  376. timestamp: number;
  377. result: FetchResult;
  378. }>;
  379. externalizeCache: Map<string, Promise<string | false>>;
  380. debugger?: Debugger;
  381. constructor(server: ViteDevServer, options?: ViteNodeServerOptions);
  382. shouldExternalize(id: string): Promise<string | false>;
  383. resolveId(id: string, importer?: string): Promise<ViteNodeResolveId | null>;
  384. fetchModule(id: string): Promise<FetchResult>;
  385. transformRequest(id: string): Promise<TransformResult$1 | null | undefined>;
  386. getTransformMode(id: string): "web" | "ssr";
  387. private _fetchModule;
  388. private _transformRequest;
  389. }
  390. declare class SnapshotManager {
  391. options: SnapshotStateOptions;
  392. summary: SnapshotSummary;
  393. extension: string;
  394. constructor(options: SnapshotStateOptions);
  395. clear(): void;
  396. add(result: SnapshotResult): void;
  397. resolvePath(testPath: string): string;
  398. }
  399. declare type RunWithFiles = (files: string[], invalidates?: string[]) => Promise<void>;
  400. interface WorkerPool {
  401. runTests: RunWithFiles;
  402. close: () => Promise<void>;
  403. }
  404. interface CollectingPromise {
  405. promise: Promise<void>;
  406. resolve: () => void;
  407. }
  408. declare class StateManager {
  409. filesMap: Map<string, File>;
  410. pathsSet: Set<string>;
  411. collectingPromise: CollectingPromise | undefined;
  412. idMap: Map<string, Task>;
  413. taskFileMap: WeakMap<Task, File>;
  414. errorsSet: Set<unknown>;
  415. catchError(err: unknown, type: string): void;
  416. clearErrors(): void;
  417. getUnhandledErrors(): unknown[];
  418. startCollectingPaths(): void;
  419. finishCollectingPaths(): void;
  420. getPaths(): Promise<string[]>;
  421. getFiles(keys?: string[]): File[];
  422. getFilepaths(): string[];
  423. getFailedFilepaths(): string[];
  424. collectPaths(paths?: string[]): void;
  425. collectFiles(files?: File[]): void;
  426. clearFiles(paths?: string[]): void;
  427. updateId(task: Task): void;
  428. updateTasks(packs: TaskResultPack[]): void;
  429. updateUserLog(log: UserConsoleLog): void;
  430. }
  431. declare class Logger {
  432. ctx: Vitest;
  433. console: Console;
  434. outputStream: NodeJS.WriteStream & {
  435. fd: 1;
  436. };
  437. errorStream: NodeJS.WriteStream & {
  438. fd: 2;
  439. };
  440. logUpdate: ((...text: string[]) => void) & {
  441. clear(): void;
  442. done(): void;
  443. };
  444. private _clearScreenPending;
  445. constructor(ctx: Vitest, console?: Console);
  446. log(...args: any[]): void;
  447. error(...args: any[]): void;
  448. warn(...args: any[]): void;
  449. clearScreen(message: string, force?: boolean): void;
  450. private _clearScreen;
  451. printError(err: unknown, fullStack?: boolean, type?: string): Promise<void>;
  452. printNoTestFound(filters?: string[]): void;
  453. printBanner(): void;
  454. printUnhandledErrors(errors: unknown[]): Promise<void>;
  455. }
  456. interface SuiteResultCache {
  457. failed: boolean;
  458. duration: number;
  459. }
  460. declare class ResultsCache {
  461. private cache;
  462. private cachePath;
  463. private version;
  464. private root;
  465. getCachePath(): string | null;
  466. setConfig(root: string, config: ResolvedConfig['cache']): void;
  467. getResults(fsPath: string): SuiteResultCache | undefined;
  468. readFromCache(): Promise<void>;
  469. updateResults(files: File[]): void;
  470. removeFromCache(filepath: string): void;
  471. writeToCache(): Promise<void>;
  472. }
  473. interface CliOptions extends UserConfig {
  474. /**
  475. * Override the watch mode
  476. */
  477. run?: boolean;
  478. }
  479. declare function startVitest(mode: VitestRunMode, cliFilters: string[], options: CliOptions, viteOverrides?: UserConfig$1): Promise<boolean>;
  480. declare type FileStatsCache = Pick<Stats, 'size'>;
  481. declare class FilesStatsCache {
  482. cache: Map<string, FileStatsCache>;
  483. getStats(fsPath: string): FileStatsCache | undefined;
  484. updateStats(fsPath: string): Promise<void>;
  485. removeStats(fsPath: string): void;
  486. }
  487. declare class VitestCache {
  488. results: ResultsCache;
  489. stats: FilesStatsCache;
  490. getFileTestResults(id: string): SuiteResultCache | undefined;
  491. getFileStats(id: string): {
  492. size: number;
  493. } | undefined;
  494. static resolveCacheDir(root: string, dir: string | undefined): string;
  495. static clearCache(options: CliOptions): Promise<{
  496. dir: string;
  497. cleared: boolean;
  498. }>;
  499. }
  500. declare class Vitest {
  501. readonly mode: VitestRunMode;
  502. config: ResolvedConfig;
  503. configOverride: Partial<ResolvedConfig> | undefined;
  504. server: ViteDevServer;
  505. state: StateManager;
  506. snapshot: SnapshotManager;
  507. cache: VitestCache;
  508. reporters: Reporter[];
  509. coverageProvider: CoverageProvider | null | undefined;
  510. logger: Logger;
  511. pool: WorkerPool | undefined;
  512. vitenode: ViteNodeServer;
  513. invalidates: Set<string>;
  514. changedTests: Set<string>;
  515. runningPromise?: Promise<void>;
  516. closingPromise?: Promise<void>;
  517. isFirstRun: boolean;
  518. restartsCount: number;
  519. runner: ViteNodeRunner;
  520. constructor(mode: VitestRunMode);
  521. private _onRestartListeners;
  522. setServer(options: UserConfig, server: ViteDevServer): Promise<void>;
  523. initCoverageProvider(): Promise<CoverageProvider | null | undefined>;
  524. getSerializableConfig(): ResolvedConfig;
  525. start(filters?: string[]): Promise<void>;
  526. private getTestDependencies;
  527. filterTestsBySource(tests: string[]): Promise<string[]>;
  528. runFiles(paths: string[]): Promise<void>;
  529. rerunFiles(files?: string[], trigger?: string): Promise<void>;
  530. changeNamePattern(pattern: string, files?: string[], trigger?: string): Promise<void>;
  531. changeFilenamePattern(pattern: string): Promise<void>;
  532. rerunFailed(): Promise<void>;
  533. updateSnapshot(files?: string[]): Promise<void>;
  534. private _rerunTimer;
  535. private scheduleRerun;
  536. private unregisterWatcher;
  537. private registerWatcher;
  538. /**
  539. * @returns A value indicating whether rerun is needed (changedTests was mutated)
  540. */
  541. private handleFileChanged;
  542. close(): Promise<void>;
  543. exit(force?: boolean): Promise<void>;
  544. report<T extends keyof Reporter>(name: T, ...args: ArgumentsType$1<Reporter[T]>): Promise<void>;
  545. globTestFiles(filters?: string[]): Promise<string[]>;
  546. isTargetFile(id: string, source?: string): Promise<boolean>;
  547. isInSourceTestFile(code: string): boolean;
  548. onServerRestart(fn: OnServerRestartHandler): void;
  549. }
  550. declare type MockMap = Map<string, Record<string, string | null | (() => unknown)>>;
  551. interface TestSequencer {
  552. /**
  553. * Slicing tests into shards. Will be run before `sort`.
  554. * Only run, if `shard` is defined.
  555. */
  556. shard(files: string[]): Awaitable<string[]>;
  557. sort(files: string[]): Awaitable<string[]>;
  558. }
  559. interface TestSequencerConstructor {
  560. new (ctx: Vitest): TestSequencer;
  561. }
  562. declare abstract class BaseReporter implements Reporter {
  563. start: number;
  564. end: number;
  565. watchFilters?: string[];
  566. isTTY: false;
  567. ctx: Vitest;
  568. private _filesInWatchMode;
  569. private _lastRunTimeout;
  570. private _lastRunTimer;
  571. private _lastRunCount;
  572. private _timeStart;
  573. constructor();
  574. get mode(): VitestRunMode;
  575. onInit(ctx: Vitest): void;
  576. relative(path: string): string;
  577. onFinished(files?: File[], errors?: unknown[]): Promise<void>;
  578. onTaskUpdate(packs: TaskResultPack[]): void;
  579. onWatcherStart(): Promise<void>;
  580. private resetLastRunLog;
  581. onWatcherRerun(files: string[], trigger?: string): Promise<void>;
  582. onUserConsoleLog(log: UserConsoleLog): void;
  583. shouldLog(log: UserConsoleLog): boolean;
  584. onServerRestart(reason?: string): void;
  585. reportSummary(files: File[]): Promise<void>;
  586. reportTestSummary(files: File[]): Promise<void>;
  587. private printErrorsSummary;
  588. reportBenchmarkSummary(files: File[]): Promise<void>;
  589. private printTaskErrors;
  590. registerUnhandledRejection(): void;
  591. }
  592. interface ListRendererOptions {
  593. renderSucceed?: boolean;
  594. logger: Logger;
  595. showHeap: boolean;
  596. }
  597. declare const createListRenderer: (_tasks: Task[], options: ListRendererOptions) => {
  598. start(): any;
  599. update(_tasks: Task[]): any;
  600. stop(): Promise<any>;
  601. clear(): void;
  602. };
  603. declare class DefaultReporter extends BaseReporter {
  604. renderer?: ReturnType<typeof createListRenderer>;
  605. rendererOptions: ListRendererOptions;
  606. onTestRemoved(trigger?: string): Promise<void>;
  607. onCollected(): void;
  608. onFinished(files?: File[], errors?: unknown[]): Promise<void>;
  609. onWatcherStart(): Promise<void>;
  610. stopListRender(): Promise<void>;
  611. onWatcherRerun(files: string[], trigger?: string): Promise<void>;
  612. onUserConsoleLog(log: UserConsoleLog): void;
  613. }
  614. declare class DotReporter extends BaseReporter {
  615. renderer?: ReturnType<typeof createListRenderer>;
  616. onCollected(): void;
  617. onFinished(files?: File[], errors?: unknown[]): Promise<void>;
  618. onWatcherStart(): Promise<void>;
  619. stopListRender(): Promise<void>;
  620. onWatcherRerun(files: string[], trigger?: string): Promise<void>;
  621. onUserConsoleLog(log: UserConsoleLog): void;
  622. }
  623. interface Callsite {
  624. line: number;
  625. column: number;
  626. }
  627. declare class JsonReporter$1 implements Reporter {
  628. start: number;
  629. ctx: Vitest;
  630. onInit(ctx: Vitest): void;
  631. protected logTasks(files: File[]): Promise<void>;
  632. onFinished(files?: File[]): Promise<void>;
  633. /**
  634. * Writes the report to an output file if specified in the config,
  635. * or logs it to the console otherwise.
  636. * @param report
  637. */
  638. writeReport(report: string): Promise<void>;
  639. protected getFailureLocation(test: Task): Promise<Callsite | undefined>;
  640. }
  641. declare class VerboseReporter extends DefaultReporter {
  642. constructor();
  643. onTaskUpdate(packs: TaskResultPack[]): void;
  644. }
  645. declare class TapReporter implements Reporter {
  646. protected ctx: Vitest;
  647. private logger;
  648. onInit(ctx: Vitest): void;
  649. static getComment(task: Task): string;
  650. private logErrorDetails;
  651. protected logTasks(tasks: Task[]): void;
  652. onFinished(files?: File[]): Promise<void>;
  653. }
  654. declare class JUnitReporter implements Reporter {
  655. private ctx;
  656. private reportFile?;
  657. private baseLog;
  658. private logger;
  659. onInit(ctx: Vitest): Promise<void>;
  660. writeElement(name: string, attrs: Record<string, any>, children: () => Promise<void>): Promise<void>;
  661. writeErrorDetails(error: ErrorWithDiff): Promise<void>;
  662. writeLogs(task: Task, type: 'err' | 'out'): Promise<void>;
  663. writeTasks(tasks: Task[], filename: string): Promise<void>;
  664. onFinished(files?: File[]): Promise<void>;
  665. }
  666. declare class TapFlatReporter extends TapReporter {
  667. onInit(ctx: Vitest): void;
  668. onFinished(files?: File[]): Promise<void>;
  669. }
  670. declare class JsonReporter implements Reporter {
  671. start: number;
  672. ctx: Vitest;
  673. onInit(ctx: Vitest): void;
  674. protected logTasks(files: File[]): Promise<void>;
  675. onFinished(files?: File[]): Promise<void>;
  676. /**
  677. * Writes the report to an output file if specified in the config,
  678. * or logs it to the console otherwise.
  679. * @param report
  680. */
  681. writeReport(report: string): Promise<void>;
  682. }
  683. declare const BenchmarkReportsMap: {
  684. default: typeof VerboseReporter;
  685. json: typeof JsonReporter;
  686. };
  687. declare type BenchmarkBuiltinReporters = keyof typeof BenchmarkReportsMap;
  688. declare const ReportersMap: {
  689. default: typeof DefaultReporter;
  690. verbose: typeof VerboseReporter;
  691. dot: typeof DotReporter;
  692. json: typeof JsonReporter$1;
  693. tap: typeof TapReporter;
  694. 'tap-flat': typeof TapFlatReporter;
  695. junit: typeof JUnitReporter;
  696. };
  697. declare type BuiltinReporters = keyof typeof ReportersMap;
  698. interface RollupError extends RollupLogProps {
  699. parserError?: Error;
  700. stack?: string;
  701. watchFiles?: string[];
  702. }
  703. interface RollupWarning extends RollupLogProps {
  704. chunkName?: string;
  705. cycle?: string[];
  706. exportName?: string;
  707. exporter?: string;
  708. guess?: string;
  709. importer?: string;
  710. missing?: string;
  711. modules?: string[];
  712. names?: string[];
  713. reexporter?: string;
  714. source?: string;
  715. sources?: string[];
  716. }
  717. interface RollupLogProps {
  718. code?: string;
  719. frame?: string;
  720. hook?: string;
  721. id?: string;
  722. loc?: {
  723. column: number;
  724. file?: string;
  725. line: number;
  726. };
  727. message: string;
  728. name?: string;
  729. plugin?: string;
  730. pluginCode?: string;
  731. pos?: number;
  732. url?: string;
  733. }
  734. interface ExistingRawSourceMap {
  735. file?: string;
  736. mappings: string;
  737. names: string[];
  738. sourceRoot?: string;
  739. sources: string[];
  740. sourcesContent?: string[];
  741. version: number;
  742. }
  743. interface SourceMap {
  744. file: string;
  745. mappings: string;
  746. names: string[];
  747. sources: string[];
  748. sourcesContent: string[];
  749. version: number;
  750. toString(): string;
  751. toUrl(): string;
  752. }
  753. type SourceMapInput = ExistingRawSourceMap | string | null | { mappings: '' };
  754. type PartialNull<T> = {
  755. [P in keyof T]: T[P] | null;
  756. };
  757. interface ModuleOptions {
  758. meta: CustomPluginOptions;
  759. moduleSideEffects: boolean | 'no-treeshake';
  760. syntheticNamedExports: boolean | string;
  761. }
  762. interface SourceDescription extends Partial<PartialNull<ModuleOptions>> {
  763. ast?: AcornNode;
  764. code: string;
  765. map?: SourceMapInput;
  766. }
  767. interface PluginCache {
  768. delete(id: string): boolean;
  769. get<T = any>(id: string): T;
  770. has(id: string): boolean;
  771. set<T = any>(id: string, value: T): void;
  772. }
  773. interface MinimalPluginContext {
  774. meta: PluginContextMeta;
  775. }
  776. interface EmittedAsset {
  777. fileName?: string;
  778. name?: string;
  779. source?: string | Uint8Array;
  780. type: 'asset';
  781. }
  782. interface EmittedChunk {
  783. fileName?: string;
  784. id: string;
  785. implicitlyLoadedAfterOneOf?: string[];
  786. importer?: string;
  787. name?: string;
  788. preserveSignature?: PreserveEntrySignaturesOption;
  789. type: 'chunk';
  790. }
  791. type EmittedFile = EmittedAsset | EmittedChunk;
  792. type EmitAsset = (name: string, source?: string | Uint8Array) => string;
  793. type EmitChunk = (id: string, options?: { name?: string }) => string;
  794. type EmitFile = (emittedFile: EmittedFile) => string;
  795. interface ModuleInfo extends ModuleOptions {
  796. ast: AcornNode | null;
  797. code: string | null;
  798. dynamicImporters: readonly string[];
  799. dynamicallyImportedIdResolutions: readonly ResolvedId[];
  800. dynamicallyImportedIds: readonly string[];
  801. hasDefaultExport: boolean | null;
  802. /** @deprecated Use `moduleSideEffects` instead */
  803. hasModuleSideEffects: boolean | 'no-treeshake';
  804. id: string;
  805. implicitlyLoadedAfterOneOf: readonly string[];
  806. implicitlyLoadedBefore: readonly string[];
  807. importedIdResolutions: readonly ResolvedId[];
  808. importedIds: readonly string[];
  809. importers: readonly string[];
  810. isEntry: boolean;
  811. isExternal: boolean;
  812. isIncluded: boolean | null;
  813. }
  814. type GetModuleInfo = (moduleId: string) => ModuleInfo | null;
  815. interface CustomPluginOptions {
  816. [plugin: string]: any;
  817. }
  818. interface PluginContext extends MinimalPluginContext {
  819. addWatchFile: (id: string) => void;
  820. cache: PluginCache;
  821. /** @deprecated Use `this.emitFile` instead */
  822. emitAsset: EmitAsset;
  823. /** @deprecated Use `this.emitFile` instead */
  824. emitChunk: EmitChunk;
  825. emitFile: EmitFile;
  826. error: (err: RollupError | string, pos?: number | { column: number; line: number }) => never;
  827. /** @deprecated Use `this.getFileName` instead */
  828. getAssetFileName: (assetReferenceId: string) => string;
  829. /** @deprecated Use `this.getFileName` instead */
  830. getChunkFileName: (chunkReferenceId: string) => string;
  831. getFileName: (fileReferenceId: string) => string;
  832. getModuleIds: () => IterableIterator<string>;
  833. getModuleInfo: GetModuleInfo;
  834. getWatchFiles: () => string[];
  835. /** @deprecated Use `this.resolve` instead */
  836. isExternal: IsExternal;
  837. load: (
  838. options: { id: string; resolveDependencies?: boolean } & Partial<PartialNull<ModuleOptions>>
  839. ) => Promise<ModuleInfo>;
  840. /** @deprecated Use `this.getModuleIds` instead */
  841. moduleIds: IterableIterator<string>;
  842. parse: (input: string, options?: any) => AcornNode;
  843. resolve: (
  844. source: string,
  845. importer?: string,
  846. options?: { custom?: CustomPluginOptions; isEntry?: boolean; skipSelf?: boolean }
  847. ) => Promise<ResolvedId | null>;
  848. /** @deprecated Use `this.resolve` instead */
  849. resolveId: (source: string, importer?: string) => Promise<string | null>;
  850. setAssetSource: (assetReferenceId: string, source: string | Uint8Array) => void;
  851. warn: (warning: RollupWarning | string, pos?: number | { column: number; line: number }) => void;
  852. }
  853. interface PluginContextMeta {
  854. rollupVersion: string;
  855. watchMode: boolean;
  856. }
  857. interface ResolvedId extends ModuleOptions {
  858. external: boolean | 'absolute';
  859. id: string;
  860. }
  861. type IsExternal = (
  862. source: string,
  863. importer: string | undefined,
  864. isResolved: boolean
  865. ) => boolean;
  866. interface TransformPluginContext extends PluginContext {
  867. getCombinedSourcemap: () => SourceMap;
  868. }
  869. type TransformResult = string | null | void | Partial<SourceDescription>;
  870. type PreserveEntrySignaturesOption = false | 'strict' | 'allow-extension' | 'exports-only';
  871. interface AcornNode {
  872. end: number;
  873. start: number;
  874. type: string;
  875. }
  876. declare type Awaitable<T> = T | PromiseLike<T>;
  877. declare type Nullable<T> = T | null | undefined;
  878. declare type Arrayable<T> = T | Array<T>;
  879. declare type ArgumentsType$1<T> = T extends (...args: infer U) => any ? U : never;
  880. declare type MergeInsertions<T> = T extends object ? {
  881. [K in keyof T]: MergeInsertions<T[K]>;
  882. } : T;
  883. declare type DeepMerge<F, S> = MergeInsertions<{
  884. [K in keyof F | keyof S]: K extends keyof S & keyof F ? DeepMerge<F[K], S[K]> : K extends keyof S ? S[K] : K extends keyof F ? F[K] : never;
  885. }>;
  886. declare type MutableArray<T extends readonly any[]> = {
  887. -readonly [k in keyof T]: T[k];
  888. };
  889. interface Constructable {
  890. new (...args: any[]): any;
  891. }
  892. interface ModuleCache {
  893. promise?: Promise<any>;
  894. exports?: any;
  895. code?: string;
  896. }
  897. interface EnvironmentReturn {
  898. teardown: (global: any) => Awaitable<void>;
  899. }
  900. interface Environment {
  901. name: string;
  902. setup(global: any, options: Record<string, any>): Awaitable<EnvironmentReturn>;
  903. }
  904. interface UserConsoleLog {
  905. content: string;
  906. type: 'stdout' | 'stderr';
  907. taskId?: string;
  908. time: number;
  909. size: number;
  910. }
  911. interface Position {
  912. source?: string;
  913. line: number;
  914. column: number;
  915. }
  916. interface ParsedStack {
  917. method: string;
  918. file: string;
  919. line: number;
  920. column: number;
  921. sourcePos?: Position;
  922. }
  923. interface ErrorWithDiff extends Error {
  924. name: string;
  925. nameStr?: string;
  926. stack?: string;
  927. stackStr?: string;
  928. stacks?: ParsedStack[];
  929. showDiff?: boolean;
  930. actual?: any;
  931. expected?: any;
  932. operator?: string;
  933. type?: string;
  934. }
  935. interface ModuleGraphData {
  936. graph: Record<string, string[]>;
  937. externalized: string[];
  938. inlined: string[];
  939. }
  940. declare type OnServerRestartHandler = (reason?: string) => Promise<void> | void;
  941. declare type ArgumentsType<T> = T extends (...args: infer A) => any ? A : never;
  942. declare type ReturnType$1<T> = T extends (...args: any) => infer R ? R : never;
  943. declare type PromisifyFn<T> = ReturnType$1<T> extends Promise<any> ? T : (...args: ArgumentsType<T>) => Promise<Awaited<ReturnType$1<T>>>;
  944. declare type BirpcFn<T> = PromisifyFn<T> & {
  945. /**
  946. * Send event without asking for response
  947. */
  948. asEvent(...args: ArgumentsType<T>): void;
  949. };
  950. declare type BirpcReturn<RemoteFunctions> = {
  951. [K in keyof RemoteFunctions]: BirpcFn<RemoteFunctions[K]>;
  952. };
  953. declare type ChainableFunction<T extends string, Args extends any[], R = any, E = {}> = {
  954. (...args: Args): R;
  955. } & {
  956. [x in T]: ChainableFunction<T, Args, R, E>;
  957. } & {
  958. fn: (this: Record<T, boolean | undefined>, ...args: Args) => R;
  959. } & E;
  960. interface BenchmarkUserOptions {
  961. /**
  962. * Include globs for benchmark test files
  963. *
  964. * @default ['**\/*.{bench,benchmark}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']
  965. */
  966. include?: string[];
  967. /**
  968. * Exclude globs for benchmark test files
  969. * @default ['node_modules', 'dist', '.idea', '.git', '.cache']
  970. */
  971. exclude?: string[];
  972. /**
  973. * Include globs for in-source benchmark test files
  974. *
  975. * @default []
  976. */
  977. includeSource?: string[];
  978. /**
  979. * Custom reporter for output. Can contain one or more built-in report names, reporter instances,
  980. * and/or paths to custom reporters
  981. */
  982. reporters?: Arrayable<BenchmarkBuiltinReporters | Reporter>;
  983. /**
  984. * Write test results to a file when the `--reporter=json` option is also specified.
  985. * Also definable individually per reporter by using an object instead.
  986. */
  987. outputFile?: string | (Partial<Record<BenchmarkBuiltinReporters, string>> & Record<string, string>);
  988. }
  989. interface Benchmark extends TaskBase {
  990. type: 'benchmark';
  991. suite: Suite;
  992. result?: TaskResult;
  993. fails?: boolean;
  994. task?: Task$1;
  995. options: Options;
  996. }
  997. interface BenchmarkResult extends TaskResult$1 {
  998. name: string;
  999. rank: number;
  1000. }
  1001. declare type BenchFunction = (this: Bench) => Promise<void> | void;
  1002. declare type BenchmarkAPI = ChainableFunction<'skip' | 'only', [
  1003. name: string,
  1004. fn: BenchFunction,
  1005. options?: Options
  1006. ], void> & {
  1007. skipIf(condition: any): BenchmarkAPI;
  1008. runIf(condition: any): BenchmarkAPI;
  1009. };
  1010. declare type RunMode = 'run' | 'skip' | 'only' | 'todo';
  1011. declare type TaskState = RunMode | 'pass' | 'fail';
  1012. interface TaskBase {
  1013. id: string;
  1014. name: string;
  1015. mode: RunMode;
  1016. concurrent?: boolean;
  1017. shuffle?: boolean;
  1018. suite?: Suite;
  1019. file?: File;
  1020. result?: TaskResult;
  1021. retry?: number;
  1022. logs?: UserConsoleLog[];
  1023. }
  1024. interface TaskResult {
  1025. state: TaskState;
  1026. duration?: number;
  1027. startTime?: number;
  1028. heap?: number;
  1029. error?: ErrorWithDiff;
  1030. htmlError?: string;
  1031. hooks?: Partial<Record<keyof SuiteHooks, TaskState>>;
  1032. benchmark?: BenchmarkResult;
  1033. retryCount?: number;
  1034. }
  1035. declare type TaskResultPack = [id: string, result: TaskResult | undefined];
  1036. interface Suite extends TaskBase {
  1037. type: 'suite';
  1038. tasks: Task[];
  1039. filepath?: string;
  1040. benchmark?: Bench;
  1041. }
  1042. interface File extends Suite {
  1043. filepath: string;
  1044. collectDuration?: number;
  1045. setupDuration?: number;
  1046. }
  1047. interface Test<ExtraContext = {}> extends TaskBase {
  1048. type: 'test';
  1049. suite: Suite;
  1050. result?: TaskResult;
  1051. fails?: boolean;
  1052. context: TestContext & ExtraContext;
  1053. }
  1054. declare type Task = Test | Suite | File | Benchmark;
  1055. declare type DoneCallback = (error?: any) => void;
  1056. declare type TestFunction<ExtraContext = {}> = (context: TestContext & ExtraContext) => Awaitable<any> | void;
  1057. declare type ExtractEachCallbackArgs<T extends ReadonlyArray<any>> = {
  1058. 1: [T[0]];
  1059. 2: [T[0], T[1]];
  1060. 3: [T[0], T[1], T[2]];
  1061. 4: [T[0], T[1], T[2], T[3]];
  1062. 5: [T[0], T[1], T[2], T[3], T[4]];
  1063. 6: [T[0], T[1], T[2], T[3], T[4], T[5]];
  1064. 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6]];
  1065. 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]];
  1066. 9: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]];
  1067. 10: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]];
  1068. fallback: Array<T extends ReadonlyArray<infer U> ? U : any>;
  1069. }[T extends Readonly<[any]> ? 1 : T extends Readonly<[any, any]> ? 2 : T extends Readonly<[any, any, any]> ? 3 : T extends Readonly<[any, any, any, any]> ? 4 : T extends Readonly<[any, any, any, any, any]> ? 5 : T extends Readonly<[any, any, any, any, any, any]> ? 6 : T extends Readonly<[any, any, any, any, any, any, any]> ? 7 : T extends Readonly<[any, any, any, any, any, any, any, any]> ? 8 : T extends Readonly<[any, any, any, any, any, any, any, any, any]> ? 9 : T extends Readonly<[any, any, any, any, any, any, any, any, any, any]> ? 10 : 'fallback'];
  1070. interface SuiteEachFunction {
  1071. <T extends any[] | [any]>(cases: ReadonlyArray<T>): (name: string, fn: (...args: T) => Awaitable<void>) => void;
  1072. <T extends ReadonlyArray<any>>(cases: ReadonlyArray<T>): (name: string, fn: (...args: ExtractEachCallbackArgs<T>) => Awaitable<void>) => void;
  1073. <T>(cases: ReadonlyArray<T>): (name: string, fn: (...args: T[]) => Awaitable<void>) => void;
  1074. }
  1075. interface TestEachFunction {
  1076. <T extends any[] | [any]>(cases: ReadonlyArray<T>): (name: string, fn: (...args: T) => Awaitable<void>, options?: number | TestOptions) => void;
  1077. <T extends ReadonlyArray<any>>(cases: ReadonlyArray<T>): (name: string, fn: (...args: ExtractEachCallbackArgs<T>) => Awaitable<void>, options?: number | TestOptions) => void;
  1078. <T>(cases: ReadonlyArray<T>): (name: string, fn: (...args: T[]) => Awaitable<void>, options?: number | TestOptions) => void;
  1079. }
  1080. declare type ChainableTestAPI<ExtraContext = {}> = ChainableFunction<'concurrent' | 'only' | 'skip' | 'todo' | 'fails', [
  1081. name: string,
  1082. fn?: TestFunction<ExtraContext>,
  1083. options?: number | TestOptions
  1084. ], void, {
  1085. each: TestEachFunction;
  1086. <T extends ExtraContext>(name: string, fn?: TestFunction<T>, options?: number | TestOptions): void;
  1087. }>;
  1088. interface TestOptions {
  1089. /**
  1090. * Test timeout.
  1091. */
  1092. timeout?: number;
  1093. /**
  1094. * Times to retry the test if fails. Useful for making flaky tests more stable.
  1095. * When retries is up, the last test error will be thrown.
  1096. *
  1097. * @default 1
  1098. */
  1099. retry?: number;
  1100. }
  1101. declare type TestAPI<ExtraContext = {}> = ChainableTestAPI<ExtraContext> & {
  1102. each: TestEachFunction;
  1103. skipIf(condition: any): ChainableTestAPI<ExtraContext>;
  1104. runIf(condition: any): ChainableTestAPI<ExtraContext>;
  1105. };
  1106. declare type ChainableSuiteAPI<ExtraContext = {}> = ChainableFunction<'concurrent' | 'only' | 'skip' | 'todo' | 'shuffle', [
  1107. name: string,
  1108. factory?: SuiteFactory<ExtraContext>,
  1109. options?: number | TestOptions
  1110. ], SuiteCollector<ExtraContext>, {
  1111. each: TestEachFunction;
  1112. <T extends ExtraContext>(name: string, factory?: SuiteFactory<T>): SuiteCollector<T>;
  1113. }>;
  1114. declare type SuiteAPI<ExtraContext = {}> = ChainableSuiteAPI<ExtraContext> & {
  1115. each: SuiteEachFunction;
  1116. skipIf(condition: any): ChainableSuiteAPI<ExtraContext>;
  1117. runIf(condition: any): ChainableSuiteAPI<ExtraContext>;
  1118. };
  1119. declare type HookListener<T extends any[], Return = void> = (...args: T) => Awaitable<Return>;
  1120. declare type HookCleanupCallback = (() => Awaitable<unknown>) | void;
  1121. interface SuiteHooks<ExtraContext = {}> {
  1122. beforeAll: HookListener<[Suite | File], HookCleanupCallback>[];
  1123. afterAll: HookListener<[Suite | File]>[];
  1124. beforeEach: HookListener<[TestContext & ExtraContext, Suite], HookCleanupCallback>[];
  1125. afterEach: HookListener<[TestContext & ExtraContext, Suite]>[];
  1126. }
  1127. interface SuiteCollector<ExtraContext = {}> {
  1128. readonly name: string;
  1129. readonly mode: RunMode;
  1130. type: 'collector';
  1131. test: TestAPI<ExtraContext>;
  1132. benchmark: BenchmarkAPI;
  1133. tasks: (Suite | Test | Benchmark | SuiteCollector<ExtraContext>)[];
  1134. collect: (file?: File) => Promise<Suite>;
  1135. clear: () => void;
  1136. on: <T extends keyof SuiteHooks<ExtraContext>>(name: T, ...fn: SuiteHooks<ExtraContext>[T]) => void;
  1137. }
  1138. declare type SuiteFactory<ExtraContext = {}> = (test: (name: string, fn: TestFunction<ExtraContext>) => void) => Awaitable<void>;
  1139. interface RuntimeContext {
  1140. tasks: (SuiteCollector | Test)[];
  1141. currentSuite: SuiteCollector | null;
  1142. }
  1143. interface TestContext {
  1144. /**
  1145. * @deprecated Use promise instead
  1146. */
  1147. (error?: any): void;
  1148. /**
  1149. * Metadata of the current test
  1150. */
  1151. meta: Readonly<Test>;
  1152. /**
  1153. * A expect instance bound to the test
  1154. */
  1155. expect: Vi.ExpectStatic;
  1156. }
  1157. declare type SnapshotData = Record<string, string>;
  1158. declare type SnapshotUpdateState = 'all' | 'new' | 'none';
  1159. interface SnapshotStateOptions {
  1160. updateSnapshot: SnapshotUpdateState;
  1161. expand?: boolean;
  1162. snapshotFormat?: OptionsReceived;
  1163. resolveSnapshotPath?: (path: string, extension: string) => string;
  1164. }
  1165. interface SnapshotMatchOptions {
  1166. testName: string;
  1167. received: unknown;
  1168. key?: string;
  1169. inlineSnapshot?: string;
  1170. isInline: boolean;
  1171. error?: Error;
  1172. }
  1173. interface SnapshotResult {
  1174. filepath: string;
  1175. added: number;
  1176. fileDeleted: boolean;
  1177. matched: number;
  1178. unchecked: number;
  1179. uncheckedKeys: Array<string>;
  1180. unmatched: number;
  1181. updated: number;
  1182. }
  1183. interface UncheckedSnapshot {
  1184. filePath: string;
  1185. keys: Array<string>;
  1186. }
  1187. interface SnapshotSummary {
  1188. added: number;
  1189. didUpdate: boolean;
  1190. failure: boolean;
  1191. filesAdded: number;
  1192. filesRemoved: number;
  1193. filesRemovedList: Array<string>;
  1194. filesUnmatched: number;
  1195. filesUpdated: number;
  1196. matched: number;
  1197. total: number;
  1198. unchecked: number;
  1199. uncheckedKeysByFile: Array<UncheckedSnapshot>;
  1200. unmatched: number;
  1201. updated: number;
  1202. }
  1203. interface WorkerContext {
  1204. workerId: number;
  1205. port: MessagePort;
  1206. config: ResolvedConfig;
  1207. files: string[];
  1208. invalidates?: string[];
  1209. }
  1210. declare type ResolveIdFunction = (id: string, importer?: string) => Promise<ViteNodeResolveId | null>;
  1211. interface AfterSuiteRunMeta {
  1212. coverage?: unknown;
  1213. }
  1214. interface WorkerRPC {
  1215. fetch: FetchFunction;
  1216. resolveId: ResolveIdFunction;
  1217. getSourceMap: (id: string, force?: boolean) => Promise<RawSourceMap | undefined>;
  1218. onFinished: (files: File[], errors?: unknown[]) => void;
  1219. onWorkerExit: (code?: number) => void;
  1220. onPathsCollected: (paths: string[]) => void;
  1221. onUserConsoleLog: (log: UserConsoleLog) => void;
  1222. onUnhandledRejection: (err: unknown) => void;
  1223. onCollected: (files: File[]) => void;
  1224. onAfterSuiteRun: (meta: AfterSuiteRunMeta) => void;
  1225. onTaskUpdate: (pack: TaskResultPack[]) => void;
  1226. snapshotSaved: (snapshot: SnapshotResult) => void;
  1227. resolveSnapshotPath: (testPath: string) => string;
  1228. }
  1229. interface WorkerGlobalState {
  1230. ctx: WorkerContext;
  1231. config: ResolvedConfig;
  1232. rpc: BirpcReturn<WorkerRPC>;
  1233. current?: Test;
  1234. filepath?: string;
  1235. moduleCache: ModuleCacheMap;
  1236. browserHashMap?: Map<string, string>;
  1237. mockMap: MockMap;
  1238. }
  1239. interface CoverageProvider {
  1240. name: string;
  1241. initialize(ctx: Vitest): Promise<void> | void;
  1242. resolveOptions(): ResolvedCoverageOptions;
  1243. clean(clean?: boolean): void | Promise<void>;
  1244. onBeforeFilesRun?(): void | Promise<void>;
  1245. onAfterSuiteRun(meta: AfterSuiteRunMeta): void | Promise<void>;
  1246. reportCoverage(): void | Promise<void>;
  1247. onFileTransform?(sourceCode: string, id: string, pluginCtx: TransformPluginContext): TransformResult | Promise<TransformResult>;
  1248. }
  1249. interface CoverageProviderModule {
  1250. /**
  1251. * Factory for creating a new coverage provider
  1252. */
  1253. getProvider(): CoverageProvider | Promise<CoverageProvider>;
  1254. /**
  1255. * Executed on after each run in the worker thread. Possible to return a payload passed to the provider
  1256. */
  1257. takeCoverage?(): unknown | Promise<unknown>;
  1258. }
  1259. declare type CoverageReporter = 'clover' | 'cobertura' | 'html-spa' | 'html' | 'json-summary' | 'json' | 'lcov' | 'lcovonly' | 'none' | 'teamcity' | 'text-lcov' | 'text-summary' | 'text';
  1260. declare type CoverageOptions = BaseCoverageOptions & {
  1261. provider?: null | CoverageProviderModule;
  1262. } | CoverageC8Options & {
  1263. provider?: 'c8';
  1264. } | CoverageIstanbulOptions & {
  1265. provider?: 'istanbul';
  1266. };
  1267. declare type ResolvedCoverageOptions = {
  1268. tempDirectory: string;
  1269. } & Required<CoverageOptions>;
  1270. interface BaseCoverageOptions {
  1271. /**
  1272. * Enable coverage, pass `--coverage` to enable
  1273. *
  1274. * @default false
  1275. */
  1276. enabled?: boolean;
  1277. /**
  1278. * Clean coverage before running tests
  1279. *
  1280. * @default true
  1281. */
  1282. clean?: boolean;
  1283. /**
  1284. * Clean coverage report on watch rerun
  1285. *
  1286. * @default false
  1287. */
  1288. cleanOnRerun?: boolean;
  1289. /**
  1290. * Directory to write coverage report to
  1291. */
  1292. reportsDirectory?: string;
  1293. /**
  1294. * Reporters
  1295. *
  1296. * @default 'text'
  1297. */
  1298. reporter?: Arrayable<CoverageReporter>;
  1299. /**
  1300. * List of files included in coverage as glob patterns
  1301. */
  1302. include?: string[];
  1303. /**
  1304. * List of files excluded from coverage as glob patterns
  1305. */
  1306. exclude?: string[];
  1307. /**
  1308. * Do not show files with 100% statement, branch, and function coverage
  1309. */
  1310. skipFull?: boolean;
  1311. /**
  1312. * Check thresholds per file
  1313. *
  1314. * @default false
  1315. */
  1316. perFile?: boolean;
  1317. /**
  1318. * Threshold for lines
  1319. */
  1320. lines?: number;
  1321. /**
  1322. * Threshold for functions
  1323. */
  1324. functions?: number;
  1325. /**
  1326. * Threshold for branches
  1327. */
  1328. branches?: number;
  1329. /**
  1330. * Threshold for statements
  1331. */
  1332. statements?: number;
  1333. /**
  1334. * Extensions for files to be included in coverage
  1335. */
  1336. extension?: string | string[];
  1337. /**
  1338. * Whether to include all files, including the untested ones into report
  1339. */
  1340. all?: boolean;
  1341. }
  1342. interface CoverageIstanbulOptions extends BaseCoverageOptions {
  1343. ignoreClassMethods?: string[];
  1344. watermarks?: {
  1345. statements?: [number, number];
  1346. functions?: [number, number];
  1347. branches?: [number, number];
  1348. lines?: [number, number];
  1349. };
  1350. }
  1351. interface CoverageC8Options extends BaseCoverageOptions {
  1352. /**
  1353. * Allow files from outside of your cwd.
  1354. *
  1355. * @default false
  1356. */
  1357. allowExternal?: any;
  1358. /**
  1359. * Exclude coverage under /node_modules/
  1360. *
  1361. * @default true
  1362. */
  1363. excludeNodeModules?: boolean;
  1364. src?: string[];
  1365. 100?: boolean;
  1366. }
  1367. interface JSDOMOptions {
  1368. /**
  1369. * The html content for the test.
  1370. *
  1371. * @default '<!DOCTYPE html>'
  1372. */
  1373. html?: string | Buffer | ArrayBufferLike;
  1374. /**
  1375. * referrer just affects the value read from document.referrer.
  1376. * It defaults to no referrer (which reflects as the empty string).
  1377. */
  1378. referrer?: string;
  1379. /**
  1380. * userAgent affects the value read from navigator.userAgent, as well as the User-Agent header sent while fetching subresources.
  1381. *
  1382. * @default `Mozilla/5.0 (${process.platform}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}`
  1383. */
  1384. userAgent?: string;
  1385. /**
  1386. * url sets the value returned by window.location, document.URL, and document.documentURI,
  1387. * and affects things like resolution of relative URLs within the document
  1388. * and the same-origin restrictions and referrer used while fetching subresources.
  1389. *
  1390. * @default 'http://localhost:3000'.
  1391. */
  1392. url?: string;
  1393. /**
  1394. * contentType affects the value read from document.contentType, and how the document is parsed: as HTML or as XML.
  1395. * Values that are not "text/html" or an XML mime type will throw.
  1396. *
  1397. * @default 'text/html'.
  1398. */
  1399. contentType?: string;
  1400. /**
  1401. * The maximum size in code units for the separate storage areas used by localStorage and sessionStorage.
  1402. * Attempts to store data larger than this limit will cause a DOMException to be thrown. By default, it is set
  1403. * to 5,000,000 code units per origin, as inspired by the HTML specification.
  1404. *
  1405. * @default 5_000_000
  1406. */
  1407. storageQuota?: number;
  1408. /**
  1409. * Enable console?
  1410. *
  1411. * @default false
  1412. */
  1413. console?: boolean;
  1414. /**
  1415. * jsdom does not have the capability to render visual content, and will act like a headless browser by default.
  1416. * It provides hints to web pages through APIs such as document.hidden that their content is not visible.
  1417. *
  1418. * When the `pretendToBeVisual` option is set to `true`, jsdom will pretend that it is rendering and displaying
  1419. * content.
  1420. *
  1421. * @default true
  1422. */
  1423. pretendToBeVisual?: boolean;
  1424. /**
  1425. * `includeNodeLocations` preserves the location info produced by the HTML parser,
  1426. * allowing you to retrieve it with the nodeLocation() method (described below).
  1427. *
  1428. * It defaults to false to give the best performance,
  1429. * and cannot be used with an XML content type since our XML parser does not support location info.
  1430. *
  1431. * @default false
  1432. */
  1433. includeNodeLocations?: boolean | undefined;
  1434. /**
  1435. * @default 'dangerously'
  1436. */
  1437. runScripts?: 'dangerously' | 'outside-only';
  1438. /**
  1439. * Enable CookieJar
  1440. *
  1441. * @default false
  1442. */
  1443. cookieJar?: boolean;
  1444. resources?: 'usable' | any;
  1445. }
  1446. interface Reporter {
  1447. onInit?(ctx: Vitest): void;
  1448. onPathsCollected?: (paths?: string[]) => Awaitable<void>;
  1449. onCollected?: (files?: File[]) => Awaitable<void>;
  1450. onFinished?: (files?: File[], errors?: unknown[]) => Awaitable<void>;
  1451. onTaskUpdate?: (packs: TaskResultPack[]) => Awaitable<void>;
  1452. onTestRemoved?: (trigger?: string) => Awaitable<void>;
  1453. onWatcherStart?: () => Awaitable<void>;
  1454. onWatcherRerun?: (files: string[], trigger?: string) => Awaitable<void>;
  1455. onServerRestart?: (reason?: string) => Awaitable<void>;
  1456. onUserConsoleLog?: (log: UserConsoleLog) => Awaitable<void>;
  1457. }
  1458. declare type BuiltinEnvironment = 'node' | 'jsdom' | 'happy-dom' | 'edge-runtime';
  1459. declare type VitestEnvironment = BuiltinEnvironment | (string & Record<never, never>);
  1460. declare type CSSModuleScopeStrategy = 'stable' | 'scoped' | 'non-scoped';
  1461. declare type ApiConfig = Pick<CommonServerOptions, 'port' | 'strictPort' | 'host'>;
  1462. interface EnvironmentOptions {
  1463. /**
  1464. * jsdom options.
  1465. */
  1466. jsdom?: JSDOMOptions;
  1467. [x: string]: unknown;
  1468. }
  1469. declare type VitestRunMode = 'test' | 'benchmark';
  1470. interface InlineConfig {
  1471. /**
  1472. * Benchmark options.
  1473. *
  1474. * @default {}
  1475. */
  1476. benchmark?: BenchmarkUserOptions;
  1477. /**
  1478. * Include globs for test files
  1479. *
  1480. * @default ['**\/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']
  1481. */
  1482. include?: string[];
  1483. /**
  1484. * Exclude globs for test files
  1485. * @default ['node_modules', 'dist', '.idea', '.git', '.cache']
  1486. */
  1487. exclude?: string[];
  1488. /**
  1489. * Include globs for in-source test files
  1490. *
  1491. * @default []
  1492. */
  1493. includeSource?: string[];
  1494. /**
  1495. * Handling for dependencies inlining or externalizing
  1496. */
  1497. deps?: {
  1498. /**
  1499. * Externalize means that Vite will bypass the package to native Node.
  1500. *
  1501. * Externalized dependencies will not be applied Vite's transformers and resolvers.
  1502. * And does not support HMR on reload.
  1503. *
  1504. * Typically, packages under `node_modules` are externalized.
  1505. */
  1506. external?: (string | RegExp)[];
  1507. /**
  1508. * Vite will process inlined modules.
  1509. *
  1510. * This could be helpful to handle packages that ship `.js` in ESM format (that Node can't handle).
  1511. *
  1512. * If `true`, every dependency will be inlined
  1513. */
  1514. inline?: (string | RegExp)[] | true;
  1515. /**
  1516. * Interpret CJS module's default as named exports
  1517. *
  1518. * @default true
  1519. */
  1520. interopDefault?: boolean;
  1521. /**
  1522. * When a dependency is a valid ESM package, try to guess the cjs version based on the path.
  1523. * This will significantly improve the performance in huge repo, but might potentially
  1524. * cause some misalignment if a package have different logic in ESM and CJS mode.
  1525. *
  1526. * @default false
  1527. */
  1528. fallbackCJS?: boolean;
  1529. /**
  1530. * Use experimental Node loader to resolve imports inside node_modules using Vite resolve algorithm.
  1531. * @default false
  1532. */
  1533. registerNodeLoader?: boolean;
  1534. };
  1535. /**
  1536. * Base directory to scan for the test files
  1537. *
  1538. * @default `config.root`
  1539. */
  1540. dir?: string;
  1541. /**
  1542. * Register apis globally
  1543. *
  1544. * @default false
  1545. */
  1546. globals?: boolean;
  1547. /**
  1548. * Running environment
  1549. *
  1550. * Supports 'node', 'jsdom', 'happy-dom', 'edge-runtime'
  1551. *
  1552. * If used unsupported string, will try to load the package `vitest-environment-${env}`
  1553. *
  1554. * @default 'node'
  1555. */
  1556. environment?: VitestEnvironment;
  1557. /**
  1558. * Environment options.
  1559. */
  1560. environmentOptions?: EnvironmentOptions;
  1561. /**
  1562. * Update snapshot
  1563. *
  1564. * @default false
  1565. */
  1566. update?: boolean;
  1567. /**
  1568. * Watch mode
  1569. *
  1570. * @default true
  1571. */
  1572. watch?: boolean;
  1573. /**
  1574. * Project root
  1575. *
  1576. * @default process.cwd()
  1577. */
  1578. root?: string;
  1579. /**
  1580. * Custom reporter for output. Can contain one or more built-in report names, reporter instances,
  1581. * and/or paths to custom reporters
  1582. */
  1583. reporters?: Arrayable<BuiltinReporters | Reporter | Omit<string, BuiltinReporters>>;
  1584. /**
  1585. * diff output length
  1586. */
  1587. outputTruncateLength?: number;
  1588. /**
  1589. * number of diff output lines
  1590. */
  1591. outputDiffLines?: number;
  1592. /**
  1593. * Write test results to a file when the --reporter=json` or `--reporter=junit` option is also specified.
  1594. * Also definable individually per reporter by using an object instead.
  1595. */
  1596. outputFile?: string | (Partial<Record<BuiltinReporters, string>> & Record<string, string>);
  1597. /**
  1598. * Enable multi-threading
  1599. *
  1600. * @default true
  1601. */
  1602. threads?: boolean;
  1603. /**
  1604. * Maximum number of threads
  1605. *
  1606. * @default available CPUs
  1607. */
  1608. maxThreads?: number;
  1609. /**
  1610. * Minimum number of threads
  1611. *
  1612. * @default available CPUs
  1613. */
  1614. minThreads?: number;
  1615. /**
  1616. * Default timeout of a test in milliseconds
  1617. *
  1618. * @default 5000
  1619. */
  1620. testTimeout?: number;
  1621. /**
  1622. * Default timeout of a hook in milliseconds
  1623. *
  1624. * @default 10000
  1625. */
  1626. hookTimeout?: number;
  1627. /**
  1628. * Default timeout to wait for close when Vitest shuts down, in milliseconds
  1629. *
  1630. * @default 1000
  1631. */
  1632. teardownTimeout?: number;
  1633. /**
  1634. * Silent mode
  1635. *
  1636. * @default false
  1637. */
  1638. silent?: boolean;
  1639. /**
  1640. * Path to setup files
  1641. */
  1642. setupFiles?: string | string[];
  1643. /**
  1644. * Path to global setup files
  1645. */
  1646. globalSetup?: string | string[];
  1647. /**
  1648. * Glob pattern of file paths to be ignore from triggering watch rerun
  1649. */
  1650. watchExclude?: string[];
  1651. /**
  1652. * Glob patter of file paths that will trigger the whole suite rerun
  1653. *
  1654. * Useful if you are testing calling CLI commands
  1655. *
  1656. * @default []
  1657. */
  1658. forceRerunTriggers?: string[];
  1659. /**
  1660. * Isolate environment for each test file
  1661. *
  1662. * @default true
  1663. */
  1664. isolate?: boolean;
  1665. /**
  1666. * Coverage options
  1667. */
  1668. coverage?: CoverageOptions;
  1669. /**
  1670. * run test names with the specified pattern
  1671. */
  1672. testNamePattern?: string | RegExp;
  1673. /**
  1674. * Will call `.mockClear()` on all spies before each test
  1675. * @default false
  1676. */
  1677. clearMocks?: boolean;
  1678. /**
  1679. * Will call `.mockReset()` on all spies before each test
  1680. * @default false
  1681. */
  1682. mockReset?: boolean;
  1683. /**
  1684. * Will call `.mockRestore()` on all spies before each test
  1685. * @default false
  1686. */
  1687. restoreMocks?: boolean;
  1688. /**
  1689. * Serve API options.
  1690. *
  1691. * When set to true, the default port is 51204.
  1692. *
  1693. * @default false
  1694. */
  1695. api?: boolean | number | ApiConfig;
  1696. /**
  1697. * Enable Vitest UI
  1698. * @internal WIP
  1699. */
  1700. ui?: boolean;
  1701. /**
  1702. * Use in browser environment
  1703. * @experimental
  1704. */
  1705. browser?: boolean;
  1706. /**
  1707. * Open UI automatically.
  1708. *
  1709. * @default true
  1710. */
  1711. open?: boolean;
  1712. /**
  1713. * Base url for the UI
  1714. *
  1715. * @default '/__vitest__/'
  1716. */
  1717. uiBase?: string;
  1718. /**
  1719. * Determine the transform method of modules
  1720. */
  1721. transformMode?: {
  1722. /**
  1723. * Use SSR transform pipeline for the specified files.
  1724. * Vite plugins will receive `ssr: true` flag when processing those files.
  1725. *
  1726. * @default [/\.([cm]?[jt]sx?|json)$/]
  1727. */
  1728. ssr?: RegExp[];
  1729. /**
  1730. * First do a normal transform pipeline (targeting browser),
  1731. * then then do a SSR rewrite to run the code in Node.
  1732. * Vite plugins will receive `ssr: false` flag when processing those files.
  1733. *
  1734. * @default other than `ssr`
  1735. */
  1736. web?: RegExp[];
  1737. };
  1738. /**
  1739. * Format options for snapshot testing.
  1740. */
  1741. snapshotFormat?: PrettyFormatOptions;
  1742. /**
  1743. * Resolve custom snapshot path
  1744. */
  1745. resolveSnapshotPath?: (path: string, extension: string) => string;
  1746. /**
  1747. * Pass with no tests
  1748. */
  1749. passWithNoTests?: boolean;
  1750. /**
  1751. * Allow tests and suites that are marked as only
  1752. */
  1753. allowOnly?: boolean;
  1754. /**
  1755. * Show heap usage after each test. Useful for debugging memory leaks.
  1756. */
  1757. logHeapUsage?: boolean;
  1758. /**
  1759. * Custom environment variables assigned to `process.env` before running tests.
  1760. */
  1761. env?: Record<string, string>;
  1762. /**
  1763. * Options for @sinon/fake-timers
  1764. */
  1765. fakeTimers?: FakeTimerInstallOpts;
  1766. /**
  1767. * Custom handler for console.log in tests.
  1768. *
  1769. * Return `false` to ignore the log.
  1770. */
  1771. onConsoleLog?: (log: string, type: 'stdout' | 'stderr') => false | void;
  1772. /**
  1773. * Indicates if CSS files should be processed.
  1774. *
  1775. * When excluded, the CSS files will be replaced with empty strings to bypass the subsequent processing.
  1776. *
  1777. * @default { include: [], modules: { classNameStrategy: false } }
  1778. */
  1779. css?: boolean | {
  1780. include?: RegExp | RegExp[];
  1781. exclude?: RegExp | RegExp[];
  1782. modules?: {
  1783. classNameStrategy?: CSSModuleScopeStrategy;
  1784. };
  1785. };
  1786. /**
  1787. * A number of tests that are allowed to run at the same time marked with `test.concurrent`.
  1788. * @default 5
  1789. */
  1790. maxConcurrency?: number;
  1791. /**
  1792. * Options for configuring cache policy.
  1793. * @default { dir: 'node_modules/.vitest' }
  1794. */
  1795. cache?: false | {
  1796. dir?: string;
  1797. };
  1798. /**
  1799. * Options for configuring the order of running tests.
  1800. */
  1801. sequence?: {
  1802. /**
  1803. * Class that handles sorting and sharding algorithm.
  1804. * If you only need to change sorting, you can extend
  1805. * your custom sequencer from `BaseSequencer` from `vitest/node`.
  1806. * @default BaseSequencer
  1807. */
  1808. sequencer?: TestSequencerConstructor;
  1809. /**
  1810. * Should tests run in random order.
  1811. * @default false
  1812. */
  1813. shuffle?: boolean;
  1814. /**
  1815. * Seed for the random number generator.
  1816. * @default Date.now()
  1817. */
  1818. seed?: number;
  1819. };
  1820. /**
  1821. * Specifies an `Object`, or an `Array` of `Object`,
  1822. * which defines aliases used to replace values in `import` or `require` statements.
  1823. * Will be merged with the default aliases inside `resolve.alias`.
  1824. */
  1825. alias?: AliasOptions;
  1826. /**
  1827. * Ignore any unhandled errors that occur
  1828. */
  1829. dangerouslyIgnoreUnhandledErrors?: boolean;
  1830. }
  1831. interface UserConfig extends InlineConfig {
  1832. /**
  1833. * Path to the config file.
  1834. *
  1835. * Default resolving to one of:
  1836. * - `vitest.config.js`
  1837. * - `vitest.config.ts`
  1838. * - `vite.config.js`
  1839. * - `vite.config.ts`
  1840. */
  1841. config?: string | undefined;
  1842. /**
  1843. * Use happy-dom
  1844. */
  1845. dom?: boolean;
  1846. /**
  1847. * Run tests that cover a list of source files
  1848. */
  1849. related?: string[] | string;
  1850. /**
  1851. * Overrides Vite mode
  1852. * @default 'test'
  1853. */
  1854. mode?: string;
  1855. /**
  1856. * Runs tests that are affected by the changes in the repository, or between specified branch or commit hash
  1857. * Requires initialized git repository
  1858. * @default false
  1859. */
  1860. changed?: boolean | string;
  1861. /**
  1862. * Test suite shard to execute in a format of <index>/<count>.
  1863. * Will divide tests into a `count` numbers, and run only the `indexed` part.
  1864. * Cannot be used with enabled watch.
  1865. * @example --shard=2/3
  1866. */
  1867. shard?: string;
  1868. }
  1869. interface ResolvedConfig extends Omit<Required<UserConfig>, 'config' | 'filters' | 'coverage' | 'testNamePattern' | 'related' | 'api' | 'reporters' | 'resolveSnapshotPath' | 'benchmark' | 'shard' | 'cache' | 'sequence'> {
  1870. mode: VitestRunMode;
  1871. base?: string;
  1872. config?: string;
  1873. filters?: string[];
  1874. testNamePattern?: RegExp;
  1875. related?: string[];
  1876. coverage: ResolvedCoverageOptions;
  1877. snapshotOptions: SnapshotStateOptions;
  1878. reporters: (Reporter | BuiltinReporters)[];
  1879. defines: Record<string, any>;
  1880. api?: ApiConfig;
  1881. benchmark?: Required<Omit<BenchmarkUserOptions, 'outputFile'>> & {
  1882. outputFile?: BenchmarkUserOptions['outputFile'];
  1883. };
  1884. shard?: {
  1885. index: number;
  1886. count: number;
  1887. };
  1888. cache: {
  1889. dir: string;
  1890. } | false;
  1891. sequence: {
  1892. sequencer: TestSequencerConstructor;
  1893. shuffle?: boolean;
  1894. seed?: number;
  1895. };
  1896. }
  1897. declare type VitestInlineConfig = InlineConfig;
  1898. declare module 'vite' {
  1899. interface UserConfig {
  1900. /**
  1901. * Options for Vitest
  1902. */
  1903. test?: VitestInlineConfig;
  1904. }
  1905. }
  1906. declare type Formatter = (input: string | number | null | undefined) => string;
  1907. interface MatcherHintOptions {
  1908. comment?: string;
  1909. expectedColor?: Formatter;
  1910. isDirectExpectCall?: boolean;
  1911. isNot?: boolean;
  1912. promise?: string;
  1913. receivedColor?: Formatter;
  1914. secondArgument?: string;
  1915. secondArgumentColor?: Formatter;
  1916. }
  1917. interface DiffOptions {
  1918. aAnnotation?: string;
  1919. aColor?: Formatter;
  1920. aIndicator?: string;
  1921. bAnnotation?: string;
  1922. bColor?: Formatter;
  1923. bIndicator?: string;
  1924. changeColor?: Formatter;
  1925. changeLineTrailingSpaceColor?: Formatter;
  1926. commonColor?: Formatter;
  1927. commonIndicator?: string;
  1928. commonLineTrailingSpaceColor?: Formatter;
  1929. contextLines?: number;
  1930. emptyFirstOrLastLinePlaceholder?: string;
  1931. expand?: boolean;
  1932. includeChangeCounts?: boolean;
  1933. omitAnnotationLines?: boolean;
  1934. patchColor?: Formatter;
  1935. compareKeys?: any;
  1936. }
  1937. declare const EXPECTED_COLOR: Formatter;
  1938. declare const RECEIVED_COLOR: Formatter;
  1939. declare const INVERTED_COLOR: Formatter;
  1940. declare const BOLD_WEIGHT: Formatter;
  1941. declare const DIM_COLOR: Formatter;
  1942. declare function matcherHint(matcherName: string, received?: string, expected?: string, options?: MatcherHintOptions): string;
  1943. declare function stringify(object: unknown, maxDepth?: number, options?: PrettyFormatOptions): string;
  1944. declare const printReceived: (object: unknown) => string;
  1945. declare const printExpected: (value: unknown) => string;
  1946. declare function diff(a: any, b: any, options?: DiffOptions): string;
  1947. declare const jestMatcherUtils_EXPECTED_COLOR: typeof EXPECTED_COLOR;
  1948. declare const jestMatcherUtils_RECEIVED_COLOR: typeof RECEIVED_COLOR;
  1949. declare const jestMatcherUtils_INVERTED_COLOR: typeof INVERTED_COLOR;
  1950. declare const jestMatcherUtils_BOLD_WEIGHT: typeof BOLD_WEIGHT;
  1951. declare const jestMatcherUtils_DIM_COLOR: typeof DIM_COLOR;
  1952. declare const jestMatcherUtils_matcherHint: typeof matcherHint;
  1953. declare const jestMatcherUtils_stringify: typeof stringify;
  1954. declare const jestMatcherUtils_printReceived: typeof printReceived;
  1955. declare const jestMatcherUtils_printExpected: typeof printExpected;
  1956. declare const jestMatcherUtils_diff: typeof diff;
  1957. declare namespace jestMatcherUtils {
  1958. export {
  1959. jestMatcherUtils_EXPECTED_COLOR as EXPECTED_COLOR,
  1960. jestMatcherUtils_RECEIVED_COLOR as RECEIVED_COLOR,
  1961. jestMatcherUtils_INVERTED_COLOR as INVERTED_COLOR,
  1962. jestMatcherUtils_BOLD_WEIGHT as BOLD_WEIGHT,
  1963. jestMatcherUtils_DIM_COLOR as DIM_COLOR,
  1964. jestMatcherUtils_matcherHint as matcherHint,
  1965. jestMatcherUtils_stringify as stringify,
  1966. jestMatcherUtils_printReceived as printReceived,
  1967. jestMatcherUtils_printExpected as printExpected,
  1968. jestMatcherUtils_diff as diff,
  1969. };
  1970. }
  1971. /**
  1972. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  1973. *
  1974. * This source code is licensed under the MIT license found in the
  1975. * LICENSE file in the root directory of this source tree.
  1976. */
  1977. interface SnapshotReturnOptions {
  1978. actual: string;
  1979. count: number;
  1980. expected?: string;
  1981. key: string;
  1982. pass: boolean;
  1983. }
  1984. interface SaveStatus {
  1985. deleted: boolean;
  1986. saved: boolean;
  1987. }
  1988. declare class SnapshotState {
  1989. testFilePath: string;
  1990. snapshotPath: string;
  1991. private _counters;
  1992. private _dirty;
  1993. private _updateSnapshot;
  1994. private _snapshotData;
  1995. private _initialData;
  1996. private _inlineSnapshots;
  1997. private _uncheckedKeys;
  1998. private _snapshotFormat;
  1999. added: number;
  2000. expand: boolean;
  2001. matched: number;
  2002. unmatched: number;
  2003. updated: number;
  2004. constructor(testFilePath: string, snapshotPath: string, options: SnapshotStateOptions);
  2005. markSnapshotsAsCheckedForTest(testName: string): void;
  2006. private _inferInlineSnapshotStack;
  2007. private _addSnapshot;
  2008. clear(): void;
  2009. save(): Promise<SaveStatus>;
  2010. getUncheckedCount(): number;
  2011. getUncheckedKeys(): Array<string>;
  2012. removeUncheckedKeys(): void;
  2013. match({ testName, received, key, inlineSnapshot, isInline, error, }: SnapshotMatchOptions): SnapshotReturnOptions;
  2014. pack(): Promise<SnapshotResult>;
  2015. }
  2016. declare type Tester = (a: any, b: any) => boolean | undefined;
  2017. interface MatcherState {
  2018. assertionCalls: number;
  2019. currentTestName?: string;
  2020. dontThrow?: () => void;
  2021. error?: Error;
  2022. equals: (a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean) => boolean;
  2023. expand?: boolean;
  2024. expectedAssertionsNumber?: number | null;
  2025. expectedAssertionsNumberErrorGen?: (() => Error) | null;
  2026. isExpectingAssertions?: boolean;
  2027. isExpectingAssertionsError?: Error | null;
  2028. isNot: boolean;
  2029. environment: VitestEnvironment;
  2030. promise: string;
  2031. snapshotState: SnapshotState;
  2032. suppressedErrors: Array<Error>;
  2033. testPath?: string;
  2034. utils: typeof jestMatcherUtils & {
  2035. iterableEquality: Tester;
  2036. subsetEquality: Tester;
  2037. };
  2038. }
  2039. interface SyncExpectationResult {
  2040. pass: boolean;
  2041. message: () => string;
  2042. actual?: any;
  2043. expected?: any;
  2044. }
  2045. declare type AsyncExpectationResult = Promise<SyncExpectationResult>;
  2046. declare type ExpectationResult = SyncExpectationResult | AsyncExpectationResult;
  2047. interface RawMatcherFn<T extends MatcherState = MatcherState> {
  2048. (this: T, received: any, expected: any, options?: any): ExpectationResult;
  2049. }
  2050. declare type MatchersObject<T extends MatcherState = MatcherState> = Record<string, RawMatcherFn<T>>;
  2051. declare type Promisify<O> = {
  2052. [K in keyof O]: O[K] extends (...args: infer A) => infer R ? O extends R ? Promisify<O[K]> : (...args: A) => Promise<R> : O[K];
  2053. };
  2054. declare global {
  2055. namespace jest {
  2056. interface Matchers<R, T = {}> {
  2057. }
  2058. }
  2059. namespace Vi {
  2060. interface ExpectStatic extends Chai.ExpectStatic, AsymmetricMatchersContaining {
  2061. <T>(actual: T, message?: string): Vi.Assertion<T>;
  2062. extend(expects: MatchersObject): void;
  2063. assertions(expected: number): void;
  2064. hasAssertions(): void;
  2065. anything(): any;
  2066. any(constructor: unknown): any;
  2067. addSnapshotSerializer(plugin: Plugin): void;
  2068. getState(): MatcherState;
  2069. setState(state: Partial<MatcherState>): void;
  2070. not: AsymmetricMatchersContaining;
  2071. }
  2072. interface AsymmetricMatchersContaining {
  2073. stringContaining(expected: string): any;
  2074. objectContaining(expected: any): any;
  2075. arrayContaining<T = unknown>(expected: Array<T>): any;
  2076. stringMatching(expected: string | RegExp): any;
  2077. }
  2078. interface JestAssertion<T = any> extends jest.Matchers<void, T> {
  2079. toMatchSnapshot<U extends {
  2080. [P in keyof T]: any;
  2081. }>(snapshot: Partial<U>, message?: string): void;
  2082. toMatchSnapshot(message?: string): void;
  2083. matchSnapshot<U extends {
  2084. [P in keyof T]: any;
  2085. }>(snapshot: Partial<U>, message?: string): void;
  2086. matchSnapshot(message?: string): void;
  2087. toMatchInlineSnapshot<U extends {
  2088. [P in keyof T]: any;
  2089. }>(properties: Partial<U>, snapshot?: string, message?: string): void;
  2090. toMatchInlineSnapshot(snapshot?: string, message?: string): void;
  2091. toThrowErrorMatchingSnapshot(message?: string): void;
  2092. toThrowErrorMatchingInlineSnapshot(snapshot?: string, message?: string): void;
  2093. toEqual<E>(expected: E): void;
  2094. toStrictEqual<E>(expected: E): void;
  2095. toBe<E>(expected: E): void;
  2096. toMatch(expected: string | RegExp): void;
  2097. toMatchObject<E extends {} | any[]>(expected: E): void;
  2098. toContain<E>(item: E): void;
  2099. toContainEqual<E>(item: E): void;
  2100. toBeTruthy(): void;
  2101. toBeFalsy(): void;
  2102. toBeGreaterThan(num: number | bigint): void;
  2103. toBeGreaterThanOrEqual(num: number | bigint): void;
  2104. toBeLessThan(num: number | bigint): void;
  2105. toBeLessThanOrEqual(num: number | bigint): void;
  2106. toBeNaN(): void;
  2107. toBeUndefined(): void;
  2108. toBeNull(): void;
  2109. toBeDefined(): void;
  2110. toBeTypeOf(expected: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined'): void;
  2111. toBeInstanceOf<E>(expected: E): void;
  2112. toBeCalledTimes(times: number): void;
  2113. toHaveLength(length: number): void;
  2114. toHaveProperty<E>(property: string | string[], value?: E): void;
  2115. toBeCloseTo(number: number, numDigits?: number): void;
  2116. toHaveBeenCalledTimes(times: number): void;
  2117. toHaveBeenCalledOnce(): void;
  2118. toHaveBeenCalled(): void;
  2119. toBeCalled(): void;
  2120. toHaveBeenCalledWith<E extends any[]>(...args: E): void;
  2121. toBeCalledWith<E extends any[]>(...args: E): void;
  2122. toHaveBeenNthCalledWith<E extends any[]>(n: number, ...args: E): void;
  2123. nthCalledWith<E extends any[]>(nthCall: number, ...args: E): void;
  2124. toHaveBeenLastCalledWith<E extends any[]>(...args: E): void;
  2125. lastCalledWith<E extends any[]>(...args: E): void;
  2126. toThrow(expected?: string | Constructable | RegExp | Error): void;
  2127. toThrowError(expected?: string | Constructable | RegExp | Error): void;
  2128. toReturn(): void;
  2129. toHaveReturned(): void;
  2130. toReturnTimes(times: number): void;
  2131. toHaveReturnedTimes(times: number): void;
  2132. toReturnWith<E>(value: E): void;
  2133. toHaveReturnedWith<E>(value: E): void;
  2134. toHaveLastReturnedWith<E>(value: E): void;
  2135. lastReturnedWith<E>(value: E): void;
  2136. toHaveNthReturnedWith<E>(nthCall: number, value: E): void;
  2137. nthReturnedWith<E>(nthCall: number, value: E): void;
  2138. toSatisfy<E>(matcher: (value: E) => boolean, message?: string): void;
  2139. }
  2140. type VitestAssertion<A, T> = {
  2141. [K in keyof A]: A[K] extends Chai.Assertion ? Assertion<T> : A[K] extends (...args: any[]) => any ? A[K] : VitestAssertion<A[K], T>;
  2142. } & ((type: string, message?: string) => Assertion);
  2143. interface Assertion<T = any> extends VitestAssertion<Chai.Assertion, T>, JestAssertion<T> {
  2144. resolves: Promisify<Assertion<T>>;
  2145. rejects: Promisify<Assertion<T>>;
  2146. }
  2147. }
  2148. }
  2149. export { MutableArray as $, ApiConfig as A, BuiltinEnvironment as B, CSSModuleScopeStrategy as C, DoneCallback as D, EnvironmentOptions as E, FakeTimerInstallOpts as F, SnapshotSummary as G, HookListener as H, InlineConfig as I, JSDOMOptions as J, ResolveIdFunction as K, AfterSuiteRunMeta as L, ModuleGraphData as M, WorkerRPC as N, WorkerGlobalState as O, Awaitable as P, Nullable as Q, ResolvedConfig as R, Suite as S, TaskResultPack as T, UserConfig as U, VitestEnvironment as V, WorkerContext as W, Arrayable as X, ArgumentsType$1 as Y, MergeInsertions as Z, DeepMerge as _, File as a, Constructable as a0, ModuleCache as a1, EnvironmentReturn as a2, Environment as a3, UserConsoleLog as a4, Position as a5, ParsedStack as a6, ErrorWithDiff as a7, OnServerRestartHandler as a8, CoverageProvider as a9, CoverageProviderModule as aa, CoverageReporter as ab, CoverageOptions as ac, ResolvedCoverageOptions as ad, BaseCoverageOptions as ae, CoverageIstanbulOptions as af, CoverageC8Options as ag, BenchmarkUserOptions as ah, Benchmark as ai, BenchmarkResult as aj, BenchFunction as ak, BenchmarkAPI as al, ModuleCacheMap as am, ViteNodeRunnerOptions as an, MockMap as ao, ViteNodeRunner as ap, TestSequencer as aq, startVitest as ar, TestSequencerConstructor as as, Reporter as b, VitestRunMode as c, RunMode as d, TaskState as e, TaskBase as f, TaskResult as g, Test as h, Task as i, TestFunction as j, TestOptions as k, TestAPI as l, SuiteAPI as m, HookCleanupCallback as n, SuiteHooks as o, SuiteCollector as p, SuiteFactory as q, RuntimeContext as r, TestContext as s, Vitest as t, SnapshotData as u, SnapshotUpdateState as v, SnapshotStateOptions as w, SnapshotMatchOptions as x, SnapshotResult as y, UncheckedSnapshot as z };