Vitest
Vitest instance requires the current test mode. It can be either:
testwhen running runtime testsbenchmarkwhen running benchmarks experimental
New in Vitest 4
Vitest 4 added several new APIs (they are marked with a "4.0.0+" badge) and removed deprecated APIs:
invalidateschangedTests(useonFilterWatchedSpecificationinstead)server(useviteinstead)getProjectsByTestFile(usegetModuleSpecificationsinstead)getFileWorkspaceSpecs(usegetModuleSpecificationsinstead)getModuleProjects(filter bythis.projectsyourself)updateLastChanged(renamed toinvalidateFile)globTestSpecs(useglobTestSpecificationsinstead)globTestFiles(useglobTestSpecificationsinstead)listFile(usegetRelevantTestSpecificationsinstead)
mode
test
Test mode will only call functions inside test or it, and throws an error when bench is encountered. This mode uses include and exclude options in the config to find test files.
benchmark experimental
Benchmark mode calls bench functions and throws an error, when it encounters test or it. This mode uses benchmark.include and benchmark.exclude options in the config to find benchmark files.
config
The root (or global) config. If projects are defined, they will reference this as globalConfig.
WARNING
This is Vitest config, it doesn't extend Vite config. It only has resolved values from the test property.
vite
This is a global ViteDevServer.
state experimental
WARNING
Public state is an experimental API (except vitest.state.getReportedEntity). Breaking changes might not follow SemVer, please pin Vitest's version when using it.
Global state stores information about the current tests. It uses the same API from @vitest/runner by default, but we recommend using the Reported Tasks API instead by calling state.getReportedEntity() on the @vitest/runner API:
const task = vitest.state.idMap.get(taskId) // old API
const testCase = vitest.state.getReportedEntity(task) // new APIIn the future, the old API won't be exposed anymore.
snapshot
The global snapshot manager. Vitest keeps track of all snapshots using the snapshot.add method.
You can get the latest summary of snapshots via the vitest.snapshot.summary property.
cache
Cache manager that stores information about latest test results and test file stats. In Vitest itself this is only used by the default sequencer to sort tests.
watcher 4.0.0+
The instance of a Vitest watcher with useful methods to track file changes and rerun tests. You can use onFileChange, onFileDelete or onFileCreate with your own watcher, if the built-in watcher is disabled.
projects
An array of test projects that belong to user's projects. If the user did not specify a them, this array will only contain a root project.
Vitest will ensure that there is always at least one project in this array. If the user specifies a non-existent --project name, Vitest will throw an error before this array is defined.
getRootProject
function getRootProject(): TestProjectThis returns the root test project. The root project generally doesn't run any tests and is not included in vitest.projects unless the user explicitly includes the root config in their configuration, or projects are not defined at all.
The primary goal of the root project is to setup the global config. In fact, rootProject.config references rootProject.globalConfig and vitest.config directly:
rootProject.config === rootProject.globalConfig === rootProject.vitest.configprovide
function provide<T extends keyof ProvidedContext & string>(
key: T,
value: ProvidedContext[T],
): voidVitest exposes provide method which is a shorthand for vitest.getRootProject().provide. With this method you can pass down values from the main thread to tests. All values are checked with structuredClone before they are stored, but the values themselves are not cloned.
To receive the values in the test, you need to import inject method from vitest entrypoint:
import { inject } from 'vitest'
const port = inject('wsPort') // 3000For better type safety, we encourage you to augment the type of ProvidedContext:
import { createVitest } from 'vitest/node'
const vitest = await createVitest('test', {
watch: false,
})
vitest.provide('wsPort', 3000)
declare module 'vitest' {
export interface ProvidedContext {
wsPort: number
}
}WARNING
Technically, provide is a method of TestProject, so it is limited to the specific project. However, all projects inherit the values from the root project which makes vitest.provide universal way of passing down values to tests.
getProvidedContext
function getProvidedContext(): ProvidedContextThis returns the root context object. This is a shorthand for vitest.getRootProject().getProvidedContext.
getProjectByName
function getProjectByName(name: string): TestProjectThis method returns the project by its name. Similar to calling vitest.projects.find.
WARNING
In case the project doesn't exist, this method will return the root project - make sure to check the names again if the project you are looking for is the one returned.
If user didn't customize a name, the Vitest will assign an empty string as a name.
globTestSpecifications
function globTestSpecifications(
filters?: string[],
): Promise<TestSpecification[]>This method constructs new test specifications by collecting every test in all projects with project.globTestFiles. It accepts string filters to match the test files - these are the same filters that CLI supports.
This method automatically caches all test specifications. When you call getModuleSpecifications next time, it will return the same specifications unless clearSpecificationsCache was called before that.
WARNING
As of Vitest 3, it's possible to have multiple test specifications with the same module ID (file path) if poolMatchGlob has several pools or if typecheck is enabled. This possibility will be removed in Vitest 4.
const specifications = await vitest.globTestSpecifications(['my-filter'])
// [TestSpecification{ moduleId: '/tests/my-filter.test.ts' }]
console.log(specifications)getRelevantTestSpecifications
function getRelevantTestSpecifications(
filters?: string[]
): Promise<TestSpecification[]>This method resolves every test specification by calling project.globTestFiles. It accepts string filters to match the test files - these are the same filters that CLI supports. If --changed flag was specified, the list will be filtered to include only files that changed. getRelevantTestSpecifications doesn't run any test files.
WARNING
This method can be slow because it needs to filter --changed flags. Do not use it if you just need a list of test files.
- If you need to get the list of specifications for known test files, use
getModuleSpecificationsinstead. - If you need to get the list of all possible test files, use
globTestSpecifications.
mergeReports
function mergeReports(directory?: string): Promise<TestRunResult>Merge reports from multiple runs located in the specified directory (value from --merge-reports if not specified). This value can also be set on config.mergeReports (by default, it will read .vitest-reports folder).
Note that the directory will always be resolved relative to the working directory.
This method is called automatically by startVitest if config.mergeReports is set.
collect
function collect(filters?: string[]): Promise<TestRunResult>Execute test files without running test callbacks. collect returns unhandled errors and an array of test modules. It accepts string filters to match the test files - these are the same filters that CLI supports.
This method resolves tests specifications based on the config include, exclude, and includeSource values. Read more at project.globTestFiles. If --changed flag was specified, the list will be filtered to include only files that changed.
WARNING
Note that Vitest doesn't use static analysis to collect tests. Vitest will run every test file in isolation, just like it runs regular tests.
This makes this method very slow, unless you disable isolation before collecting tests.
start
function start(filters?: string[]): Promise<TestRunResult>Initialize reporters, the coverage provider, and run tests. This method accepts string filters to match the test files - these are the same filters that CLI supports.
WARNING
This method should not be called if vitest.init() is also invoked. Use runTestSpecifications or rerunTestSpecifications instead if you need to run tests after Vitest was initialised.
This method is called automatically by startVitest if config.mergeReports and config.standalone are not set.
init
function init(): Promise<void>Initialize reporters and the coverage provider. This method doesn't run any tests. If the --watch flag is provided, Vitest will still run changed tests even if this method was not called.
Internally, this method is called only if --standalone flag is enabled.
WARNING
This method should not be called if vitest.start() is also invoked.
This method is called automatically by startVitest if config.standalone is set.
getModuleSpecifications
function getModuleSpecifications(moduleId: string): TestSpecification[]Returns a list of test specifications related to the module ID. The ID should already be resolved to an absolute file path. If ID doesn't match include or includeSource patterns, the returned array will be empty.
This method can return already cached specifications based on the moduleId and pool. But note that project.createSpecification always returns a new instance and it's not cached automatically. However, specifications are automatically cached when runTestSpecifications is called.
WARNING
As of Vitest 3, this method uses a cache to check if the file is a test. To make sure that the cache is not empty, call globTestSpecifications at least once.
clearSpecificationsCache
function clearSpecificationsCache(moduleId?: string): voidVitest automatically caches test specifications for each file when globTestSpecifications or runTestSpecifications is called. This method clears the cache for the given file or the whole cache altogether depending on the first argument.
runTestSpecifications
function runTestSpecifications(
specifications: TestSpecification[],
allTestsRun = false
): Promise<TestRunResult>This method runs every test based on the received specifications. The second argument, allTestsRun, is used by the coverage provider to determine if it needs to include uncovered files in report.
WARNING
This method doesn't trigger onWatcherRerun, onWatcherStart and onTestsRerun callbacks. If you are rerunning tests based on the file change, consider using rerunTestSpecifications instead.
rerunTestSpecifications
function rerunTestSpecifications(
specifications: TestSpecification[],
allTestsRun = false
): Promise<TestRunResult>This method emits reporter.onWatcherRerun and onTestsRerun events, then it runs tests with runTestSpecifications. If there were no errors in the main process, it will emit reporter.onWatcherStart event.
updateSnapshot
function updateSnapshot(files?: string[]): Promise<TestRunResult>Update snapshots in specified files. If no files are provided, it will update files with failed tests and obsolete snapshots.
collectTests
function collectTests(
specifications: TestSpecification[]
): Promise<TestRunResult>Execute test files without running test callbacks. collectTests returns unhandled errors and an array of test modules.
This method works exactly the same as collect, but you need to provide test specifications yourself.
WARNING
Note that Vitest doesn't use static analysis to collect tests. Vitest will run every test file in isolation, just like it runs regular tests.
This makes this method very slow, unless you disable isolation before collecting tests.
cancelCurrentRun
function cancelCurrentRun(reason: CancelReason): Promise<void>This method will gracefully cancel all ongoing tests. It will wait for started tests to finish running and will not run tests that were scheduled to run but haven't started yet.
setGlobalTestNamePattern
function setGlobalTestNamePattern(pattern: string | RegExp): voidThis methods overrides the global test name pattern.
WARNING
This method doesn't start running any tests. To run tests with updated pattern, call runTestSpecifications.
getGlobalTestNamePattern 4.0.0+
function getGlobalTestNamePattern(): RegExp | undefinedReturns the regexp used for the global test name pattern.
resetGlobalTestNamePattern
function resetGlobalTestNamePattern(): voidThis methods resets the test name pattern. It means Vitest won't skip any tests now.
WARNING
This method doesn't start running any tests. To run tests without a pattern, call runTestSpecifications.
enableSnapshotUpdate
function enableSnapshotUpdate(): voidEnable the mode that allows updating snapshots when running tests. Every test that runs after this method is called will update snapshots. To disable the mode, call resetSnapshotUpdate.
WARNING
This method doesn't start running any tests. To update snapshots, run tests with runTestSpecifications.
resetSnapshotUpdate
function resetSnapshotUpdate(): voidDisable the mode that allows updating snapshots when running tests. This method doesn't start running any tests.
invalidateFile
function invalidateFile(filepath: string): voidThis method invalidates the file in the cache of every project. It is mostly useful if you rely on your own watcher because Vite's cache persist in memory.
DANGER
If you disable Vitest's watcher but keep Vitest running, it is important to manually clear the cache with this method because there is no way to disable the cache. This method will also invalidate file's importers.
import
function import<T>(moduleId: string): Promise<T>Import a file using Vite module runner. The file will be transformed by Vite with the global config and executed in a separate context. Note that moduleId will be relative to the config.root.
DANGER
project.import reuses Vite's module graph, so importing the same module using a regular import will return a different module:
import * as staticExample from './example.js'
const dynamicExample = await vitest.import('./example.js')
dynamicExample !== staticExample // ✅INFO
Internally, Vitest uses this method to import global setups, custom coverage providers, and custom reporters, meaning all of them share the same module graph as long as they belong to the same Vite server.
close
function close(): Promise<void>Closes all projects and their associated resources. This can only be called once; the closing promise is cached until the server restarts.
exit
function exit(force = false): Promise<void>Closes all projects and exit the process. If force is set to true, the process will exit immediately after closing the projects.
This method will also forcefully call process.exit() if the process is still active after config.teardownTimeout milliseconds.
shouldKeepServer
function shouldKeepServer(): booleanThis method will return true if the server should be kept running after the tests are done. This usually means that the watch mode was enabled.
onServerRestart
function onServerRestart(fn: OnServerRestartHandler): voidRegister a handler that will be called when the server is restarted due to a config change.
onCancel
function onCancel(fn: (reason: CancelReason) => Awaitable<void>): voidRegister a handler that will be called when the test run is cancelled with vitest.cancelCurrentRun.
onClose
function onClose(fn: () => Awaitable<void>): voidRegister a handler that will be called when the server is closed.
onTestsRerun
function onTestsRerun(fn: OnTestsRerunHandler): voidRegister a handler that will be called when the tests are rerunning. The tests can rerun when rerunTestSpecifications is called manually or when a file is changed and the built-in watcher schedules a rerun.
onFilterWatchedSpecification
function onFilterWatchedSpecification(
fn: (specification: TestSpecification) => boolean
): voidRegister a handler that will be called when a file is changed. This callback should return true or false, indicating whether the test file needs to be rerun.
With this method, you can hook into the default watcher logic to delay or discard tests that the user doesn't want to keep track of at the moment:
const continuesTests: string[] = []
myCustomWrapper.onContinuesRunEnabled(testItem =>
continuesTests.push(item.fsPath)
)
vitest.onFilterWatchedSpecification(specification =>
continuesTests.includes(specification.moduleId)
)Vitest can create different specifications for the same file depending on the pool or locations options, so do not rely on the reference. Vitest can also return cached specification from vitest.getModuleSpecifications - the cache is based on the moduleId and pool. Note that project.createSpecification always returns a new instance.
matchesProjectFilter 3.1.0+
function matchesProjectFilter(name: string): booleanCheck if the name matches the current project filter. If there is no project filter, this will always return true.
It is not possible to programmatically change the --project CLI option.
waitForTestRunEnd 4.0.0+
function waitForTestRunEnd(): Promise<void>If there is a test run happening, returns a promise that will resolve when the test run is finished.
createCoverageProvider 4.0.0+
function createCoverageProvider(): Promise<CoverageProvider | null>Creates a coverage provider if coverage is enabled in the config. This is done automatically if you are running tests with start or init methods.
WARNING
This method will also clean all previous reports if coverage.clean is not set to false.
enableCoverage 4.0.0+
function enableCoverage(): Promise<void>This method enables coverage for tests that run after this call. enableCoverage doesn't run any tests; it only sets up Vitest to collect coverage.
It creates a new coverage provider if one doesn't already exist.
disableCoverage 4.0.0+
function disableCoverage(): voidThis method disables coverage collection for tests that run afterwards.
getSeed 4.0.0+
function getSeed(): number | nullReturns the seed, if tests are running in a random order.
experimental_parseSpecification 4.0.0+ experimental
function experimental_parseSpecification(
specification: TestSpecification
): Promise<TestModule>This function will collect all tests inside the file without running it. It uses rollup's parseAst function on top of Vite's ssrTransform to statically analyse the file and collect all tests that it can.
WARNING
If Vitest could not analyse the name of the test, it will inject a dynamic: true property to the test or a suite. The id will also have a postfix with -dynamic to not break tests that were collected properly.
Vitest always injects this property in tests with for or each modifier or tests with a dynamic name (like, hello ${property} or 'hello' + ${property}). Vitest will still assign a name to the test, but it cannot be used to filter tests.
There is nothing Vitest can do to make it possible to filter dynamic tests, but you can turn a test with for or each modifier into a name pattern with escapeTestName function:
import { escapeTestName } from 'vitest/node'
// turns into /hello, .+?/
const escapedPattern = new RegExp(escapeTestName('hello, %s', true))WARNING
Vitest will only collect tests defined in the file. It will never follow imports to other files.
Vitest collects all it, test, suite and describe definitions even if they were not imported from the vitest entry point.
experimental_parseSpecifications 4.0.0+ experimental
function experimental_parseSpecifications(
specifications: TestSpecification[],
options?: {
concurrency?: number
}
): Promise<TestModule[]>This method will collect tests from an array of specifications. By default, Vitest will run only os.availableParallelism() number of specifications at a time to reduce the potential performance degradation. You can specify a different number in a second argument.