Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

64 Commits

Folders and files

Repository files navigation

@cldmv/vitest-runner

@cldmv/vitest-runner is a sequential Vitest runner that spawns each test file in its own child process, so a large test suite never has to fit in one Vitest process's memory. It runs files one at a time or in a parallel worker pool, gives heavy files their own heap ceiling or a solo slot, and prints one combined summary of results, memory use and duration at the end.

Coverage stays out-of-memory-safe too: each file writes a coverage blob, and a single vitest --mergeReports step combines them into one report, with a worst-coverage table after it. The runner auto-detects your Vitest config, forwards every standard Vitest flag unchanged, and works as a vitest-runner CLI or as a programmatic run() API from ESM and CommonJS.

Big suites, small processes: every test file gets its own Vitest, and the results come back as one run.

npm version npm downloads GitHub downloads Last commit npm last update Coverage

Contributors Sponsor shinrai


✨ What's New

Latest: v1.11.5 (November 2026)

  • CJS shim synced with the package-layout template β€” src/index.cjs now matches the CLDMV/.github template: when the ESM entry exports a single value, require() returns it with default and every export name attached. vitest-runner exports many values, so require("@cldmv/vitest-runner") returns the same module object as before (#175).
  • View full v1.11.5 Changelog

Recent Releases

  • v1.11.4 (November 2026) β€” @cldmv/lib-process 0.1.1 frees a lock the moment release() returns; dev tools bumped, behaviour unchanged (Changelog)
  • v1.11.3 (November 2026) β€” dist/index.cjs is the generic CLDMV CommonJS shim; require() unchanged (Changelog)
  • v1.11.2 (November 2026) β€” ci.yml cancels superseded runs on next and hotfixes (the CLDMV/.github v4.46.0 concurrency block); no runtime changes (Changelog)
  • v1.11.1 (November 2026) β€” Coverage runs report test progress to the idle watchdog, so long coverage files aren't killed as idle; dist/ ships one file per module and the CLI moves to dist/bin/ (Changelog)

πŸ“š For complete release notes, see the docs/changelog/ folder.


πŸš€ Key Features

  • Runs every test file in its own child process, one at a time or in a configurable parallel worker pool
  • Solo slots for heavy files (--solo-pattern) and per-file heap ceilings (perFileHeapOverrides)
  • A per-file watchdog: a file that hangs is killed with its whole process group and reported as failed, and the run carries on
  • Full coverage mode via blob-per-file + --mergeReports (no OOM), with a worst-coverage table
  • Auto-detects your vitest config; accepts an explicit path if needed
  • All standard Vitest CLI flags are forwarded unchanged
  • Usable as a CLI binary or as a programmatic Node.js API, with an optional JSON run report
  • A per-run scratch directory for every test file (VITEST_RUNNER_TMP / makeRunTmpDir), cleaned up on exit
  • ES module build with a thin CommonJS entry for require()

πŸ“¦ Installation

Requirements

  • Node.js 22.0.0 or later (engines.node is >=22.0.0, set by the chalk 6 dependency). The package is an ES module and loads with import. The Vitest version you install has its own Node.js floor. Node.js 20 is not supported from v1.5.3; stay on v1.5.1 there.
  • require("@cldmv/vitest-runner") loads the ES module build synchronously, which needs Node.js >=22.13.0; on older Node.js, use import() instead.
  • Developing this package needs Node.js 22.22.0 or later (devEngines).
  • vitest β‰₯ 1.0 (peer dependency, installed in your project)
  • chalk (a dependency, installed with the package)

Install

npm install --save-dev @cldmv/vitest-runner

Or to use the CLI globally:

npm install -g @cldmv/vitest-runner

πŸš€ Quick Start

Run every discovered *.test.vitest.{js,mjs,cjs} file, each in its own process:

npx vitest-runner

Run with OOM-safe coverage and a live progress bar:

npx vitest-runner --coverage-quiet

From code:

import { run } from "@cldmv/vitest-runner";

const code = await run({ testDir: "src/tests" });
process.exit(code);

The full flag list is under CLI usage and every option under Programmatic API.


πŸ’» CLI usage

vitest-runner [OPTIONS] [PATTERNS...]

Runner flags

Flag Description
--test-list <file> Run only the files listed in a JSON array file instead of scanning
--file-pattern <regex> Override the file discovery regex (default: \.test\.vitest\.(?:js|mjs|cjs)$)
--workers <n> Number of parallel workers (default: 4 or VITEST_WORKERS)
--solo-pattern <pat> Run files matching this path substring solo (one at a time) before the worker pool; repeatable
--exclude <glob> Directory / file glob, relative to cwd, that discovery never enters (e.g. tmp/**); repeatable
--no-error-details Hide inline error blocks β€” show only counts in the summary
--coverage-quiet Implies --coverage; suppress per-file output and show only a live progress bar and final summaries
--log-file <path> Write a clean (ANSI-stripped) copy of all output to this file. Defaults to coverage/coverage-run.log when --coverage-quiet is active
--suppress-file-output Suppress per-file runner output blocks in any mode
--suppress-passing-files Hide the PASSED TEST FILES section in the final summary
--no-top-summary Hide TOP MEMORY USERS and TOP DURATION summary sections
--json Print a JSON run report (no runner text output)
--blobs-dir <path> Directory for per-file coverage blobs (default: .vitest-coverage-blobs, relative to cwd)
--no-merge-reports Produce the coverage blobs but skip the merge and summary, leaving them in --blobs-dir for an external merge step
--no-coverage-index Don't write coverage-index.json after a coverage run; see Coverage index
--merge-batch-size <n> Merge coverage blobs in batches of n when there are more than n (default: 50 or VITEST_MERGE_BATCH_SIZE; 0 = one merge)
--merge-heap-mb <mb> Heap ceiling for the coverage merge only (default: VITEST_MERGE_HEAP_MB, else VITEST_HEAP_MB)
--file-timeout <s> Kill a test file's processes and fail it after s seconds (default: 1800 or VITEST_FILE_TIMEOUT; 0 = no limit); see Watchdog
--file-idle-timeout <s> Kill and fail a file that prints nothing for s seconds (default: 600 or VITEST_FILE_IDLE_TIMEOUT; 0 = no limit)
--keep-tmp Keep this run's scratch directory instead of removing it on completion
--isolate Run the suite in its own PID namespace (Linux; see Isolation)
--isolate=force The same, even when already in a PID namespace
--scratch-dir <path> Per-run scratch root, relative to cwd (default: tmp/vitest-runner)
--help, -h Print this help and exit

Test patterns

Patterns are resolved against cwd. Any of the following forms work:

# Absolute or relative file path
vitest-runner src/tests/config/background.test.vitest.mjs

# Partial path or filename β€” matched against all discovered test files
vitest-runner background.test.vitest.mjs
vitest-runner config/background.test.vitest.mjs

# Directory β€” all test files inside it are run
vitest-runner src/tests/metadata

Multiple patterns can be combined:

vitest-runner src/tests/config src/tests/metadata

Vitest passthrough flags

All unrecognised flags are forwarded verbatim to every vitest child process:

vitest-runner --reporter=verbose
vitest-runner -t "lazy materialization"
vitest-runner --coverage
vitest-runner --bail

Environment variables

Variable Default Description
VITEST_HEAP_MB (none) --max-old-space-size ceiling passed to every child process
VITEST_WORKERS 4 Maximum parallel worker slots in the non-solo phase (overridden by --workers)
VITEST_MERGE_HEAP_MB (none) --max-old-space-size for the coverage merge only (overridden by --merge-heap-mb / mergeMaxOldSpaceMb; falls back to VITEST_HEAP_MB)
VITEST_MERGE_BATCH_SIZE 50 Coverage merge batch size (overridden by --merge-batch-size / mergeBatchSize); see Merging many blobs
VITEST_FILE_TIMEOUT 1800 Per-file time limit in seconds, 0 = no limit (overridden by --file-timeout / fileTimeoutMs); see Watchdog
VITEST_FILE_IDLE_TIMEOUT 600 Per-file idle limit in seconds, 0 = no limit (overridden by --file-idle-timeout / fileIdleTimeoutMs)
CLDMV_TEST_ISOLATE (none) 1 runs the suite in its own PID namespace, force does it even when already in one (Linux; the isolate option or --isolate take precedence)

Examples

# Run all test files discovered under the default testDir
vitest-runner

# Run all tests, filter by name
vitest-runner -t "should handle null input"

# Run a specific folder
vitest-runner src/tests/auth

# Run with coverage (blob + merge β€” OOM-safe)
vitest-runner --coverage

# Coverage with quiet output and live progress bar (ideal for CI)
vitest-runner --coverage --coverage-quiet

# Run only files listed in a JSON file
vitest-runner --test-list my-tests.json

# Use a custom file discovery pattern
vitest-runner --file-pattern '\.spec\.ts$'

# Run 2 workers, with certain files running solo first
vitest-runner --workers 2 --solo-pattern heavy/ --solo-pattern listener-cleanup/

# Skip scratch worktrees / build output when discovery walks the repo root
vitest-runner --exclude 'tmp/**' --exclude 'dist/**'

# Custom heap and worker count
VITEST_HEAP_MB=8192 vitest-runner --workers 2 src/tests/heavy

# Suppress error details in the summary
vitest-runner --no-error-details

# JSON output for automation
vitest-runner --json

# JSON output without top summary arrays
vitest-runner --json --no-top-summary

πŸ”§ Programmatic API

import { run } from "@cldmv/vitest-runner";

// CommonJS
const { run } = require("@cldmv/vitest-runner");

require() loads the ES module build synchronously through Node's require(esm), which needs Node.js >=22.13.0; on older Node.js it throws a clear ERR_REQUIRE_ESM error, and import() is the way to load the package there.

When developing against a local checkout or workspace copy instead of the published package, run Node with --conditions=vitest-runner-dev so that import of the package resolves to its src/ entry (src/index.mjs) and require to src/index.cjs, instead of the built dist/. In this repository npm test runs the suite against src/ through that condition, and npm run test:dist builds the package and runs the suite against dist/.

run(options) β†’ Promise<number | object>

Runs the test suite and resolves with an exit code (0 = all passed, 1 = any failure) by default. When json: true is passed, it returns a structured JSON report object (including exitCode) instead of printing runner text output.

import { run } from "@cldmv/vitest-runner";

const code = await run({
	testDir: "src/tests"
});

process.exit(code);

Options

Option Type Default Description
cwd string process.cwd() Absolute project root directory
testDir string cwd Directory (absolute or relative to cwd) to scan for *.test.vitest.{js,mjs,cjs} files
vitestConfig string auto-detect Explicit vitest config path; when omitted the runner walks standard config names (vitest.config.ts, vite.config.ts, etc.) relative to cwd
testPatterns string[] [] File / folder patterns to filter β€” empty means all files in testDir
testListFile string undefined Path to a JSON array of test file paths; when set, scanning is skipped entirely
testFilePattern RegExp DEFAULT_TEST_FILE_PATTERN Regex matched against file names during discovery (*.test.vitest.{js,mjs,cjs} by default)
exclude string[] [] Directory / file globs, relative to cwd, that discovery never enters (e.g. ['tmp/**']). Applies to both the default scan and partial-path pattern resolution
vitestArgs string[] [] Extra CLI args forwarded verbatim to every vitest invocation
showErrorDetails boolean true Print inline error blocks under each failed file in the summary
coverageQuiet boolean false Suppress per-file output; show only the progress bar and final summaries
suppressFileOutput boolean false Suppress per-file runner output blocks in all modes
suppressPassingFiles boolean false Hide passed-file rows in the final summary
topSummary boolean true Show or hide top memory/duration summary sections (and JSON arrays)
json boolean false Return a JSON report object instead of printing text output
workers number 4 Maximum parallel worker slots (overrides VITEST_WORKERS)
worstCoverageCount number 10 Rows in the worst-coverage table after a coverage run (0 disables it)
blobsDir string <cwd>/.vitest-coverage-blobs Directory for per-file coverage blobs. Relative paths resolve against cwd. Always cleared at the start of a coverage run
mergeReports boolean true When true, blobs are merged via vitest --mergeReports, the coverage summary is printed, and blobsDir is deleted. When false, the run stops after producing blobs β€” no merge, no summary β€” and blobsDir is left populated for an external merge
coverageIndex boolean true With mergeReports, write <reportsDirectory>/coverage-index.json: which test files executed which source functions. See Coverage index
mergeBatchSize number 50 Blob count above which blobs are merged in batches before the final vitest --mergeReports (overrides VITEST_MERGE_BATCH_SIZE). 0 always merges in one process; values below 2 are raised to 2. See Merging many blobs
maxOldSpaceMb number undefined Global --max-old-space-size ceiling in MB (overrides VITEST_HEAP_MB)
mergeMaxOldSpaceMb number undefined --max-old-space-size in MB for the coverage merge only: the final vitest --mergeReports and each batch process (overrides VITEST_MERGE_HEAP_MB; falls back to maxOldSpaceMb). Gives the merge more heap than each test file gets
earlyRunPatterns string[] [] Path substrings β€” matching files run solo (one at a time) before the parallel worker pool starts
perFileHeapOverrides PerFileHeapOverride[] [] Per-file minimum heap ceilings; the maximum of this and maxOldSpaceMb wins
fileTimeoutMs number 1800000 Longest one file may run before its process group is killed and the file reported as failed (overrides VITEST_FILE_TIMEOUT). 0 = no limit. See Watchdog
fileIdleTimeoutMs number 600000 Longest one file may go without printing anything before it is killed the same way (overrides VITEST_FILE_IDLE_TIMEOUT). 0 = no limit
perFileTimeoutOverrides PerFileTimeoutOverride[] [] Limits for known slow files, { pattern, timeoutMs?, idleTimeoutMs? }; the first matching path substring wins and replaces the limits it sets
conditions string[] [] Additional --conditions Node flags forwarded to children
nodeEnv string 'development' Value written to NODE_ENV in child processes
scratchDir string 'tmp/vitest-runner' Per-run scratch root, relative to cwd (or absolute). A subdirectory is created per file invocation and exposed to it via VITEST_RUNNER_TMP
keepTmp boolean false Keep the run's scratch root instead of removing it on completion (normal exit, failure, or SIGINT/SIGTERM)
isolate boolean | "force" CLDMV_TEST_ISOLATE Linux: run the whole suite in its own PID namespace; "force" does it even when already in one (see Isolation). Can't be combined with json
fsModuleCachePath string | false <cwd>/node_modules/.vitest-cache Vitest 5+ fsModuleCache directory for every child, relative to cwd (or absolute). Overrides a path in the vitest config; a --fsModuleCachePath passthrough arg overrides this. When unset, the default applies only if the resolved config (root or any project) sets no path. false adds nothing. See Vitest's module cache

PerFileHeapOverride

{
	pattern: string;
	heapMb: number;
}

pattern is a substring matched against the normalised (forward-slash) file path. The first match wins and is compared against the global maxOldSpaceMb; the larger value is used.

Examples

// Run all tests under src/tests/ (cwd defaults to process.cwd())
await run({ testDir: "src/tests" });

// Run only the config and metadata suites
await run({
	testDir: "src/tests",
	testPatterns: ["src/tests/config", "src/tests/metadata"]
});

// Coverage run (OOM-safe blob + merge mode)
await run({
	testDir: "src/tests",
	vitestArgs: ["--coverage"]
});

// Quiet coverage with live progress bar
await run({
	testDir: "src/tests",
	coverageQuiet: true
});

// Machine-readable output (no text logs)
const report = await run({
	testDir: "src/tests",
	json: true
});

console.log(report.exitCode);

// Give heap-heavy files a larger ceiling while keeping the global limit lower
await run({
	testDir: "src/tests",
	maxOldSpaceMb: 2048,
	earlyRunPatterns: ["listener-cleanup/"],
	perFileHeapOverrides: [{ pattern: "listener-cleanup/", heapMb: 6144 }]
});

Scratch directories (VITEST_RUNNER_TMP / makeRunTmpDir)

Every run gets its own scratch root (<scratchDir>/<16 random hex>/), created before any file runs and removed once the run completes β€” on success, on failure, and on SIGINT/SIGTERM β€” unless keepTmp is set. Each file invocation gets its own subdirectory under that root, exposed to the child as process.env.VITEST_RUNNER_TMP.

Stale roots left by a crashed prior run are swept at the start of the next run. A live run holds a liveness socket in its root (@cldmv/lib-process alive), so the sweep never trusts a pid: a root whose socket refuses connections is removed straight away, even inside a PID namespace where other runs' pids look dead. A root with no socket (a run still starting, or a path too long for a Unix socket) is only removed once it has gone 10 minutes without an update; live runs touch their root every minute. Roots named the old way (<pid>-<timestamp>, before 1.7) are removed after a day.

From a test file, use makeRunTmpDir(label) to get a fresh, uniquely-named subdirectory instead of managing your own mkdtemp base:

import { makeRunTmpDir } from "@cldmv/vitest-runner";

const dir = makeRunTmpDir("my-fixture"); // a fresh directory under VITEST_RUNNER_TMP

CLI flags: --scratch-dir <path> and --keep-tmp (see Runner flags above).

Watchdog

A test that never settles used to hold the whole run forever. Now every file has two limits: how long it may run (fileTimeoutMs, default 30 minutes) and how long it may go without printing anything (fileIdleTimeoutMs, default 10 minutes). When either is hit, the runner kills the file's whole process group (SIGTERM, then SIGKILL 5 seconds later), reports the file as failed with the reason and its last 20 lines of output, and carries on with the rest of the run. In the JSON report the file's result has a timedOut field with the reason.

await run({
	fileTimeoutMs: 15 * 60 * 1000,
	perFileTimeoutOverrides: [{ pattern: "browser/", timeoutMs: 45 * 60 * 1000, idleTimeoutMs: 0 }]
});
  • 0 turns a limit off. The CLI takes seconds: --file-timeout 900 --file-idle-timeout 0, or VITEST_FILE_TIMEOUT / VITEST_FILE_IDLE_TIMEOUT.
  • Vitest's default reporter can print little while a long test runs. In coverage runs, where it prints nothing until the file ends, the runner adds a small reporter that reports test progress on a side pipe, and that progress counts as output. A single test that legitimately runs for more than 10 minutes still needs a higher idle limit or an override.
  • Each file runs in its own process group so the kill also reaches vitest's workers and anything a test started, such as a browser. A process that moves itself out of the group (a new session) isn't reached. The runner reports the file anyway once its output pipes stay open past the grace period.
  • Because the files no longer share the terminal's process group, the runner kills their groups itself on SIGINT, SIGTERM and exit, with or without keepTmp. killChildProcessGroups() does the same from your own code.
  • On Windows there are no process groups, so a timeout kills the file's own process only.

Isolation (PID namespace)

A test that kills by a computed pid can reach every process you own. With isolate: true (or --isolate, or CLDMV_TEST_ISOLATE=1) the runner re-runs its own command line under unshare -U --map-current-user -p -f --mount-proc and returns that run's exit code. Inside the namespace a kill only reaches the run's own processes, and when the run ends the kernel kills anything it left behind.

  • Linux only. When unprivileged user and PID namespaces aren't available, the run fails before it starts. It never falls back to running unsandboxed.
  • Already in a PID namespace (a container, a k3s pod, an earlier unshare -p)? Then it runs as is: the runner compares /proc/self/ns/pid with the kernel's initial namespace. To isolate anyway, for example to test the isolated path in a container that allows unprivileged unshare, use isolate: "force", --isolate=force or CLDMV_TEST_ISOLATE=force. The same rule applies: if unshare isn't permitted, the run fails before it starts.
  • The re-run process gets VITEST_RUNNER_ISOLATED=1, which the runner removes from its environment straight away, so it doesn't re-run itself again and the tests it starts don't see it.
  • Your user id stays the same inside (--map-current-user, not -r, which breaks cp -a), so files keep their owner. The network isn't separated.
  • Code in your script before run() runs twice, once outside and once inside, because the whole command line is re-run.
  • Can't be combined with json.

Vitest's module cache

Vitest 5 caches transformed modules on disk (fsModuleCache, on by default from 5.0.5). Its default location is node_modules/.vitest-cache at the workspace root, shared by every package in the workspace, and each vitest process deletes the whole directory on startup when the lockfile differs from the one the cache was written for. Several processes starting at once after a lockfile change all try to delete it, and some fail with ENOTEMPTY. Packages in one workspace that have their own lockfile also keep clearing each other's cache.

Before any file runs, the runner starts one short helper process that loads the project's Vitest config (the root and every project) the way the workers will, and:

  • picks a cache per package: when the cache is on and nothing sets a path, every child gets --fsModuleCachePath=<cwd>/node_modules/.vitest-cache, so one package's run never clears another's cache;
  • checks the lockfile once: it starts Vitest once with the workers' args, which clears a stale cache, and exits. The workers then start on a cache that matches the lockfile. This step is skipped when solo files run first (the first solo file does the same job), when files never run in parallel, or when the cache is off.

The cache path is chosen in this order:

  1. a --fsModuleCachePath passthrough arg;
  2. the fsModuleCachePath option (false adds nothing and leaves Vitest's own setting in place);
  3. fsModuleCachePath set anywhere in the resolved config, including a project's own config;
  4. <cwd>/node_modules/.vitest-cache.

None of this applies to Vitest before 5, and if the helper fails or takes longer than a minute, the run goes ahead without it. To turn the cache off, pass --fsModuleCache=false or set fsModuleCache: false in the vitest config.

πŸ“Š Coverage mode

When --coverage (or coverageQuiet: true) is passed, the runner uses a blob-per-file strategy:

  1. Each file receives --coverage --reporter=blob with its own temp output directory.
  2. After all files complete, vitest --mergeReports combines the blobs into a single report.
  3. Temporary blob and per-file coverage directories are cleaned up automatically. The per-file coverage directories live under the run's own scratch root (see scratchDir), so two runs in the same project never remove each other's.

This avoids the OOM crash that occurs when a single vitest process holds coverage data for thousands of files simultaneously.

Merging many blobs

vitest --mergeReports reads every blob into memory at once, and each blob carries a coverage map of the whole include set, so a suite with hundreds of test files can run the merge itself out of heap after every test has passed.

When there are more blobs than mergeBatchSize (default 50, CLI --merge-batch-size, env VITEST_MERGE_BATCH_SIZE), the runner reduces them in rounds first. Each round merges up to mergeBatchSize blobs into one blob, each batch in its own Node process (with mergeMaxOldSpaceMb / VITEST_MERGE_HEAP_MB, else maxOldSpaceMb / VITEST_HEAP_MB, as its heap ceiling when set), and reads the batch one blob at a time. Rounds repeat until no more than mergeBatchSize blobs remain, then the usual vitest --mergeReports runs over the reduced set. Reporters, coverage.thresholds, test failures and the exit code therefore behave exactly as with a single merge; only Vitest's "Per blob" timing line lists the reduced blobs.

  • At or below the batch size nothing changes: one vitest --mergeReports over blobsDir.
  • The reduced blobs are written under the run's scratch directory (see scratchDir) and removed on every exit path. blobsDir itself is never modified by the reduction.
  • A reduced blob uses the installed Vitest's own flatted and @vitest/istanbul-lib-coverage, in the same layout the blob reporter writes. The layout is verified for Vitest 5.x. With any other Vitest major, or a blob that doesn't have that layout, the runner prints a warning and falls back to the single merge. It also falls back, with a warning, if a batch fails.
  • runMergeReports(blobsDir, opts) takes the same batchSize (and an optional scratchDir, defaulting to a directory next to blobsDir) when called directly.

Coverage index

After the merge, and before the blobs are deleted, the runner writes coverage-index.json into the coverage reports directory (coverage/ by default, or --coverage.reportsDirectory=<dir>), next to coverage-summary.json. For each source file it lists the file's functions and the test files that executed each one:

{
	"version": 1,
	"commit": "4f9c1e0…",
	"files": {
		"src/calc.mjs": {
			"add": ["tests/add.test.vitest.mjs", "tests/initials.test.vitest.mjs"],
			"clamp": []
		}
	}
}
  • A function lists a test file when its call count in that file's blob is above zero. Only real functions are indexed, never module top-level code: loading a package runs every module's top level, which would list every test against every file.
  • Every function in the coverage map appears, with [] when no test reached it. A name used more than once in one file is keyed name@<line> for each occurrence.
  • Paths are relative to cwd with forward slashes, so the index is the same in CI and a local checkout. commit is git rev-parse HEAD in cwd, else GITHUB_SHA, else null.
  • With the index, a repo can re-measure one source file by running only the test files that reach it, instead of the whole suite.
  • The blobs are read one at a time. If the index can't be written, the runner prints a warning and the run's result is unchanged. The JSON report carries coverageIndex: { path, files, testFiles } (or null).
  • coverageIndex: false / --no-coverage-index turns it off. With mergeReports: false the run writes no index; a caller that merges the blobs itself writes it with writeCoverageIndexFromBlobs() (see Producing blobs for an external merge).

Coverage quiet mode

--coverage-quiet / coverageQuiet: true suppresses all per-file output and renders a live progress bar instead. On completion it prints the coverage table and any failures verbosely. When running in this mode, output is also mirrored to coverage/coverage-run.log (CLI only) with ANSI colour codes stripped so the file is human-readable in any editor.

The log file path can be overridden with --log-file <path>. Passing --log-file by itself only enables log mirroring (it does not enable coverage mode).

When no files are measured

If the coverage include matches no files (for example, a scaffold repo with a test but no source yet), istanbul reports every percentage as Unknown rather than a number. The runner prints those metrics as Unknown β€” Coverage Unknown% lines | Unknown% statements | … β€” adds a note that no files were measured, and exits 0 if the tests passed. The same applies to any individual non-numeric percentage in the worst-coverage table.

Coverage thresholds are skipped in this case, because there is nothing to measure: vitest's own threshold check does not fail on an Unknown percentage, and the runner does not add a check of its own. Thresholds apply again as soon as at least one file is measured. The JSON report's coverageSummary.noFilesMeasured is true for such a run.

Producing blobs for an external merge

Set mergeReports: false (CLI: --no-merge-reports) to stop the run after the per-file blobs are written. The internal vitest --mergeReports call and the coverage summary are skipped, and blobsDir is left intact instead of being deleted. The blobs directory is still cleared at the start of each run, so it only ever contains the current run's output.

This is useful when a second coverage blob set (for example, a browser-mode run with a different coverage transform) needs to be merged together with the node-mode blobs. Point both runs at known directories with blobsDir, then merge them in one external vitest --mergeReports step:

// Node-mode blobs, no internal merge
await run({
	testDir: "src/tests",
	vitestArgs: ["--coverage"],
	blobsDir: ".coverage-blobs/node",
	mergeReports: false
});

// (separately produce browser-mode blobs into .coverage-blobs/browser)
// then merge both blob sets in a single external step:
//   vitest --mergeReports .coverage-blobs --coverage

The exit code still reflects test pass/fail; there is just no coverage-merge result to fold in.

The run doesn't write the coverage index in this mode. Write it after your own merge, before deleting the blobs. It takes one blobs directory or several, and reads each blob's test files from the blob itself:

import { runMergeReports, writeCoverageIndexFromBlobs } from "@cldmv/vitest-runner";

await runMergeReports(".coverage-blobs/node", { cwd, vitestBin, extraCoverageArgs });
await writeCoverageIndexFromBlobs({ blobsDir: [".coverage-blobs/node", ".coverage-blobs/browser"], cwd, outputDir: "coverage" });

If the only reason for the external merge is to give it more heap, mergeMaxOldSpaceMb (CLI --merge-heap-mb, env VITEST_MERGE_HEAP_MB) sets the merge's heap on its own, and the runner's merge writes the index itself.


πŸ“‹ Test list files

A test list file is a plain JSON array of test file paths (relative to cwd):

["src/tests/auth/login.test.vitest.mjs", "src/tests/auth/register.test.vitest.mjs", "src/tests/config/defaults.test.vitest.mjs"]

Pass --test-list <file> (CLI) or testListFile: 'path/to/list.json' (API) to run exactly those files instead of scanning testDir.


πŸ” Test file naming

By default, the runner discovers files matching:

*.test.vitest.js
*.test.vitest.mjs
*.test.vitest.cjs

Files in node_modules or hidden directories (names starting with .) are always skipped.

The pattern can be overridden with --file-pattern <regex> (CLI) or the testFilePattern option (API):

# Match .spec.ts files instead
vitest-runner --file-pattern '\.spec\.ts$'
await run({ cwd, testDir: "src", testFilePattern: /\.spec\.ts$/i });

πŸ“ Source layout

dist/                  ← npm run build (scripts/build.mjs): src/ minified file by file, same layout,
                         nothing bundled β€” generated, not committed
  index.mjs            ← ESM entry
  index.cjs            ← thin CJS entry, copied verbatim from src/index.cjs; require()s index.mjs
  bin/vitest-runner.mjs ← the CLI (package.json "bin"); imports ../index.mjs
src/
  index.mjs            ← main run() API + re-exports
  index.cjs            ← CommonJS entry source (copied to dist/index.cjs by the build)
  bin/
    vitest-runner.mjs  ← CLI entry SOURCE β€” run this directly for source-level dev/testing
  utils/
    ansi.mjs           ← stripAnsi, colourPct
    duration.mjs       ← formatDuration
    env.mjs            ← buildNodeOptions, buildEnv
    resolve.mjs        ← resolveBin, resolveVitestConfig
  core/
    discover.mjs       ← discoverVitestFiles, sortWithPriority, computeFilterConflicts
    parse.mjs          ← parseVitestOutput, deduplicateErrors
    spawn.mjs          ← runSingleFile, runVitestDirect, runMergeReports
    report.mjs         ← printCoverageSummary, printMergeOutput
    progress.mjs       ← createCoverageProgressTracker
    scratch.mjs        ← makeRunTmpDir + the scratch-directory lifecycle
    watchdog.mjs       ← per-file time and idle limits, process-group kills
    heartbeat-reporter.mjs ← reports coverage-run test progress to the idle watchdog
    fs-cache.mjs       ← prepareFsModuleCache: Vitest module cache path + one-time lockfile check
    fs-cache-helper.mjs ← helper process started by fs-cache.mjs (built to dist/ and bin/)
    merge-batches.mjs  ← batched coverage-blob merge used by runMergeReports
    merge-batches-helper.mjs ← helper process that merges one batch (built to dist/ and bin/)
  cli/
    args.mjs           ← parseArguments
    help.mjs           ← showHelp

src/ is not published β€” only dist/, bin/, and types/ ship (see Programmatic API for the vitest-runner-dev export condition, used when developing against a workspace/local checkout instead of the published package). All sub-module utilities are re-exported from the root entry point, so deep imports are optional.


πŸ“š Documentation

CodeFactor OpenSSF Scorecard npms.io score npm unpacked size Repo size


🀝 Contributing

Bug reports and pull requests are welcome on GitHub. Pull requests target the next branch; releases ship from next to master.

Contributors Sponsor shinrai


πŸ”— Links


πŸ“„ License

npm license

Apache-2.0 Β© Shinrai / CLDMV. See LICENSE for the full text.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages