diff --git a/.gitignore b/.gitignore index 98d5c9045..8ca3bb427 100644 --- a/.gitignore +++ b/.gitignore @@ -32,4 +32,5 @@ test/cli/fixtures/browser-multiple/basic-* # exclude static html reporter folder test/browser/html/ test/core/html/ -.vitest-attachments \ No newline at end of file +.vitest-attachments +explainFiles.txt \ No newline at end of file diff --git a/package.json b/package.json index dd058f53c..e32de768a 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "test:ci": "CI=true pnpm -r --reporter-hide-prefix --stream --sequential --filter '@vitest/test-*' --filter !test-browser run test", "test:examples": "CI=true pnpm -r --reporter-hide-prefix --stream --filter '@vitest/example-*' run test", "test:ecosystem-ci": "ECOSYSTEM_CI=true pnpm test:ci", + "typebuild": "tsx ./scripts/explain-types.ts", "typecheck": "tsc -p tsconfig.check.json --noEmit", "typecheck:why": "tsc -p tsconfig.check.json --noEmit --explainFiles > explainTypes.txt", "ui:build": "vite build packages/ui", diff --git a/packages/browser/package.json b/packages/browser/package.json index ab89144a9..7d717d625 100644 --- a/packages/browser/package.json +++ b/packages/browser/package.json @@ -64,6 +64,8 @@ "providers" ], "scripts": { + "typecheck": "tsc -p ./src/client/tsconfig.json --noEmit", + "typecheck:why": "tsc -p ./src/client/tsconfig.json --noEmit --explainFiles > explainTypes.txt", "build": "rimraf dist && pnpm build:node && pnpm build:client", "build:client": "vite build src/client", "build:node": "rollup -c", diff --git a/packages/browser/src/client/client.ts b/packages/browser/src/client/client.ts index fa9a72d39..e425c18c6 100644 --- a/packages/browser/src/client/client.ts +++ b/packages/browser/src/client/client.ts @@ -1,7 +1,7 @@ import type { ModuleMocker } from '@vitest/mocker/browser' import type { CancelReason } from '@vitest/runner' import type { BirpcReturn } from 'birpc' -import type { WebSocketBrowserEvents, WebSocketBrowserHandlers } from '../node/types' +import type { WebSocketBrowserEvents, WebSocketBrowserHandlers } from '../types' import type { IframeOrchestrator } from './orchestrator' import { createBirpc } from 'birpc' import { parse, stringify } from 'flatted' diff --git a/packages/browser/src/client/tester/context.ts b/packages/browser/src/client/tester/context.ts index 5385b322d..2c3d1c761 100644 --- a/packages/browser/src/client/tester/context.ts +++ b/packages/browser/src/client/tester/context.ts @@ -1,11 +1,14 @@ -import type { Options as TestingLibraryOptions, UserEvent as TestingLibraryUserEvent } from '@testing-library/user-event' -import type { RunnerTask } from 'vitest' +import type { + Options as TestingLibraryOptions, + UserEvent as TestingLibraryUserEvent, +} from '@testing-library/user-event' import type { BrowserLocators, BrowserPage, Locator, UserEvent, -} from '../../../context' +} from '@vitest/browser/context' +import type { RunnerTask } from 'vitest' import type { IframeViewportEvent } from '../client' import type { BrowserRunnerState } from '../utils' import type { Locator as LocatorAPI } from './locators/index' @@ -289,12 +292,19 @@ export const page: BrowserPage = { const name = options.path || `${taskName.replace(/[^a-z0-9]/gi, '-')}-${number}.png` - return ensureAwaited(error => triggerCommand('__vitest_screenshot', [name, processTimeoutOptions({ - ...options, - element: options.element - ? convertToSelector(options.element) - : undefined, - })], error)) + return ensureAwaited(error => triggerCommand( + '__vitest_screenshot', + [ + name, + processTimeoutOptions({ + ...options, + element: options.element + ? convertToSelector(options.element) + : undefined, + } as any /** TODO */), + ], + error, + )) }, getByRole() { throw new Error(`Method "getByRole" is not implemented in the "${provider}" provider.`) diff --git a/packages/browser/src/client/tester/locators/playwright.ts b/packages/browser/src/client/tester/locators/playwright.ts index 4c0f659fe..ab6538f07 100644 --- a/packages/browser/src/client/tester/locators/playwright.ts +++ b/packages/browser/src/client/tester/locators/playwright.ts @@ -1,4 +1,12 @@ -import type { UserEventClearOptions, UserEventClickOptions, UserEventDragAndDropOptions, UserEventFillOptions, UserEventHoverOptions, UserEventSelectOptions, UserEventUploadOptions } from '@vitest/browser/context' +import type { + UserEventClearOptions, + UserEventClickOptions, + UserEventDragAndDropOptions, + UserEventFillOptions, + UserEventHoverOptions, + UserEventSelectOptions, + UserEventUploadOptions, +} from '@vitest/browser/context' import { page, server } from '@vitest/browser/context' import { getByAltTextSelector, diff --git a/packages/browser/src/client/tester/locators/webdriverio.ts b/packages/browser/src/client/tester/locators/webdriverio.ts index 03765a71a..630862d84 100644 --- a/packages/browser/src/client/tester/locators/webdriverio.ts +++ b/packages/browser/src/client/tester/locators/webdriverio.ts @@ -1,4 +1,9 @@ -import type { UserEventClickOptions, UserEventDragAndDropOptions, UserEventHoverOptions, UserEventSelectOptions } from '@vitest/browser/context' +import type { + UserEventClickOptions, + UserEventDragAndDropOptions, + UserEventHoverOptions, + UserEventSelectOptions, +} from '@vitest/browser/context' import { page, server } from '@vitest/browser/context' import { getByAltTextSelector, diff --git a/packages/browser/src/client/tester/runner.ts b/packages/browser/src/client/tester/runner.ts index a0cabe1c6..ffe5e9601 100644 --- a/packages/browser/src/client/tester/runner.ts +++ b/packages/browser/src/client/tester/runner.ts @@ -1,6 +1,5 @@ import type { CancelReason, File, Suite, Task, TaskEventPack, TaskResultPack, Test, TestAnnotation, VitestRunner } from '@vitest/runner' import type { SerializedConfig, TestExecutionMethod, WorkerGlobalState } from 'vitest' -import type { VitestExecutor } from 'vitest/execute' import type { VitestBrowserClientMocker } from './mocker' import { globalChannel, onCancel } from '@vitest/browser/client' import { page, userEvent } from '@vitest/browser/context' @@ -77,7 +76,7 @@ export function createBrowserRunner( if (this.config.browser.screenshotFailures && document.body.clientHeight > 0 && task.result?.state === 'fail') { const screenshot = await page.screenshot({ timeout: this.config.browser.providerOptions?.actionTimeout ?? 5_000, - }).catch((err) => { + } as any /** TODO */).catch((err) => { console.error('[vitest] Failed to take a screenshot', err) }) if (screenshot) { @@ -239,8 +238,8 @@ export async function initiateRunner( }) const [diffOptions] = await Promise.all([ - loadDiffConfig(config, executor as unknown as VitestExecutor), - loadSnapshotSerializers(config, executor as unknown as VitestExecutor), + loadDiffConfig(config, executor as any), + loadSnapshotSerializers(config, executor as any), ]) runner.config.diffOptions = diffOptions getWorkerState().onFilterStackTrace = (stack: string) => { diff --git a/packages/browser/src/client/tester/state.ts b/packages/browser/src/client/tester/state.ts index 5cdbd00e5..8bd0e6c41 100644 --- a/packages/browser/src/client/tester/state.ts +++ b/packages/browser/src/client/tester/state.ts @@ -32,6 +32,7 @@ const state: WorkerGlobalState = { }, onCleanup: fn => getBrowserState().cleanups.push(fn), moduleCache: getBrowserState().moduleCache, + moduleExecutionInfo: new Map(), rpc: null as any, durations: { environment: 0, diff --git a/packages/browser/src/client/tsconfig.json b/packages/browser/src/client/tsconfig.json new file mode 100644 index 000000000..958f3e685 --- /dev/null +++ b/packages/browser/src/client/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../tsconfig.base.json", + "compilerOptions": { + "lib": [ + "dom", + "esnext", + "DOM.Iterable" + ], + "types": ["vite/client"], + "noEmit": true + }, + "include": [ + "./**/*.ts", + "../types.ts", + "../../matchers.d.ts", + "../../../vitest/src/integrations/chai/chai-subset.d.ts" + ], + "exclude": [ + "./vite.config.ts" + ] +} diff --git a/packages/browser/src/client/utils.ts b/packages/browser/src/client/utils.ts index b18aa80a1..a6ecd9556 100644 --- a/packages/browser/src/client/utils.ts +++ b/packages/browser/src/client/utils.ts @@ -65,7 +65,7 @@ export function ensureAwaited(promise: (error?: Error) => Promise): Promis export interface BrowserRunnerState { files: string[] runningFiles: string[] - moduleCache: WorkerGlobalState['moduleCache'] + moduleCache: Map config: SerializedConfig provider: string runner: VitestRunner diff --git a/packages/browser/src/node/cdp.ts b/packages/browser/src/node/cdp.ts index 389a9f964..40c23797f 100644 --- a/packages/browser/src/node/cdp.ts +++ b/packages/browser/src/node/cdp.ts @@ -1,5 +1,5 @@ import type { CDPSession } from 'vitest/node' -import type { WebSocketBrowserRPC } from './types' +import type { WebSocketBrowserRPC } from '../types' export class BrowserServerCDPHandler { private listenerIds: Record = {} diff --git a/packages/browser/src/node/rpc.ts b/packages/browser/src/node/rpc.ts index 1ce8b57df..c7b19290c 100644 --- a/packages/browser/src/node/rpc.ts +++ b/packages/browser/src/node/rpc.ts @@ -3,10 +3,10 @@ import type { Duplex } from 'node:stream' import type { TestError } from 'vitest' import type { BrowserCommandContext, ResolveSnapshotPathHandlerContext, TestProject } from 'vitest/node' import type { WebSocket } from 'ws' +import type { WebSocketBrowserEvents, WebSocketBrowserHandlers } from '../types' import type { ParentBrowserProject } from './projectParent' import type { WebdriverBrowserProvider } from './providers/webdriver' import type { BrowserServerState } from './state' -import type { WebSocketBrowserEvents, WebSocketBrowserHandlers } from './types' import { existsSync, promises as fs } from 'node:fs' import { AutomockedModule, AutospiedModule, ManualMockedModule, RedirectedModule } from '@vitest/mocker' import { ServerMockResolver } from '@vitest/mocker/node' diff --git a/packages/browser/src/node/state.ts b/packages/browser/src/node/state.ts index 2f04dc5cb..9561c234d 100644 --- a/packages/browser/src/node/state.ts +++ b/packages/browser/src/node/state.ts @@ -1,5 +1,5 @@ import type { BrowserServerState as IBrowserServerState } from 'vitest/node' -import type { WebSocketBrowserRPC } from './types' +import type { WebSocketBrowserRPC } from '../types' export class BrowserServerState implements IBrowserServerState { public readonly orchestrators: Map = new Map() diff --git a/packages/browser/src/node/types.ts b/packages/browser/src/types.ts similarity index 82% rename from packages/browser/src/node/types.ts rename to packages/browser/src/types.ts index 742b3544c..94fcd72e6 100644 --- a/packages/browser/src/node/types.ts +++ b/packages/browser/src/types.ts @@ -1,13 +1,12 @@ -import type { MockedModuleSerialized } from '@vitest/mocker' -import type { ServerIdResolution, ServerMockResolution } from '@vitest/mocker/node' +import type { MockedModuleSerialized, ServerIdResolution, ServerMockResolution } from '@vitest/mocker' import type { TaskEventPack, TaskResultPack, TestAnnotation } from '@vitest/runner' import type { BirpcReturn } from 'birpc' import type { AfterSuiteRunMeta, BrowserTesterOptions, CancelReason, - Reporter, RunnerTestFile, + SerializedTestSpecification, SnapshotResult, TestExecutionMethod, UserConsoleLog, @@ -60,16 +59,19 @@ export interface WebSocketBrowserHandlers { trackCdpEvent: (sessionId: string, type: 'on' | 'once' | 'off', event: string, listenerId: string) => void } -export interface WebSocketEvents - extends Pick< - Reporter, - | 'onCollected' - | 'onFinished' - | 'onTaskUpdate' - | 'onUserConsoleLog' - | 'onPathsCollected' - | 'onSpecsCollected' - > { +export type Awaitable = T | PromiseLike + +export interface WebSocketEvents { + onCollected?: (files: RunnerTestFile[]) => Awaitable + onFinished?: ( + files: File[], + errors: unknown[], + coverage?: unknown + ) => Awaitable + onTaskUpdate?: (packs: TaskResultPack[]) => Awaitable + onUserConsoleLog?: (log: UserConsoleLog) => Awaitable + onPathsCollected?: (paths?: string[]) => Awaitable + onSpecsCollected?: (specs?: SerializedTestSpecification[]) => Awaitable onFinishedReportCoverage: () => void } diff --git a/packages/browser/tsconfig.json b/packages/browser/tsconfig.json index 84f0e3d1d..89c57bbd4 100644 --- a/packages/browser/tsconfig.json +++ b/packages/browser/tsconfig.json @@ -4,5 +4,10 @@ "types": ["node", "vite/client"], "isolatedDeclarations": true }, - "exclude": ["dist", "node_modules", "**/vite.config.ts"] + "exclude": [ + "dist", + "node_modules", + "**/vite.config.ts", + "src/client/**/*.ts" + ] } diff --git a/packages/mocker/src/index.ts b/packages/mocker/src/index.ts index 062e194e3..3909b5a55 100644 --- a/packages/mocker/src/index.ts +++ b/packages/mocker/src/index.ts @@ -22,4 +22,6 @@ export type { ModuleMockFactory, ModuleMockFactoryWithHelper, ModuleMockOptions, + ServerIdResolution, + ServerMockResolution, } from './types' diff --git a/packages/mocker/src/node/index.ts b/packages/mocker/src/node/index.ts index 42f7cf80f..88376fac0 100644 --- a/packages/mocker/src/node/index.ts +++ b/packages/mocker/src/node/index.ts @@ -10,8 +10,4 @@ export type { InterceptorPluginOptions } from './interceptorPlugin' export { mockerPlugin } from './mockerPlugin' export { findMockRedirect } from './redirect' export { ServerMockResolver } from './resolver' -export type { - ServerIdResolution, - ServerMockResolution, - ServerResolverOptions, -} from './resolver' +export type { ServerResolverOptions } from './resolver' diff --git a/packages/mocker/src/node/resolver.ts b/packages/mocker/src/node/resolver.ts index 834472b22..d0aadbf8e 100644 --- a/packages/mocker/src/node/resolver.ts +++ b/packages/mocker/src/node/resolver.ts @@ -1,4 +1,5 @@ import type { Rollup, ResolvedConfig as ViteConfig, ViteDevServer } from 'vite' +import type { ServerIdResolution, ServerMockResolution } from '../types' import { existsSync, readFileSync } from 'node:fs' import { isAbsolute, join, resolve } from 'pathe' import { cleanUrl } from '../utils' @@ -181,17 +182,3 @@ function withTrailingSlash(path: string): string { return path } - -export interface ServerMockResolution { - mockType: 'manual' | 'redirect' | 'automock' | 'autospy' - resolvedId: string - resolvedUrl: string - needsInterop?: boolean - redirectUrl?: string | null -} - -export interface ServerIdResolution { - id: string - url: string - optimized: boolean -} diff --git a/packages/mocker/src/types.ts b/packages/mocker/src/types.ts index caf9964d4..facd7c01e 100644 --- a/packages/mocker/src/types.ts +++ b/packages/mocker/src/types.ts @@ -7,3 +7,17 @@ export type ModuleMockFactory = () => any export interface ModuleMockOptions { spy?: boolean } + +export interface ServerMockResolution { + mockType: 'manual' | 'redirect' | 'automock' | 'autospy' + resolvedId: string + resolvedUrl: string + needsInterop?: boolean + redirectUrl?: string | null +} + +export interface ServerIdResolution { + id: string + url: string + optimized: boolean +} diff --git a/packages/snapshot/src/index.ts b/packages/snapshot/src/index.ts index aaccc0bff..4fa23f225 100644 --- a/packages/snapshot/src/index.ts +++ b/packages/snapshot/src/index.ts @@ -6,6 +6,7 @@ export { default as SnapshotState } from './port/state' export type { SnapshotData, + SnapshotEnvironment, SnapshotMatchOptions, SnapshotResult, SnapshotSerializer, diff --git a/packages/ui/tsconfig.json b/packages/ui/tsconfig.json index 18cfa8843..20dca8962 100644 --- a/packages/ui/tsconfig.json +++ b/packages/ui/tsconfig.json @@ -2,6 +2,7 @@ "extends": "../../tsconfig.base.json", "compilerOptions": { "jsx": "preserve", + "lib": ["dom", "esnext", "DOM.Iterable"], "skipLibCheck": true }, "include": ["./client/**/*"], diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index d13646f9d..58b167463 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -47,7 +47,6 @@ export type { Constructable, DeepMerge, MergeInsertions, - MutableArray, Nullable, ParsedStack, SerializedError, diff --git a/packages/utils/src/timers.ts b/packages/utils/src/timers.ts index aa9f27480..5323d3cdb 100644 --- a/packages/utils/src/timers.ts +++ b/packages/utils/src/timers.ts @@ -1,13 +1,22 @@ const SAFE_TIMERS_SYMBOL = Symbol('vitest:SAFE_TIMERS') export interface SafeTimers { - nextTick: (cb: () => void) => void + // node.js timers + nextTick?: (cb: () => void) => void + setImmediate?: { + ( + callback: (...args: TArgs) => void, + ...args: TArgs + ): any + __promisify__: (value?: T, options?: any) => Promise + } + clearImmediate?: (immediateId: any) => void + + // cross-platform timers setTimeout: typeof setTimeout setInterval: typeof setInterval clearInterval: typeof clearInterval clearTimeout: typeof clearTimeout - setImmediate: typeof setImmediate - clearImmediate: typeof clearImmediate queueMicrotask: typeof queueMicrotask } @@ -23,7 +32,7 @@ export function getSafeTimers(): SafeTimers { } = (globalThis as any)[SAFE_TIMERS_SYMBOL] || globalThis const { nextTick: safeNextTick } = (globalThis as any)[SAFE_TIMERS_SYMBOL] - || globalThis.process || { nextTick: (cb: () => void) => cb() } + || globalThis.process || {} return { nextTick: safeNextTick, @@ -48,9 +57,7 @@ export function setSafeTimers(): void { queueMicrotask: safeQueueMicrotask, } = globalThis - const { nextTick: safeNextTick } = globalThis.process || { - nextTick: cb => cb(), - } + const { nextTick: safeNextTick } = globalThis.process || {} const timers = { nextTick: safeNextTick, diff --git a/packages/utils/src/types.ts b/packages/utils/src/types.ts index 37dcd10f3..fb39b8175 100644 --- a/packages/utils/src/types.ts +++ b/packages/utils/src/types.ts @@ -17,10 +17,6 @@ export type DeepMerge = MergeInsertions<{ : never; }> -export type MutableArray = { - -readonly [k in keyof T]: T[k]; -} - export interface Constructable { new (...args: any[]): any } diff --git a/packages/vitest/src/integrations/chai/index.ts b/packages/vitest/src/integrations/chai/index.ts index bee086916..f7dcb1e1a 100644 --- a/packages/vitest/src/integrations/chai/index.ts +++ b/packages/vitest/src/integrations/chai/index.ts @@ -1,5 +1,3 @@ -// CI fails only for this file, but it works locally - import type { Assertion, ExpectStatic, MatcherState } from '@vitest/expect' import type { TaskPopulated, Test } from '@vitest/runner' import { diff --git a/packages/vitest/src/integrations/vi.ts b/packages/vitest/src/integrations/vi.ts index b2aa5b143..8e3d95c85 100644 --- a/packages/vitest/src/integrations/vi.ts +++ b/packages/vitest/src/integrations/vi.ts @@ -724,7 +724,7 @@ function createVitest(): VitestUtils { }, resetModules() { - resetModules(workerState.moduleCache) + resetModules(workerState.moduleCache as any) return utils }, diff --git a/packages/vitest/src/node/types/config.ts b/packages/vitest/src/node/types/config.ts index d6f421884..2521b6cc7 100644 --- a/packages/vitest/src/node/types/config.ts +++ b/packages/vitest/src/node/types/config.ts @@ -7,7 +7,6 @@ import type { AliasOptions, ConfigEnv, DepOptimizationConfig, ServerOptions, Use import type { ViteNodeServerOptions } from 'vite-node' import type { ChaiConfig } from '../../integrations/chai/config' import type { SerializedConfig } from '../../runtime/config' -import type { EnvironmentOptions } from '../../types/environment' import type { Arrayable, LabelColor, ParsedStack, ProvidedContext, TestError } from '../../types/general' import type { HappyDOMOptions } from '../../types/happy-dom-options' import type { JSDOMOptions } from '../../types/jsdom-options' @@ -47,7 +46,16 @@ export type ApiConfig = Pick< 'port' | 'strictPort' | 'host' | 'middlewareMode' > -export type { EnvironmentOptions, HappyDOMOptions, JSDOMOptions } +export interface EnvironmentOptions { + /** + * jsdom options. + */ + jsdom?: JSDOMOptions + happyDOM?: HappyDOMOptions + [x: string]: unknown +} + +export type { HappyDOMOptions, JSDOMOptions } export type VitestRunMode = 'test' | 'benchmark' diff --git a/packages/vitest/src/public/index.ts b/packages/vitest/src/public/index.ts index 23d0bf2ba..dc5376386 100644 --- a/packages/vitest/src/public/index.ts +++ b/packages/vitest/src/public/index.ts @@ -1,53 +1,5 @@ -import type { - /** @deprecated import from `vitest/node` instead */ - Vitest as Vitest_, -} from '../node/core' - -import type { - BenchmarkUserOptions as BenchmarkUserOptions_, -} from '../node/types/benchmark' -import type { - ApiConfig as ApiConfig_, - BrowserConfigOptions as BrowserConfigOptions_, - BrowserScript as BrowserScript_, - BuiltinEnvironment as BuiltinEnvironment_, - CSSModuleScopeStrategy as CSSModuleScopeStrategy_, - DepsOptimizationOptions as DepsOptimizationOptions_, - EnvironmentOptions as EnvironmentOptions_, - HappyDOMOptions as HappyDOMOptions_, - InlineConfig as InlineConfig_, - JSDOMOptions as JSDOMOptions_, - Pool as Pool_, - PoolOptions as PoolOptions_, - ProjectConfig as ProjectConfig_, - ResolvedConfig as ResolvedConfig_, - SequenceHooks as SequenceHooks_, - SequenceSetupFiles as SequenceSetupFiles_, - TransformModePatterns as TransformModePatterns_, - TypecheckConfig as TypecheckConfig_, - UserConfig as UserConfig_, - UserWorkspaceConfig as UserWorkspaceConfig_, - VitestEnvironment as VitestEnvironment_, - VitestRunMode as VitestRunMode_, -} from '../node/types/config' - -import type { - /** @deprecated import from `vitest/node` instead */ - Reporter as Reporter_, -} from '../node/types/reporter' - -import type { - WorkerContext as WorkerContext_, -} from '../node/types/worker' - import type { SerializedTestSpecification } from '../runtime/types/utils' -import type { - WorkerRPC as WorkerRPC_, -} from '../types/worker' - -// TODO: deprecate in favor of `` -import '../node/types/vite' import '../types/global' export type { @@ -85,16 +37,10 @@ export type { AssertType } from '../typecheck/assertType' export { expectTypeOf } from '../typecheck/expectTypeOf' export type { ExpectTypeOf } from '../typecheck/expectTypeOf' -/** @deprecated import from `vitest/node` instead */ -export type WorkerContext = WorkerContext_ -/** @deprecated import from `vitest/node` instead */ -export type WorkerRPC = WorkerRPC_ - export type { BrowserTesterOptions } from '../types/browser' export type { AfterSuiteRunMeta, LabelColor, - ModuleCache, ModuleGraphData, ParsedStack, ProvidedContext, @@ -112,7 +58,6 @@ export type { BrowserUI } from '../types/ui' export type { ContextRPC, ContextTestEnvironment, - ResolveIdFunction, TestExecutionMethod, WorkerGlobalState, } from '../types/worker' @@ -168,11 +113,6 @@ export type { TestOptions, } from '@vitest/runner' -/** @deprecated import from `vitest/reporter` instead */ -export type Reporter = Reporter_ -/** @deprecated import from `vitest/node` instead */ -export type Vitest = Vitest_ - export type { CancelReason } from '@vitest/runner' export type { @@ -196,58 +136,6 @@ export type { MockInstance, } from '@vitest/spy' -/** @deprecated import from `vitest/node` instead */ -export type BrowserScript = BrowserScript_ -/** @deprecated import from `vitest/node` instead */ -export type BrowserConfigOptions = BrowserConfigOptions_ -/** @deprecated import from `vitest/node` instead */ -export type SequenceHooks = SequenceHooks_ -/** @deprecated import from `vitest/node` instead */ -export type SequenceSetupFiles = SequenceSetupFiles_ -/** @deprecated import from `vitest/node` instead */ -export type BuiltinEnvironment = BuiltinEnvironment_ -/** @deprecated import from `vitest/node` instead */ -export type VitestEnvironment = VitestEnvironment_ -/** @deprecated import from `vitest/node` instead */ -export type Pool = Pool_ -/** @deprecated import from `vitest/node` instead */ -export type PoolOptions = PoolOptions_ -/** @deprecated import from `vitest/node` instead */ -export type CSSModuleScopeStrategy = CSSModuleScopeStrategy_ -/** @deprecated import from `vitest/node` instead */ -export type ApiConfig = ApiConfig_ -/** @deprecated import from `vitest/node` instead */ -export type JSDOMOptions = JSDOMOptions_ -/** @deprecated import from `vitest/node` instead */ -export type HappyDOMOptions = HappyDOMOptions_ -/** @deprecated import from `vitest/node` instead */ -export type EnvironmentOptions = EnvironmentOptions_ -/** @deprecated import from `vitest/node` instead */ -export type VitestRunMode = VitestRunMode_ -/** @deprecated import from `vitest/node` instead */ -export type DepsOptimizationOptions = DepsOptimizationOptions_ -/** @deprecated import from `vitest/node` instead */ -export type TransformModePatterns = TransformModePatterns_ -/** @deprecated import from `vitest/node` instead */ -export type InlineConfig = InlineConfig_ -/** @deprecated import from `vitest/node` instead */ -export type TypecheckConfig = TypecheckConfig_ -/** @deprecated import from `vitest/node` instead */ -export type UserConfig = UserConfig_ -/** @deprecated import from `vitest/node` instead */ -export type ResolvedConfig = ResolvedConfig_ -/** @deprecated import from `vitest/node` instead */ -export type ProjectConfig = ProjectConfig_ -/** @deprecated import from `vitest/node` instead */ -export type UserWorkspaceConfig = UserWorkspaceConfig_ - export type { SerializedError } from '@vitest/utils' - -/** @deprecated use `SerializedTestSpecification` instead */ -export type SerializableSpec = SerializedTestSpecification export type { SerializedTestSpecification } - -/** @deprecated import from `vitest/node` instead */ -export type BenchmarkUserOptions = BenchmarkUserOptions_ - export type { DiffOptions } from '@vitest/utils/diff' diff --git a/packages/vitest/src/public/node.ts b/packages/vitest/src/public/node.ts index 76f64b47a..b654ebf4f 100644 --- a/packages/vitest/src/public/node.ts +++ b/packages/vitest/src/public/node.ts @@ -1,7 +1,5 @@ -import type { ModuleDiagnostic as _FileDiagnostic } from '../node/reporters/reported-tasks' import * as vite from 'vite' import { Vitest } from '../node/core' -import { TestModule as _TestFile } from '../node/reporters/reported-tasks' export const version: string = Vitest.version @@ -80,8 +78,6 @@ export type { ProjectBrowser, ResolvedBrowserOptions, } from '../node/types/browser' -/** @deprecated use `createViteServer` instead */ -export const createServer: typeof vite.createServer = vite.createServer export const createViteServer: typeof vite.createServer = vite.createServer export type { ApiConfig, @@ -89,9 +85,7 @@ export type { CSSModuleScopeStrategy, DepsOptimizationOptions, EnvironmentOptions, - HappyDOMOptions, InlineConfig, - JSDOMOptions, Pool, PoolOptions, ProjectConfig, @@ -102,9 +96,9 @@ export type { RuntimeConfig, SequenceHooks, SequenceSetupFiles, + UserConfig as TestUserConfig, TransformModePatterns, TypecheckConfig, - UserConfig, UserWorkspaceConfig, VitestEnvironment, VitestRunMode, @@ -124,19 +118,10 @@ export type { export type { VitestPluginContext } from '../node/types/plugin' export type { TestRunResult } from '../node/types/tests' -/** - * @deprecated Use `TestModule` instead - */ -export const TestFile: typeof _TestFile = _TestFile export type { WorkerContext } from '../node/types/worker' export { createViteLogger } from '../node/viteLogger' export type { WatcherTriggerPattern } from '../node/watcher' -/** - * @deprecated Use `ModuleDiagnostic` instead - */ -export type FileDiagnostic = _FileDiagnostic - export { distDir, rootDir } from '../paths' export type { diff --git a/packages/vitest/src/runtime/config.ts b/packages/vitest/src/runtime/config.ts index 0383f144e..a3b6b45f1 100644 --- a/packages/vitest/src/runtime/config.ts +++ b/packages/vitest/src/runtime/config.ts @@ -1,8 +1,7 @@ import type { FakeTimerInstallOpts } from '@sinonjs/fake-timers' import type { PrettyFormatOptions } from '@vitest/pretty-format' import type { SequenceHooks, SequenceSetupFiles } from '@vitest/runner' -import type { SnapshotUpdateState } from '@vitest/snapshot' -import type { SnapshotEnvironment } from '@vitest/snapshot/environment' +import type { SnapshotEnvironment, SnapshotUpdateState } from '@vitest/snapshot' import type { SerializedDiffOptions } from '@vitest/utils/diff' /** diff --git a/packages/vitest/src/runtime/execute.ts b/packages/vitest/src/runtime/execute.ts index dcd646db2..862275a78 100644 --- a/packages/vitest/src/runtime/execute.ts +++ b/packages/vitest/src/runtime/execute.ts @@ -152,7 +152,7 @@ export async function startVitestExecutor(options: ContextExecutorOptions): Prom return rpc().resolveId(id, importer, getTransformMode()) }, get moduleCache() { - return state().moduleCache + return state().moduleCache as ModuleCacheMap }, get moduleExecutionInfo() { return state().moduleExecutionInfo diff --git a/packages/vitest/src/runtime/rpc.ts b/packages/vitest/src/runtime/rpc.ts index 91dd95ce8..3c324f4f0 100644 --- a/packages/vitest/src/runtime/rpc.ts +++ b/packages/vitest/src/runtime/rpc.ts @@ -22,10 +22,15 @@ function withSafeTimers(fn: () => void) { try { globalThis.setTimeout = setTimeout globalThis.clearTimeout = clearTimeout - globalThis.setImmediate = setImmediate - globalThis.clearImmediate = clearImmediate - if (globalThis.process) { + if (setImmediate) { + globalThis.setImmediate = setImmediate + } + if (clearImmediate) { + globalThis.clearImmediate = clearImmediate + } + + if (globalThis.process && nextTick) { globalThis.process.nextTick = nextTick } @@ -38,7 +43,7 @@ function withSafeTimers(fn: () => void) { globalThis.setImmediate = currentSetImmediate globalThis.clearImmediate = currentClearImmediate - if (globalThis.process) { + if (globalThis.process && nextTick) { nextTick(() => { globalThis.process.nextTick = currentNextTick }) diff --git a/packages/vitest/src/runtime/runBaseTests.ts b/packages/vitest/src/runtime/runBaseTests.ts index 7f2a1acb6..5b9313531 100644 --- a/packages/vitest/src/runtime/runBaseTests.ts +++ b/packages/vitest/src/runtime/runBaseTests.ts @@ -1,4 +1,5 @@ import type { FileSpecification } from '@vitest/runner' +import type { ModuleCacheMap } from 'vite-node' import type { ResolvedTestEnvironment } from '../types/environment' import type { SerializedConfig } from './config' import type { VitestExecutor } from './execute' @@ -56,7 +57,7 @@ export async function run( for (const file of files) { if (isolate) { executor.mocker.reset() - resetModules(workerState.moduleCache, true) + resetModules(workerState.moduleCache as ModuleCacheMap, true) } workerState.filepath = file.filepath diff --git a/packages/vitest/src/runtime/runVmTests.ts b/packages/vitest/src/runtime/runVmTests.ts index c1a92b2d4..b76273ef1 100644 --- a/packages/vitest/src/runtime/runVmTests.ts +++ b/packages/vitest/src/runtime/runVmTests.ts @@ -1,4 +1,5 @@ import type { FileSpecification } from '@vitest/runner' +import type { ModuleCacheMap } from 'vite-node' import type { SerializedConfig } from './config' import type { VitestExecutor } from './execute' import { createRequire } from 'node:module' @@ -61,7 +62,7 @@ export async function run( } installSourcemapsSupport({ - getSourceMap: source => workerState.moduleCache.getSourceMap(source), + getSourceMap: source => (workerState.moduleCache as ModuleCacheMap).getSourceMap(source), }) await startCoverageInsideWorker(config.coverage, executor, { isolate: false }) diff --git a/packages/vitest/src/runtime/runners/benchmark.ts b/packages/vitest/src/runtime/runners/benchmark.ts index 2400cfa1b..9c875a43a 100644 --- a/packages/vitest/src/runtime/runners/benchmark.ts +++ b/packages/vitest/src/runtime/runners/benchmark.ts @@ -6,7 +6,7 @@ import type { VitestRunnerImportSource, } from '@vitest/runner' import type { SerializedConfig } from '../config' -import type { VitestExecutor } from '../execute' +// import type { VitestExecutor } from '../execute' import type { Benchmark, BenchmarkResult, @@ -150,7 +150,7 @@ async function runBenchmarkSuite(suite: Suite, runner: NodeBenchmarkRunner) { } export class NodeBenchmarkRunner implements VitestRunner { - private __vitest_executor!: VitestExecutor + private __vitest_executor!: any constructor(public config: SerializedConfig) {} diff --git a/packages/vitest/src/runtime/runners/test.ts b/packages/vitest/src/runtime/runners/test.ts index 4d8dcd4ad..fe823a4f9 100644 --- a/packages/vitest/src/runtime/runners/test.ts +++ b/packages/vitest/src/runtime/runners/test.ts @@ -11,7 +11,7 @@ import type { VitestRunnerImportSource, } from '@vitest/runner' import type { SerializedConfig } from '../config' -import type { VitestExecutor } from '../execute' +// import type { VitestExecutor } from '../execute' import { getState, GLOBAL_EXPECT, setState } from '@vitest/expect' import { getNames, getTestName, getTests } from '@vitest/runner/utils' import { normalize } from 'pathe' @@ -28,7 +28,7 @@ const workerContext = Object.create(null) export class VitestTestRunner implements VitestRunner { private snapshotClient = getSnapshotClient() private workerState = getWorkerState() - private __vitest_executor!: VitestExecutor + private __vitest_executor!: any private cancelRun = false private assertionsErrors = new WeakMap, Error>() diff --git a/packages/vitest/src/runtime/setup-node.ts b/packages/vitest/src/runtime/setup-node.ts index bf670f3fb..066babdf9 100644 --- a/packages/vitest/src/runtime/setup-node.ts +++ b/packages/vitest/src/runtime/setup-node.ts @@ -1,3 +1,4 @@ +import type { ModuleCacheMap } from 'vite-node' import type { ResolvedTestEnvironment } from '../types/environment' import type { SerializedConfig } from './config' import type { VitestExecutor } from './execute' @@ -66,7 +67,7 @@ export async function setupGlobalEnv( } installSourcemapsSupport({ - getSourceMap: source => state.moduleCache.getSourceMap(source), + getSourceMap: source => (state.moduleCache as ModuleCacheMap).getSourceMap(source), }) if (!config.disableConsoleIntercept) { diff --git a/packages/vitest/src/runtime/workers/vm.ts b/packages/vitest/src/runtime/workers/vm.ts index 1f050a2b0..f4f809979 100644 --- a/packages/vitest/src/runtime/workers/vm.ts +++ b/packages/vitest/src/runtime/workers/vm.ts @@ -1,4 +1,5 @@ import type { Context } from 'node:vm' +import type { ModuleCacheMap } from 'vite-node' import type { WorkerGlobalState } from '../../types/worker' import { pathToFileURL } from 'node:url' import { isContext } from 'node:vm' @@ -76,7 +77,7 @@ export async function runVmTests(method: 'run' | 'collect', state: WorkerGlobalS const executor = await startVitestExecutor({ context, - moduleCache: state.moduleCache, + moduleCache: state.moduleCache as ModuleCacheMap, state, externalModulesExecutor, requestStubs: stubs, diff --git a/packages/vitest/src/types/environment.ts b/packages/vitest/src/types/environment.ts index fb047822d..6c6d34597 100644 --- a/packages/vitest/src/types/environment.ts +++ b/packages/vitest/src/types/environment.ts @@ -1,6 +1,4 @@ import type { Awaitable } from './general' -import type { HappyDOMOptions } from './happy-dom-options' -import type { JSDOMOptions } from './jsdom-options' export interface EnvironmentReturn { teardown: (global: any) => Awaitable @@ -21,15 +19,6 @@ export interface Environment { ) => Awaitable } -export interface EnvironmentOptions { - /** - * jsdom options. - */ - jsdom?: JSDOMOptions - happyDOM?: HappyDOMOptions - [x: string]: unknown -} - export interface ResolvedTestEnvironment { environment: Environment options: Record | null diff --git a/packages/vitest/src/types/general.ts b/packages/vitest/src/types/general.ts index 5d8367968..6e61863bc 100644 --- a/packages/vitest/src/types/general.ts +++ b/packages/vitest/src/types/general.ts @@ -5,23 +5,8 @@ export type Nullable = T | null | undefined export type Arrayable = T | Array export type ArgumentsType = T extends (...args: infer U) => any ? U : never -export type MutableArray = { - -readonly [k in keyof T]: T[k]; -} - -export interface Constructable { - new (...args: any[]): any -} - export type TransformMode = 'web' | 'ssr' -/** @deprecated not used */ -export interface ModuleCache { - promise?: Promise - exports?: any - code?: string -} - export interface AfterSuiteRunMeta { coverage?: unknown testFiles: string[] diff --git a/packages/vitest/src/types/worker.ts b/packages/vitest/src/types/worker.ts index 7a871d570..6920de9de 100644 --- a/packages/vitest/src/types/worker.ts +++ b/packages/vitest/src/types/worker.ts @@ -1,17 +1,10 @@ import type { CancelReason, FileSpecification, Task } from '@vitest/runner' import type { BirpcReturn } from 'birpc' -import type { ModuleCacheMap, ModuleExecutionInfo, ViteNodeResolveId } from 'vite-node' import type { SerializedConfig } from '../runtime/config' import type { Environment } from './environment' import type { TransformMode } from './general' import type { RunnerRPC, RuntimeRPC } from './rpc' -/** @deprecated unused */ -export type ResolveIdFunction = ( - id: string, - importer?: string -) => Promise - export type WorkerRPC = BirpcReturn export interface ContextTestEnvironment { @@ -43,8 +36,8 @@ export interface WorkerGlobalState { environment: Environment environmentTeardownRun?: boolean onCancel: Promise - moduleCache: ModuleCacheMap - moduleExecutionInfo?: ModuleExecutionInfo + moduleCache: Map + moduleExecutionInfo: Map onCleanup: (listener: () => unknown) => void providedContext: Record durations: { diff --git a/packages/web-worker/tsconfig.json b/packages/web-worker/tsconfig.json index e75f9c404..90dfce908 100644 --- a/packages/web-worker/tsconfig.json +++ b/packages/web-worker/tsconfig.json @@ -1,7 +1,7 @@ { "extends": "../../tsconfig.base.json", "compilerOptions": { - "lib": ["ESNext", "WebWorker"], + "lib": ["ESNext", "WebWorker", "DOM"], "isolatedDeclarations": true }, "exclude": ["./dist"] diff --git a/packages/ws-client/tsconfig.json b/packages/ws-client/tsconfig.json index 1c5e738cb..333be106c 100644 --- a/packages/ws-client/tsconfig.json +++ b/packages/ws-client/tsconfig.json @@ -1,6 +1,7 @@ { "extends": "../../tsconfig.base.json", "compilerOptions": { + "lib": ["DOM"], "isolatedDeclarations": true }, "exclude": ["./dist"] diff --git a/scripts/explain-types.ts b/scripts/explain-types.ts new file mode 100644 index 000000000..43d75849e --- /dev/null +++ b/scripts/explain-types.ts @@ -0,0 +1,49 @@ +import { readFileSync } from 'node:fs' + +// { dep: ['dep2'], dep2: [] } +const dependencies: Record = {} +const content = readFileSync(process.argv[2], 'utf-8').split('\n') + +let lastKey = content[0] +for (let i = 1; i < content.length; i++) { + const line = content[i] + if (line.startsWith(' ')) { + const line = content[i].trim() + if (!line.startsWith('Imported via')) { + continue + } + + const [_, __, from] = (line.includes('with') + ? /Imported via '(.*)' from file '(.*)' with/.exec(line) + : /Imported via '(.*)' from file '(.*)'/.exec(line)) ?? [] + + dependencies[from] ??= [] + if (!dependencies[from].includes(lastKey)) { + dependencies[from].push(lastKey) + } + } + else { + lastKey = content[i] + } +} + +function printTree(start: string, deps: string[], depth = 1, seen = new Set()) { + for (const dep of deps) { + if (seen.has(dep)) { + continue + } + seen.add(dep) + console.error(' '.repeat(depth) + dep) + const deps = dependencies[dep] + if (deps && !dep.includes('node_modules')) { + printTree(start, deps, depth + 1, seen) + } + } +} + +for (const key in dependencies) { + if (key.startsWith('src/client')) { + console.error(key) + printTree(key, dependencies[key]) + } +} diff --git a/test/cli/test/expect-soft.test.ts b/test/cli/test/expect-soft.test.ts index d96ad33e2..8dd750a50 100644 --- a/test/cli/test/expect-soft.test.ts +++ b/test/cli/test/expect-soft.test.ts @@ -1,11 +1,11 @@ -import type { UserConfig } from 'vitest' +import type { TestUserConfig } from 'vitest/node' import { resolve } from 'node:path' import { describe, expect, test } from 'vitest' import { getCurrentTest } from 'vitest/suite' import { runVitest } from '../../test-utils' describe('expect.soft', () => { - const run = (config?: UserConfig) => runVitest({ + const run = (config?: TestUserConfig) => runVitest({ root: resolve('./fixtures/expect-soft'), include: ['expects/soft.test.ts'], setupFiles: [], diff --git a/test/cli/test/public-api.test.ts b/test/cli/test/public-api.test.ts index d2a1fb2a1..35693dbd3 100644 --- a/test/cli/test/public-api.test.ts +++ b/test/cli/test/public-api.test.ts @@ -1,5 +1,5 @@ import type { RunnerTaskResultPack, RunnerTestFile } from 'vitest' -import type { UserConfig } from 'vitest/node' +import type { TestUserConfig } from 'vitest/node' import { resolve } from 'pathe' import { expect, it } from 'vitest' import { rolldownVersion } from 'vitest/node' @@ -14,7 +14,7 @@ it.each([ enabled: true, }, }, -] as UserConfig[])('passes down metadata when $name', { timeout: 60_000, retry: 1 }, async (config) => { +] as TestUserConfig[])('passes down metadata when $name', { timeout: 60_000, retry: 1 }, async (config) => { const taskUpdate: RunnerTaskResultPack[] = [] const finishedFiles: RunnerTestFile[] = [] const collectedFiles: RunnerTestFile[] = [] diff --git a/test/cli/test/scoped-fixtures.test.ts b/test/cli/test/scoped-fixtures.test.ts index ee31758f2..365c7459a 100644 --- a/test/cli/test/scoped-fixtures.test.ts +++ b/test/cli/test/scoped-fixtures.test.ts @@ -2,7 +2,7 @@ import type { TestAPI } from 'vitest' import type { ViteUserConfig } from 'vitest/config' -import type { TestSpecification, UserConfig } from 'vitest/node' +import type { TestSpecification, TestUserConfig } from 'vitest/node' import type { TestFsStructure } from '../../test-utils' import { runInlineTests } from '../../test-utils' @@ -702,7 +702,7 @@ describe('browser tests', () => { async function runFixtureTests( extendedTest: ({ log }: { log: typeof console.log }) => TestAPI, fs: Record }) => unknown) | ViteUserConfig>, - config?: UserConfig, + config?: TestUserConfig, ) { if (typeof fs['vitest.config.js'] === 'object') { fs['vitest.config.js'].test!.globals = true diff --git a/test/config/test/bail.test.ts b/test/config/test/bail.test.ts index e9a370a61..349fcee11 100644 --- a/test/config/test/bail.test.ts +++ b/test/config/test/bail.test.ts @@ -1,10 +1,10 @@ -import type { UserConfig } from 'vitest/node' +import type { TestUserConfig } from 'vitest/node' import { expect, test } from 'vitest' import { runVitest } from '../../test-utils' -const configs: UserConfig[] = [] -const pools: UserConfig[] = [ +const configs: TestUserConfig[] = [] +const pools: TestUserConfig[] = [ { pool: 'threads' }, { pool: 'forks' }, { pool: 'threads', poolOptions: { threads: { singleThread: true } } }, diff --git a/test/config/test/browser-configs.test.ts b/test/config/test/browser-configs.test.ts index d4ae0eafb..1801fbc37 100644 --- a/test/config/test/browser-configs.test.ts +++ b/test/config/test/browser-configs.test.ts @@ -1,5 +1,5 @@ import type { ViteUserConfig } from 'vitest/config' -import type { UserConfig, VitestOptions } from 'vitest/node' +import type { TestUserConfig, VitestOptions } from 'vitest/node' import type { TestFsStructure } from '../../test-utils' import crypto from 'node:crypto' import { resolve } from 'pathe' @@ -7,7 +7,7 @@ import { describe, expect, onTestFinished, test } from 'vitest' import { createVitest } from 'vitest/node' import { runVitestCli, useFS } from '../../test-utils' -async function vitest(cliOptions: UserConfig, configValue: UserConfig = {}, viteConfig: ViteUserConfig = {}, vitestOptions: VitestOptions = {}) { +async function vitest(cliOptions: TestUserConfig, configValue: TestUserConfig = {}, viteConfig: ViteUserConfig = {}, vitestOptions: VitestOptions = {}) { const vitest = await createVitest('test', { ...cliOptions, watch: false }, { ...viteConfig, test: configValue as any }, vitestOptions) onTestFinished(() => vitest.close()) return vitest @@ -308,7 +308,7 @@ test('can enable browser-cli options for multi-project workspace', async () => { expect(projects[1].config.browser.headless).toBe(true) }) -function getCliConfig(options: UserConfig, cli: string[], fs: TestFsStructure = {}) { +function getCliConfig(options: TestUserConfig, cli: string[], fs: TestFsStructure = {}) { const root = resolve(process.cwd(), `vitest-test-${crypto.randomUUID()}`) useFS(root, { ...fs, diff --git a/test/config/test/configureVitest.test.ts b/test/config/test/configureVitest.test.ts index a17ef21f7..e470b3571 100644 --- a/test/config/test/configureVitest.test.ts +++ b/test/config/test/configureVitest.test.ts @@ -1,9 +1,9 @@ import type { ViteUserConfig } from 'vitest/config' -import type { TestProject, UserConfig, VitestOptions } from 'vitest/node' +import type { TestProject, TestUserConfig, VitestOptions } from 'vitest/node' import { expect, onTestFinished, test } from 'vitest' import { createVitest } from 'vitest/node' -async function vitest(cliOptions: UserConfig, configValue: UserConfig = {}, viteConfig: ViteUserConfig = {}, vitestOptions: VitestOptions = {}) { +async function vitest(cliOptions: TestUserConfig, configValue: TestUserConfig = {}, viteConfig: ViteUserConfig = {}, vitestOptions: VitestOptions = {}) { const vitest = await createVitest('test', { ...cliOptions, watch: false }, { ...viteConfig, test: configValue as any }, vitestOptions) onTestFinished(() => vitest.close()) return vitest diff --git a/test/config/test/failures.test.ts b/test/config/test/failures.test.ts index 6fefa943b..ebaee7124 100644 --- a/test/config/test/failures.test.ts +++ b/test/config/test/failures.test.ts @@ -1,5 +1,5 @@ import type { UserConfig as ViteUserConfig } from 'vite' -import type { UserConfig } from 'vitest/node' +import type { TestUserConfig } from 'vitest/node' import type { VitestRunnerCLIOptions } from '../../test-utils' import { cpus } from 'node:os' import { normalize, resolve } from 'pathe' @@ -11,7 +11,7 @@ const providers = ['playwright', 'webdriverio', 'preview'] as const const names = ['edge', 'chromium', 'webkit', 'chrome', 'firefox', 'safari'] as const const browsers = providers.map(provider => names.map(name => ({ name, provider }))).flat() -function runVitest(config: NonNullable & { shard?: any }, viteOverrides: ViteUserConfig = {}, runnerOptions?: VitestRunnerCLIOptions) { +function runVitest(config: NonNullable & { shard?: any }, viteOverrides: ViteUserConfig = {}, runnerOptions?: VitestRunnerCLIOptions) { return testUtils.runVitest({ root: './fixtures/test', include: ['example.test.ts'], ...config }, [], undefined, viteOverrides, runnerOptions) } diff --git a/test/config/test/get-state.test.ts b/test/config/test/get-state.test.ts index 0ed86f081..5be27c042 100644 --- a/test/config/test/get-state.test.ts +++ b/test/config/test/get-state.test.ts @@ -1,4 +1,4 @@ -import type { UserConfig } from 'vitest/node' +import type { TestUserConfig } from 'vitest/node' import { expect, test } from 'vitest' import { runVitest } from '../../test-utils' @@ -7,7 +7,7 @@ test.for([ { isolate: false, minWorkers: 1, maxWorkers: 1 }, { isolate: false, fileParallelism: false }, { isolate: false, poolOptions: { forks: { singleFork: true } } }, -] satisfies UserConfig[])(`getState().testPath during collection %s`, async (config) => { +] satisfies TestUserConfig[])(`getState().testPath during collection %s`, async (config) => { const result = await runVitest({ root: './fixtures/get-state', ...config, diff --git a/test/config/test/mixed-environments.test.ts b/test/config/test/mixed-environments.test.ts index 739241be4..061bc7b82 100644 --- a/test/config/test/mixed-environments.test.ts +++ b/test/config/test/mixed-environments.test.ts @@ -1,9 +1,9 @@ -import type { UserConfig } from 'vitest/node' +import type { TestUserConfig } from 'vitest/node' import { expect, test } from 'vitest' import { runVitest } from '../../test-utils' -const configs: UserConfig[] = [ +const configs: TestUserConfig[] = [ { pool: 'threads', poolOptions: { threads: { isolate: false, singleThread: true } } }, { pool: 'threads', poolOptions: { threads: { isolate: false, singleThread: false } } }, { pool: 'threads', poolOptions: { threads: { isolate: false, minThreads: 1, maxThreads: 1 } } }, diff --git a/test/config/test/override.test.ts b/test/config/test/override.test.ts index 19691dc00..9ec222547 100644 --- a/test/config/test/override.test.ts +++ b/test/config/test/override.test.ts @@ -1,18 +1,18 @@ import type { UserConfig as ViteUserConfig } from 'vite' -import type { UserConfig } from 'vitest/node' +import type { TestUserConfig } from 'vitest/node' import { describe, expect, it, onTestFinished } from 'vitest' import { extraInlineDeps } from 'vitest/config' import { createVitest, parseCLI } from 'vitest/node' type VitestOptions = Parameters[3] -async function vitest(cliOptions: UserConfig, configValue: UserConfig = {}, viteConfig: ViteUserConfig = {}, vitestOptions: VitestOptions = {}) { +async function vitest(cliOptions: TestUserConfig, configValue: TestUserConfig = {}, viteConfig: ViteUserConfig = {}, vitestOptions: VitestOptions = {}) { const vitest = await createVitest('test', { ...cliOptions, watch: false }, { ...viteConfig, test: configValue as any }, vitestOptions) onTestFinished(() => vitest.close()) return vitest } -async function config(cliOptions: UserConfig, configValue: UserConfig = {}, viteConfig: ViteUserConfig = {}, vitestOptions: VitestOptions = {}) { +async function config(cliOptions: TestUserConfig, configValue: TestUserConfig = {}, viteConfig: ViteUserConfig = {}, vitestOptions: VitestOptions = {}) { const v = await vitest(cliOptions, configValue, viteConfig, vitestOptions) return v.config } diff --git a/test/config/test/shard.test.ts b/test/config/test/shard.test.ts index 308a6e788..4f2a45a98 100644 --- a/test/config/test/shard.test.ts +++ b/test/config/test/shard.test.ts @@ -1,10 +1,10 @@ -import type { UserConfig } from 'vitest/node' +import type { TestUserConfig } from 'vitest/node' import { basename } from 'pathe' import { expect, test } from 'vitest' import * as testUtils from '../../test-utils' -function runVitest(config: UserConfig) { +function runVitest(config: TestUserConfig) { return testUtils.runVitest({ ...config, root: './fixtures/shard' }) } diff --git a/test/config/test/workers-option.test.ts b/test/config/test/workers-option.test.ts index 5e1215445..5b44cb4e6 100644 --- a/test/config/test/workers-option.test.ts +++ b/test/config/test/workers-option.test.ts @@ -1,4 +1,4 @@ -import type { UserConfig } from 'vitest/node' +import type { TestUserConfig } from 'vitest/node' import { describe, expect, test, vi } from 'vitest' import { getWorkersCountByPercentage } from 'vitest/src/utils/workers.js' @@ -26,7 +26,7 @@ describe('workers util', () => { }) }) -function runVitest(config: UserConfig) { +function runVitest(config: TestUserConfig) { return testUtils.runVitest({ ...config, root: './fixtures/workers-option' }) } diff --git a/test/core/test/exports.test.ts b/test/core/test/exports.test.ts index 1314e201e..1fe7d8e3c 100644 --- a/test/core/test/exports.test.ts +++ b/test/core/test/exports.test.ts @@ -88,13 +88,11 @@ it('exports snapshot', async ({ skip, task }) => { "./node": { "BaseSequencer": "function", "GitNotFoundError": "function", - "TestFile": "function", "TestsNotFoundError": "function", "VitestPackageInstaller": "function", "VitestPlugin": "function", "createDebugger": "function", "createMethodsRPC": "function", - "createServer": "function", "createViteLogger": "function", "createViteServer": "function", "createVitest": "function", @@ -243,13 +241,11 @@ it('exports snapshot', async ({ skip, task }) => { "./node": { "BaseSequencer": "function", "GitNotFoundError": "function", - "TestFile": "function", "TestsNotFoundError": "function", "VitestPackageInstaller": "function", "VitestPlugin": "function", "createDebugger": "function", "createMethodsRPC": "function", - "createServer": "function", "createViteLogger": "function", "createViteServer": "function", "createVitest": "function", diff --git a/test/coverage-test/utils.ts b/test/coverage-test/utils.ts index c35cd0bf9..a957ddc11 100644 --- a/test/coverage-test/utils.ts +++ b/test/coverage-test/utils.ts @@ -1,6 +1,6 @@ import type { CoverageSummary, FileCoverageData } from 'istanbul-lib-coverage' import type { TestFunction } from 'vitest' -import type { UserConfig } from 'vitest/node' +import type { TestUserConfig } from 'vitest/node' import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { fileURLToPath } from 'node:url' @@ -28,7 +28,7 @@ export function coverageTest(name: string, fn: TestFunction) { } } -export async function runVitest(config: UserConfig, options = { throwOnError: true }) { +export async function runVitest(config: TestUserConfig, options = { throwOnError: true }) { const provider = process.env.COVERAGE_PROVIDER as any const result = await testUtils.runVitest({ diff --git a/test/reporters/src/custom-reporter.ts b/test/reporters/src/custom-reporter.ts index 0ac841382..77e037a54 100644 --- a/test/reporters/src/custom-reporter.ts +++ b/test/reporters/src/custom-reporter.ts @@ -1,4 +1,4 @@ -import type { Reporter, Vitest } from 'vitest' +import type { Reporter, Vitest } from 'vitest/node' export default class TestReporter implements Reporter { ctx!: Vitest diff --git a/test/reporters/tests/test-run.test.ts b/test/reporters/tests/test-run.test.ts index f40f0dbc5..cafe8c33a 100644 --- a/test/reporters/tests/test-run.test.ts +++ b/test/reporters/tests/test-run.test.ts @@ -8,7 +8,7 @@ import type { TestRunEndReason, TestSpecification, TestSuite, - UserConfig, + TestUserConfig, Vitest, } from 'vitest/node' import { rmSync } from 'node:fs' @@ -1110,12 +1110,12 @@ interface ReporterOptions { async function run( structure: Parameters[0], - customConfig?: UserConfig, + customConfig?: TestUserConfig, reporterOptions?: ReporterOptions, ) { const reporter = new CustomReporter(reporterOptions) - const config: UserConfig = { + const config: TestUserConfig = { config: false, fileParallelism: false, globals: true, diff --git a/test/reporters/tests/utils.test.ts b/test/reporters/tests/utils.test.ts index 87c22f3bb..69061bde4 100644 --- a/test/reporters/tests/utils.test.ts +++ b/test/reporters/tests/utils.test.ts @@ -1,5 +1,5 @@ import type { ViteNodeRunner } from 'vite-node/client' -import type { Vitest } from 'vitest' +import type { Vitest } from 'vitest/node' /** * @format */ diff --git a/test/test-utils/index.ts b/test/test-utils/index.ts index fd339c348..951566109 100644 --- a/test/test-utils/index.ts +++ b/test/test-utils/index.ts @@ -2,7 +2,7 @@ import type { Options } from 'tinyexec' import type { UserConfig as ViteUserConfig } from 'vite' import type { WorkerGlobalState } from 'vitest' import type { TestProjectConfiguration } from 'vitest/config' -import type { TestModule, UserConfig, Vitest, VitestRunMode } from 'vitest/node' +import type { TestModule, TestUserConfig, Vitest, VitestRunMode } from 'vitest/node' import { webcrypto as crypto } from 'node:crypto' import fs from 'node:fs' import { Readable, Writable } from 'node:stream' @@ -29,7 +29,7 @@ export interface VitestRunnerCLIOptions { } export async function runVitest( - cliOptions: UserConfig, + cliOptions: TestUserConfig, cliFilters: string[] = [], mode: VitestRunMode = 'test', viteOverrides: ViteUserConfig = {}, @@ -342,7 +342,7 @@ export function useFS(root: string, structure: T) { export async function runInlineTests( structure: TestFsStructure, - config?: UserConfig, + config?: TestUserConfig, options?: VitestRunnerCLIOptions, viteOverrides: ViteUserConfig = {}, ) { diff --git a/test/typescript/failing/node-types.test-d.ts b/test/typescript/failing/node-types.test-d.ts new file mode 100644 index 000000000..e75e1400a --- /dev/null +++ b/test/typescript/failing/node-types.test-d.ts @@ -0,0 +1,5 @@ +import { test } from 'vitest' + +test('buffer is not available', () => { + Buffer.from([]) +}) diff --git a/test/typescript/test/__snapshots__/runner.test.ts.snap b/test/typescript/test/__snapshots__/runner.test.ts.snap index 266ad1763..7bcdf8500 100644 --- a/test/typescript/test/__snapshots__/runner.test.ts.snap +++ b/test/typescript/test/__snapshots__/runner.test.ts.snap @@ -2,6 +2,7 @@ exports[`should fail > typecheck files 1`] = ` "TypeCheckError: Type 'string' does not satisfy the constraint '"Expected string, Actual number"'. +TypeCheckError: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try \`npm i --save-dev @types/node\` and then add 'node' to the types field in your tsconfig. TypeCheckError: This expression is not callable. Type 'ExpectArray' has no call signatures. TypeCheckError: This expression is not callable. Type 'ExpectUndefined' has no call signatures. TypeCheckError: This expression is not callable. Type 'ExpectVoid' has no call signatures. @@ -77,6 +78,17 @@ TypeCheckError: This expression is not callable. Type 'ExpectArray' has `; exports[`should fail > typecheck files 8`] = ` +" FAIL node-types.test-d.ts > buffer is not available +TypeCheckError: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try \`npm i --save-dev @types/node\` and then add 'node' to the types field in your tsconfig. + ❯ node-types.test-d.ts:4:3 + 2| + 3| test('buffer is not available', () => { + 4| Buffer.from([]) + | ^ + 5| })" +`; + +exports[`should fail > typecheck files 9`] = ` " FAIL only.test-d.ts > failing test TypeCheckError: Type 'string' does not satisfy the constraint '"Expected string, Actual number"'. ❯ only.test-d.ts:4:33 diff --git a/test/typescript/tsconfig.fails.json b/test/typescript/tsconfig.fails.json index f912e9d7a..5fe8c7db5 100644 --- a/test/typescript/tsconfig.fails.json +++ b/test/typescript/tsconfig.fails.json @@ -1,5 +1,8 @@ { "extends": "../../tsconfig.build.json", + "compilerOptions": { + "types": [] + }, "include": [ "./failing/*" ], diff --git a/tsconfig.base.json b/tsconfig.base.json index a13f0f293..cd21f6657 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -24,17 +24,9 @@ "~/*": ["./packages/ui/client/*"], "vitest": ["./packages/vitest/src/public/index.ts"], "vitest/globals": ["./packages/vitest/globals.d.ts"], - "vitest/node": ["./packages/vitest/src/public/node.ts"], - "vitest/reporters": ["./packages/vitest/src/public/reporters.ts"], - "vitest/execute": ["./packages/vitest/src/public/execute.ts"], - "vitest/config": ["./packages/vitest/src/public/config.ts"], - "vitest/coverage": ["./packages/vitest/src/public/coverage.ts"], - "vitest/internal/browser": ["./packages/vitest/src/public/browser.ts"], - "vitest/runners": ["./packages/vitest/src/public/runners.ts"], + "vitest/*": ["./packages/vitest/src/public/*"], "vite-node": ["./packages/vite-node/src/index.ts"], - "vite-node/client": ["./packages/vite-node/src/client.ts"], - "vite-node/server": ["./packages/vite-node/src/server.ts"], - "vite-node/utils": ["./packages/vite-node/src/utils.ts"] + "vite-node/*": ["./packages/vite-node/src/*"] }, "strict": true, "declaration": true, diff --git a/tsconfig.build.json b/tsconfig.build.json index 4e6d50061..0fbf95be1 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -2,7 +2,8 @@ "extends": "./tsconfig.base.json", "compilerOptions": { "paths": { - "vitest": ["./packages/vitest/dist/index.d.ts"] + "vitest": ["./packages/vitest/dist/index.d.ts"], + "vitest/*": ["./packages/vitest/dist/*"] } } }