Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
2943ccf
feat(experimental): allow disabling the module runner
sheremet-va Dec 8, 2025
085be59
fix: throw an error in vmForks/vmThreads
sheremet-va Dec 8, 2025
c25402a
feat: implement nativeModuleRunner
sheremet-va Dec 8, 2025
318eb6b
chore: cleanup types
sheremet-va Dec 8, 2025
0611b57
fix: watcher respects non-client/ssr environments
sheremet-va Dec 8, 2025
3e4caa2
feat: support watch mode
sheremet-va Dec 8, 2025
4e5464b
fix: support module.register
sheremet-va Dec 8, 2025
3c40971
feat: support import.meta.vitest
sheremet-va Dec 8, 2025
c047490
chore: cli-config
sheremet-va Dec 8, 2025
b83f29c
chore: add sample project
sheremet-va Dec 9, 2025
3fd5618
chore: cleanup
sheremet-va Dec 9, 2025
e4b0d2e
chore: cleanup
sheremet-va Dec 9, 2025
fe86182
feat: support automock, autospy and redirect mock types
sheremet-va Dec 9, 2025
3f7e2b3
fix: show module as external in UI
sheremet-va Dec 9, 2025
2273518
fix: run setup file for every test, execute in-source tests as separa…
sheremet-va Dec 9, 2025
6c44609
feat: first implementation of factory mocking
sheremet-va Dec 10, 2025
4091d0d
chore: collect
sheremet-va Dec 12, 2025
0926f28
chore: refactor native module mocker
sheremet-va Dec 12, 2025
f76caa0
refactor: cleanup exports collection
sheremet-va Dec 12, 2025
d6f72bd
fix: support importActual and recursive factory
sheremet-va Dec 12, 2025
086c47c
fix: support vi.importMock
sheremet-va Dec 12, 2025
06a351e
fix: support mocking deps
sheremet-va Dec 12, 2025
8b4f29b
fix(mocker): support top level import if dependency is not circular
sheremet-va Dec 15, 2025
f50aa81
fix: allow `export *` when automocking
sheremet-va Dec 15, 2025
a4e603e
test: add more tests
sheremet-va Dec 15, 2025
d458c67
fix: update loading errors
sheremet-va Dec 15, 2025
34f1bb3
Merge branch 'main' of github.com:vitest-dev/vitest into 12-08-feat_e…
sheremet-va Dec 15, 2025
d3db1bf
chore: cleanup
sheremet-va Dec 15, 2025
b653ee3
chore: cleanup
sheremet-va Dec 15, 2025
0ab2dab
fix: override is false by default
sheremet-va Dec 16, 2025
69ca0d8
chore: cleanup
sheremet-va Dec 16, 2025
4786dd1
refactor: move the example to test/
sheremet-va Dec 16, 2025
5bb68aa
docs: cleanup
sheremet-va Dec 16, 2025
74a84c4
chore: add try/catch
sheremet-va Dec 17, 2025
c81d363
Merge branch 'main' of github.com:vitest-dev/vitest into 12-08-feat_e…
sheremet-va Dec 17, 2025
f7def15
fix: listen for unhandled errors in vm pool
sheremet-va Dec 17, 2025
3f96c63
fix(windows): support circular manual mock
sheremet-va Dec 17, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 130 additions & 7 deletions docs/config/experimental.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ outline: deep
## experimental.fsModuleCache <Version type="experimental">4.0.11</Version> {#experimental-fsmodulecache}

::: tip FEEDBACK
Please, leave feedback regarding this feature in a [GitHub Discussion](https://github.com/vitest-dev/vitest/discussions/9221).
Please leave feedback regarding this feature in a [GitHub Discussion](https://github.com/vitest-dev/vitest/discussions/9221).
:::

- **Type:** `boolean`
Expand All @@ -30,9 +30,9 @@ DEBUG=vitest:cache:fs vitest --experimental.fsModuleCache

### Known Issues

Vitest creates persistent file hash based on file content, its id, vite's environment configuration and coverage status. Vitest tries to use as much information it has about the configuration, but it is still incomplete. At the moment, it is not possible to track your plugin options because there is no standard interface for it.
Vitest creates a persistent file hash based on file content, its id, Vite's environment configuration and coverage status. Vitest tries to use as much information as it has about the configuration, but it is still incomplete. At the moment, it is not possible to track your plugin options because there is no standard interface for it.

If you have a plugin that relies on things outside the file content or the public configuration (like reading another file or a folder), it's possible that the cache will get stale. To workaround that, you can define a [cache key generator](/api/advanced/plugin#definecachekeygenerator) to specify dynamic option or to opt-out of caching for that module:
If you have a plugin that relies on things outside the file content or the public configuration (like reading another file or a folder), it's possible that the cache will get stale. To work around that, you can define a [cache key generator](/api/advanced/plugin#definecachekeygenerator) to specify a dynamic option or to opt out of caching for that module:

```js [vitest.config.js]
import { defineConfig } from 'vitest/config'
Expand Down Expand Up @@ -66,7 +66,7 @@ export default defineConfig({

If you are a plugin author, consider defining a [cache key generator](/api/advanced/plugin#definecachekeygenerator) in your plugin if it can be registered with different options that affect the transform result.

On the other hand, if your plugin should not affect the cache key, you can opt-out by setting `api.vitest.experimental.ignoreFsModuleCache` to `true`:
On the other hand, if your plugin should not affect the cache key, you can opt out by setting `api.vitest.experimental.ignoreFsModuleCache` to `true`:

```js [vitest.config.js]
import { defineConfig } from 'vitest/config'
Expand All @@ -92,7 +92,7 @@ export default defineConfig({
})
```

Note that you can still define the cache key generator even the plugin opt-out of module caching.
Note that you can still define the cache key generator even if the plugin opts out of module caching.

## experimental.fsModuleCachePath <Version type="experimental">4.0.11</Version> {#experimental-fsmodulecachepath}

Expand All @@ -108,7 +108,7 @@ At the moment, Vitest ignores the [test.cache.dir](/config/cache) or [cacheDir](
## experimental.openTelemetry <Version type="experimental">4.0.11</Version> {#experimental-opentelemetry}

::: tip FEEDBACK
Please, leave feedback regarding this feature in a [GitHub Discussion](https://github.com/vitest-dev/vitest/discussions/9222).
Please leave feedback regarding this feature in a [GitHub Discussion](https://github.com/vitest-dev/vitest/discussions/9222).
:::

- **Type:**
Expand Down Expand Up @@ -177,7 +177,7 @@ It's important that Node can process `sdkPath` content because it is not transfo
## experimental.printImportBreakdown <Version type="experimental">4.0.15</Version> {#experimental-printimportbreakdown}

::: tip FEEDBACK
Please, leave feedback regarding this feature in a [GitHub Discussion](https://github.com/vitest-dev/vitest/discussions/9224).
Please leave feedback regarding this feature in a [GitHub Discussion](https://github.com/vitest-dev/vitest/discussions/9224).
:::

- **Type:** `boolean`
Expand All @@ -195,3 +195,126 @@ Note that if the file path is too long, Vitest will truncate it at the start unt
::: info
[Vitest UI](/guide/ui#import-breakdown) shows a breakdown of imports automatically if at least one file took longer than 500 milliseconds to load. You can manually set this option to `false` to disable this.
:::

## experimental.viteModuleRunner <Version type="experimental">4.0.16</Version> {#experimental-vitemodulerunner}

- **Type:** `boolean`
- **Default:** `true`

Controls whether Vitest uses Vite's [module runner](https://vite.dev/guide/api-environment-runtimes#modulerunner) to run the code or fallback to the native `import`.

If this option is defined in the root config, all [projects](/guide/projects) will inherit it automatically.

We recommend disabling the module runner if you are running tests in the same environment as your code (server backend or simple scripts, for example). However, we still recommend running `jsdom`/`happy-dom` tests with the module runner or in [the browser](/guide/browser/) since it doesn't require any additional configuration.

Disabling this flag will disable _all_ file transforms:

- test files and your source code are not processed by Vite
- your global setup files are not processed
- your custom runner/pool/environment files are not processed
- your config file is still processed by Vite (this happens before Vitest knows the `viteModuleRunner` flag)

::: warning
At the moment, Vitest still requires Vite for certain functionality like the module graph or watch mode.
:::

### Module Runner

By default, Vitest runs tests in a very permissive module runner sandbox powered by Vite's [Environment API](https://vite.dev/guide/api-environment.html#environment-api). Every file is categorized as either an "inline" module or an "external" module.

Module runner runs all "inline" modules. It provides `import.meta.env`, `require`, `__dirname`, `__filename`, static `import`, and has its own module resolution mechanism. This makes it very easy to run code when you don't want to configure the environment and just need to test that the bare JavaScript logic you wrote works as intended.

All "external" modules run in native mode, meaning they are executed outside of the module runner sandbox. If you are running tests in Node.js, these files are imported with the native `import` keyword and processed by Node.js directly.

While running JSDOM/happy-dom tests in a permissive fake environment might be justified, running Node.js tests in a non-Node.js environment is counter-productive as it can hide and silence potential errors you may encounter in production, especially if your code doesn't require any additional transformations provided by Vite plugins.

### Known Limitations

Some Vitest features rely on files being transformed. Vitest uses synchronous [Node.js Loaders API](https://nodejs.org/api/module.html#customization-hooks) to transform test files and setup files to support these features:

- [`import.meta.vitest`](/guide/in-source)
- [`vi.mock`](/api/vi#vi-mock)
- [`vi.hoisted`](/api/vi#vi-hoisted)

::: warning
This means that Vitest requires at least Node 22.15 for those features to work. At the moment, they also do not work in Deno or Bun.
:::

This could affect performance because Vitest needs to read the file and process it. If you do not use these features, you can disable the transforms by setting `experimental.nodeLoader` to `false`. Vitest only reads test files and setup files while looking for `vi.mock` or `vi.hoisted`. Using these in other files won't hoist them to the top of the file and can lead to unexpected behavior.

Some features will not work due to the nature of `viteModuleRunner`, including:

- no `import.meta.env`: `import.meta.env` is a Vite feature, use `process.env` instead
- no `plugins`: plugins are not applied because there is no transformation phase
- no `alias`: aliases are not applied because there is no transformation phase

With regards to mocking, it is also important to point out that ES modules do not support property override. This means that code like this won't work anymore:

```ts
import * as module from './some-module.js'
import { vi } from 'vitest'

vi.spyOn(module, 'function').mockImplementation(() => 42)
```

However, Vitest supports auto-spying on modules without overriding their implementation. When `vi.mock` is called with a `spy: true` argument, the module is mocked in a way that preserves original implementations, but all exported functions are wrapped in a `vi.fn()` spy:

```ts
import * as module from './some-module.js'
import { vi } from 'vitest'

vi.mock('./some-module.js', { spy: true })

module.function.mockImplementation(() => 42)
```

### TypeScript

If you are using Node.js 22.18/23.6 or higher, TypeScript will be [transformed natively](https://nodejs.org/en/learn/typescript/run-natively) by Node.js.

::: warning TypeScript with Node.js 22.6-22.18
If you are using Node.js version between 22.6 and 22.18, you can also enable native TypeScript support via `--experimental-strip-types` flag:

```shell
NODE_OPTIONS="--experimental-strip-types" vitest
```

Note that Node.js will print an experimental warning for every test file; you can silence the warning by providing `--no-warnings` flag:

```shell
NODE_OPTIONS="--experimental-strip-types --no-warnings" vitest
```
:::

If you are using TypeScript and Node.js version lower than 22.6, then you will need to either:

- build your test files and source code and run those files directly
- import a [custom loader](https://nodejs.org/api/module.html#customization-hooks) via `execArgv` flag

```ts
import { defineConfig } from 'vitest/config'

const tsxApi = import.meta.resolve('tsx/esm/api')

export default defineConfig({
test: {
execArgv: [
`--import=data:text/javascript,import * as tsx from "${tsxApi}";tsx.register()`,
],
experimental: {
viteModuleRunner: false,
},
},
})
```

If you are running tests in Deno, TypeScript files are processed by the runtime without any additional configurations.

## experimental.nodeLoader <Version type="experimental">4.0.16</Version> {#experimental-nodeloader}

- **Type:** `boolean`
- **Default:** `true`

If module runner is disabled, Vitest uses a module loader to transform files to support `import.meta.vitest`, `vi.mock` and `vi.hoisted`.

If you don't use these features, you can disable this.
8 changes: 7 additions & 1 deletion packages/mocker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@
"types": "./dist/register.d.ts",
"default": "./dist/register.js"
},
"./*": "./*"
"./transforms": {
"types": "./dist/transforms.d.ts",
"default": "./dist/transforms.js"
},
"./package.json": "./package.json"
},
"main": "./dist/index.js",
"module": "./dist/index.js",
Expand Down Expand Up @@ -79,6 +83,8 @@
"@vitest/spy": "workspace:*",
"@vitest/utils": "workspace:*",
"acorn-walk": "catalog:",
"cjs-module-lexer": "^2.1.1",
"es-module-lexer": "^2.0.0",
"msw": "catalog:",
"pathe": "catalog:",
"vite": "^6.3.5"
Expand Down
1 change: 1 addition & 0 deletions packages/mocker/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const entries = {
'browser': 'src/browser/index.ts',
'register': 'src/browser/register.ts',
'auto-register': 'src/browser/auto-register.ts',
'transforms': 'src/node/transforms.ts',
}

const external = [
Expand Down
60 changes: 43 additions & 17 deletions packages/mocker/src/browser/mocker.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import type { CreateMockInstanceProcedure } from '../automocker'
import type { MockedModule, MockedModuleType } from '../registry'
import type { ModuleMockOptions } from '../types'
import type { ModuleMockContext, ModuleMockOptions, TestModuleMocker } from '../types'
import type { ModuleMockerInterceptor } from './interceptor'
import { extname, join } from 'pathe'
import { mockObject } from '../automocker'
import { AutomockedModule, MockerRegistry, RedirectedModule } from '../registry'

const { now } = Date

export class ModuleMocker {
export class ModuleMocker implements TestModuleMocker {
protected registry: MockerRegistry = new MockerRegistry()

private queue = new Set<Promise<void>>()
Expand Down Expand Up @@ -66,7 +66,7 @@ export class ModuleMocker {
)
}
const ext = extname(resolved.id)
const url = new URL(resolved.url, location.href)
const url = new URL(resolved.url, this.getBaseUrl())
const query = `_vitest_original&ext${ext}`
const actualUrl = `${url.pathname}${
url.search ? `${url.search}&${query}` : `?${query}`
Expand All @@ -81,6 +81,10 @@ export class ModuleMocker {
})
}

protected getBaseUrl(): string {
return location.href
}

public async importMock<T>(rawId: string, importer: string): Promise<T> {
await this.prepare()
const { resolvedId, resolvedUrl, redirectUrl } = await this.rpc.resolveMock(
Expand All @@ -94,7 +98,7 @@ export class ModuleMocker {

if (!mock) {
if (redirectUrl) {
const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString()
const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), this.getBaseUrl()).toString()
mock = new RedirectedModule(rawId, resolvedId, mockUrl, resolvedRedirect)
}
else {
Expand All @@ -107,30 +111,42 @@ export class ModuleMocker {
}

if (mock.type === 'automock' || mock.type === 'autospy') {
const url = new URL(`/@id/${resolvedId}`, location.href)
const url = new URL(`/@id/${resolvedId}`, this.getBaseUrl())
const query = url.search ? `${url.search}&t=${now()}` : `?t=${now()}`
const moduleObject = await import(/* @vite-ignore */ `${url.pathname}${query}&mock=${mock.type}${url.hash}`)
return this.mockObject(moduleObject, mock.type) as T
return this.mockObject(moduleObject, undefined, mock.type) as T
}

return import(/* @vite-ignore */ mock.redirect)
}

public mockObject(
object: Record<string | symbol, any>,
mockExports: Record<string | symbol, any> | undefined,
moduleType: 'automock' | 'autospy' = 'automock',
): Record<string | symbol, any> {
return mockObject({
globalConstructors: {
Object,
Function,
Array,
Map,
RegExp,
const result = mockObject(
{
globalConstructors: {
Object,
Function,
Array,
Map,
RegExp,
},
createMockInstance: this.createMockInstance,
type: moduleType,
},
createMockInstance: this.createMockInstance,
type: moduleType,
}, object)
object,
mockExports,
)
return result
}

public getMockContext(): ModuleMockContext {
return {
callstack: null,
}
}

public queueMock(rawId: string, importer: string, factoryOrOptions?: ModuleMockOptions | (() => any)): void {
Expand All @@ -153,7 +169,7 @@ export class ModuleMocker {
: undefined

const mockRedirect = typeof redirectUrl === 'string'
? new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString()
? new URL(this.resolveMockPath(cleanVersion(redirectUrl)), this.getBaseUrl()).toString()
: null

let module: MockedModule
Expand Down Expand Up @@ -211,6 +227,16 @@ export class ModuleMocker {
return moduleFactory
}

public getMockedModuleById(id: string): MockedModule | undefined {
return this.registry.getById(id)
}

public reset(): void {
this.registry.clear()
this.mockedIds.clear()
this.queue.clear()
}

private resolveMockPath(path: string) {
const config = this.config
const fsRoot = join('/@fs/', config.root)
Expand Down
2 changes: 2 additions & 0 deletions packages/mocker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ export type {
} from './registry'

export type {
ModuleMockContext,
ModuleMockFactory,
ModuleMockFactoryWithHelper,
ModuleMockOptions,
ServerIdResolution,
ServerMockResolution,
TestModuleMocker,
} from './types'
Loading
Loading