| | |

Vitest 38 🧪 CI Integration — shard, tags, and reporter configuration

⏱️ Estimated read: 19 min | |

A test suite that runs on a laptop and a test suite that runs in a pipeline are two different problems. On a laptop, the developer wants a fast feedback loop and a readable failure. In a pipeline, the same suite has to finish inside a job timeout, split its work across parallel machines, produce artifacts that the CI provider can read, and fail loudly when something uses .only. Vitest addresses these as separate, named features rather than as one “CI mode” switch: --shard for splitting, tags for selecting subsets, reporters for the output format, and a handful of defaults that flip when the CI environment variable is present.

This chapter covers the three pieces that make the biggest difference in a pipeline. The first section covers --shard and the blob reporter that collects the pieces back together. The second covers test tags, the --tags-filter CLI option, and the strictTags guard. The third covers reporter configuration, including the github-actions and junit reporters and the outputFile map that routes each format to its own destination.

Key point: sharding splits work by test file, not by test, so a single slow file still lands on one machine; the blob reporter plus vitest merge-reports is what turns the split run back into one report, and tags are the mechanism for choosing which tests run in which job rather than just how many.


Why CI integration exists

The wall-clock problem. A suite of two thousand test files running on one worker takes as long as the sum of the files’ durations. The pipeline is billed by the minute and gated by a job timeout, so the suite has to be divided across machines. Dividing it badly is worse than not dividing it: if the split is unbalanced, the slowest machine sets the wall clock and the others idle. The sharding mechanism has to be deterministic, so that a rerun assigns the same files to the same shard and a flaky file does not wander between jobs.

The reporting problem. Once the run is split across four jobs, there is no single terminal output that a human or a bot can read. Each job has a fragment. The CI provider wants one artifact for its test-results tab, the pull request wants inline annotations on the changed lines, and the dashboard wants machine-readable JSON. These are three different output formats that have to be produced from one run, and a run split into four pieces has to have its four fragments merged before any of them is correct.

The subset problem. Not every job needs the whole suite. A pull request wants the tests affected by the changed files, a nightly job wants everything, a deploy gate wants the smoke set, and a migration job wants the database set. File-name matching is too coarse for this, because a smoke test and a database test can live in the same file. Tags add a second axis that is independent of the file layout, so the same file can be partitioned by purpose.

The trust problem. A pipeline that never fails is worse than one that does. Vitest reverses some local conveniences in CI: .only is rejected because a committed .only silently skips most of the suite, and an empty shard is an error because an empty shard usually means the shard index was wrong. These reversals are keyed on the CI environment variable that every major provider sets.

The flake problem. A test that fails in the pipeline but passes locally is expensive to debug because the pipeline does not keep the machine. The retry mechanism and the artifact reporters exist so the failure is reproducible: the junit XML records which test failed and how long it took, the blob report records the full run, and --retry distinguishes a genuinely broken test from a flaky one.


a. Sharding with --shard

--shard takes one value in the form <index>/<count>. The index is one-based and the count is the number of jobs that will run. Vitest sorts the discovered test files deterministically and assigns each file to a shard, so a rerun of the same commit assigns the same files to the same index.

# Run shard 1 of 4 in this job
npx vitest run --shard=1/4   # index=1, count=4; the other three run elsewhere

# Shard 2 of 4 in the next job
npx vitest run --shard=2/4   # index=2, count=4; disjoint from shard 1

# A nightly job that is not sharded runs everything
npx vitest run                # no --shard means one job, all files

The unit of division is the test file, not the test. A file with two hundred tests goes entirely to one shard, and a file with one slow integration test goes entirely to one shard and dominates that shard’s duration. The consequence is practical: sharding works well when the suite is many small files and works poorly when the suite is one giant file. If a single file is the bottleneck, splitting it into smaller files is the fix, not raising the shard count.

# Four jobs, each with its own worker pool
npx vitest run --shard=1/4 --maxWorkers=2   # shard 1 runs up to 2 workers

# The shard count and the worker count are independent knobs
npx vitest run --shard=1/4 --maxWorkers=8   # shard 1 runs up to 8 workers

The shard count and the maxWorkers count answer different questions. The shard count decides how many machines the file list is divided across. The maxWorkers count decides how many worker processes each machine uses for its share. A job with plenty of CPU and a small shard count benefits from a higher maxWorkers; a job pinned to two cores should not exceed maxWorkers: 2.

The --shard flag has a config equivalent in test.shard, and it accepts the same string or a { index, count } object. The CLI form is the one used in CI because the index comes from the matrix variable, not from the file.

// vitest.config.ts — the shard can also be pinned in config
export default defineConfig({
  test: {
    shard: "1/4", // same as --shard=1/4; usually set from CI instead
  },
});

--changed is the complementary filter for the pull-request case. It runs only the tests whose files depend on the files that changed against a git base. In a pipeline the base is usually the target branch, and passing it explicitly is what makes the result correct after a shallow checkout.

# Only tests affected by files changed since the target branch
npx vitest run --changed=origin/main   # base ref for the diff

# In a shallow clone, fetch the base first or the diff is wrong
git fetch origin main --depth=1        # make origin/main resolvable

Sharding and --changed compose but stack badly. --changed reduces the file list and --shard divides whatever remains, so a run with both may produce several empty shards. An empty shard is not a silent success: with passWithNoTests unset, a shard that discovers no files fails, which is the correct behaviour in a matrix job because an empty shard usually means the base ref was wrong.


b. Test tags and --tags-filter

Tags attach a name to a test or a suite so that a CLI filter can select it later. The name is an arbitrary string and the convention is a leading @. The tag is declared in the test’s options object, which is the second argument when the body is third.

import { test, expect } from "vitest";

// A single test with one tag
test("rejects an expired card", { tags: ["@smoke"] }, async () => {
  await expect(charge({ expired: true })).rejects.toThrow(); // the smoke assertion
});

// A test with two tags is selected by either one
test("checkout with a coupon", { tags: ["@smoke", "@slow"] }, async () => {
  await expect(checkout(coupon)).resolves.toMatchObject({ paid: true }); // real flow
});

// A database test that is neither smoke nor slow
test("migration adds the column", { tags: ["@db"] }, async () => {
  await expect(getColumns("orders")).toContain("paid_at"); // schema assertion
});

describe accepts the same option, and the tag applies to every test inside the block. That is the way to tag a whole file without repeating the option on each test, and the way to tag a nested block with an additional name.

import { describe, test } from "vitest";

describe("payments", { tags: ["@smoke"] }, () => {
  test("charges a card", async () => { /* inherits @smoke */ });   // tagged by the block
  test("refunds a charge", async () => { /* inherits @smoke */ }); // tagged by the block

  describe("webhooks", { tags: ["@slow"] }, () => {
    test("retries on 500", async () => { /* @smoke and @slow */ }); // both tags
  });
});

--tags-filter selects by these names. Its value is a filter expression: a bare name selects tests that have it, a ! prefix excludes them, and several terms combine. This is the option that lets one job run the smoke set and another job run everything else, using the same files.

# Only the tests tagged @smoke
npx vitest run --tags-filter='@smoke'   # inclusion

# Everything except the database tests
npx vitest run --tags-filter='!@db'     # exclusion

# Scope the filter to a directory as well
npx vitest run src/api --tags-filter='@smoke'  # file pattern + tag

The tags are declared in config so that a tag can carry behaviour, not just a name. A tag entry can attach retry and timeout, which then apply to every test carrying that tag. That is the mechanism for the “this test is known to be slow” case, and it keeps the numbers out of the individual tests.

// vitest.config.ts — a tag that carries a retry and a timeout
export default defineConfig({
  test: {
    tags: [
      { name: "@slow", timeout: 60_000 },  // the whole slow suite gets 60s
      { name: "@flaky", retry: 3 },        // three attempts for the tagged tests
    ],
  },
});

strictTags is on by default, and it means a test that uses a tag not declared in config fails. The guard exists because a typo in a tag name is invisible otherwise: the misspelled tag never matches a filter, so the test silently stops running in the shard that was supposed to run it. Turning strictTags off is possible but removes the only protection against that mistake.

// vitest.config.ts — the strict tag guard
export default defineConfig({
  test: {
    strictTags: true, // unknown tag = failure (the default)
  },
});

The --project flag is the other selection axis, and it is the one to reach for when the repository is a monorepo. A tag selects by purpose across all projects; a project selects by package. The two compose, so a matrix job can run --project=web --tags-filter='@smoke' to get one package’s smoke set.


c. Reporter configuration

A CI run usually needs more than one reporter: the default reporter for the human reading the log, and a machine format for the provider. The reporters array accepts several entries and each one is instantiated.

// vitest.config.ts — two reporters in one run
export default defineConfig({
  test: {
    reporters: ["default", "junit"], // terminal summary plus xml
  },
});

The github-actions reporter emits workflow commands rather than plain text, so a failing assertion becomes an annotation attached to the file and line in the pull-request diff. It is the reporter that makes the failure visible without opening the raw log, and it is meant to be combined with the default reporter rather than replace it.

// vitest.config.ts — annotations on the pull request
export default defineConfig({
  test: {
    reporters: ["default", "github-actions"], // summary + inline annotations
  },
});

The junit reporter produces the XML that most CI providers parse for their test-results tab. The json reporter produces the machine format for a custom dashboard. Both need a destination, and the outputFile map routes each reporter to its own path so that two file reporters in one run do not overwrite each other.

// vitest.config.ts — one destination per file reporter
export default defineConfig({
  test: {
    reporters: ["default", "junit", "json"], // three reporters at once
    outputFile: {
      junit: "./reports/junit.xml", // consumed by the CI test tab
      json: "./reports/results.json", // consumed by the dashboard
    },
  },
});

The blob reporter is the one that makes sharding work. It writes a binary artifact containing the full result of the run — every test, every duration, every failure — to a directory that defaults to .vitest-reports. Each shard produces its own blob, the CI uploads the directory as an artifact, and a merge job downloads all of them and runs vitest merge-reports to produce the single report that the other reporters would have produced in an unsharded run.

# Each shard writes a blob instead of printing a summary
npx vitest run --shard=1/4 --reporter=blob   # output lands in .vitest-reports

# The merge job turns the collected blobs into a normal report
npx vitest merge-reports --reporter=default .vitest-reports  # one summary

Two configuration defaults change in CI, and both are safety measures. allowOnly is false whenever CI is set, so a committed .only fails the run instead of silently narrowing it. passWithNoTests is false, so a job that discovers no files fails rather than passing vacuously.

// vitest.config.ts — the two CI-sensitive defaults
export default defineConfig({
  test: {
    allowOnly: !process.env.CI,  // reject .only in CI, allow it locally
    passWithNoTests: false,      // an empty run is a failure
  },
});

Complete Example Session

# ============================================
# PART 1: THE SHARD COMMAND
# ============================================
npx vitest run --shard=1/4   # index 1 of 4; deterministic file split

# ============================================
# PART 2: THE BLOB REPORTER PER SHARD
# ============================================
npx vitest run --shard=1/4 --reporter=blob   # writes .vitest-reports/ for the merge

# ============================================
# PART 3: THE MERGE JOB
# ============================================
npx vitest merge-reports --reporter=default .vitest-reports   # one combined summary

# ============================================
# PART 4: THE TAG DEFINITIONS
# ============================================
import { test } from "vitest";

test("rejects an expired card", { tags: ["@smoke"] }, async () => {
  await expect(charge({ expired: true })).rejects.toThrow(); // the smoke assertion
});
# ============================================
# PART 5: THE TAG FILTERS
# ============================================
npx vitest run --tags-filter='@smoke'   # the deploy gate runs only these
npx vitest run --tags-filter='!@db'     # the unit job skips the database

# ============================================
# PART 6: THE TAG CONFIG WITH ATTACHED RETRY
# ============================================
// vitest.config.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    tags: [
      { name: "@slow", timeout: 60_000 },  // raised timeout for the slow set
      { name: "@flaky", retry: 3 },        // three attempts for the tagged tests
    ],
    strictTags: true,                      // a typo in a tag fails the run
  },
});
# ============================================
# PART 7: THE CI-SENSITIVE DEFAULTS
# ============================================
// vitest.config.ts
export default defineConfig({
  test: {
    allowOnly: !process.env.CI,  // .only allowed locally, rejected in CI
    passWithNoTests: false,      // an empty shard is a failure
  },
});
# ============================================
# PART 8: THE OUTPUT FILES
# ============================================
// vitest.config.ts
export default defineConfig({
  test: {
    reporters: ["default", "junit", "json"], // terminal + two machine formats
    outputFile: {
      junit: "./reports/junit.xml",   // for the CI test-results tab
      json: "./reports/results.json", // for the dashboard
    },
  },
});
# ============================================
# PART 9: THE CHANGED-ONLY RUN
# ============================================
git fetch origin main --depth=1        # make the base ref resolvable
npx vitest run --changed=origin/main   # only tests affected by the diff

# ============================================
# PART 10: THE FULL CI JOB
# ============================================
# .github/workflows/test.yml
name: test
on: [push, pull_request]
jobs:
  shard:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        shard: [1, 2, 3, 4]                    # the four indices
    steps:
      - uses: actions/checkout@v4              # source for the run
      - run: npm ci                            # install dependencies
      - run: npx vitest run --shard=${{ matrix.shard }}/4 --reporter=blob
      - uses: actions/upload-artifact@v4       # collect this shard's fragment
        with:
          name: blob-${{ matrix.shard }}       # a unique name per shard
          path: .vitest-reports                # the directory the blob reporter wrote

  merge:
    needs: shard                               # runs after all four shards
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4              # a clean workspace for the merge
      - uses: actions/download-artifact@v4     # pull all four fragments
        with:
          path: all-blobs                      # one directory of blob dirs
      - run: npx vitest merge-reports --reporter=default --reporter=junit all-blobs

The ten parts covered the shard command, the blob reporter, the merge job, a tagged test, the filter expressions, the tag config with attached retry, the CI-sensitive defaults, the output file map, the changed-only run, and a full workflow that shards across four jobs and merges the fragments in a fifth.


Quick Reference

Sharding and Merging

CommandEffect
--shard=1/4Run shard 1 of 4
--reporter=blobWrite a mergeable fragment
vitest merge-reports <dir>Combine fragments into one report
.vitest-reportsDefault blob output directory
--changed=origin/mainOnly tests affected by the diff

Tag Selection

CommandEffect
--tags-filter='@smoke'Only tests with the tag
--tags-filter='!@db'Exclude tests with the tag
strictTags: trueUnknown tag is a failure
{ tags: [...] }Tag a test or a suite

Reporters

ReporterOutput
defaultGrouped terminal summary
verboseOne line per test
github-actionsInline pull-request annotations
junitXML for the test-results tab
jsonMachine-readable results
blobMergeable shard fragment

CI Defaults

OptionIn CI
allowOnlyfalse
passWithNoTestsfalse
retryAs configured
maxWorkersos.availableParallelism()

Best Practices

✅ Do This:

// Split by file count, not by test count
// --shard=1/4 --shard=2/4 --shard=3/4 --shard=4/4                  // ✅

// Use the blob reporter in every shard job
// npx vitest run --shard=1/4 --reporter=blob                       // ✅

// Tag at the describe level when the whole block shares a purpose
describe("payments", { tags: ["@smoke"] }, () => { ... });          // ✅

// Declare every tag in config so the guard can catch typos
tags: [{ name: "@slow", timeout: 60_000 }]                          // ✅

// Route each file reporter to its own path
outputFile: { junit: "./reports/junit.xml" }                        // ✅

// Fetch the base ref before a --changed run
// git fetch origin main --depth=1                                  // ✅

// Keep maxWorkers in step with the job's core count
maxWorkers: 2 // on a two-core runner                               // ✅

❌ Don’t Do This:

// Expect one giant file to shard well
// --shard=1/4 with 90% of tests in one file                        // ❌

// Print the summary in each shard instead of merging
// npx vitest run --shard=1/4 --reporter=default                    // ❌

// Rely on a tag that is not declared in config
test("x", { tags: ["@smok"] }, ...); // typo, silently unselected    // ❌

// Turn off the strict guard to silence the error
strictTags: false                                                   // ❌

// Combine --changed with a high shard count
// --changed=origin/main --shard=4/4 // three shards may be empty   // ❌

// Leave outputFile unset with two file reporters
reporters: ["junit", "json"] // they collide on the default path    // ❌

// Leave a committed .only in place
test.only("x", () => { ... }); // fails in CI by design              // ❌

Common Pitfalls

PitfallWhy It HappensFix
Uneven shard durationsOne file holds most testsSplit the file, not the shard count
Empty shard fails the job--changed reduced the listLower the shard count
No combined reportEach shard printed its ownUse blob then merge
Tag filter matches nothingTag misspelled, guard offDeclare tags, keep strictTags
Merged report emptyWrong artifact pathPoint merge-reports at the parent dir
Annotations missinggithub-actions not in reportersAdd it alongside default
Wrong changed setShallow clone, no base refgit fetch the base first
XML overwrittenTwo file reporters, one pathUse the outputFile map

Real-World Examples

1. The shard flag

npx vitest run --shard=2/4   # second of four jobs

2. The blob fragment

npx vitest run --shard=2/4 --reporter=blob   # writes .vitest-reports

3. The merge step

npx vitest merge-reports --reporter=default .vitest-reports   # one report

4. A tagged test

test("charges a card", { tags: ["@smoke"] }, async () => { ... });

5. A tagged block

describe("payments", { tags: ["@smoke"] }, () => { ... });

6. The inclusion filter

npx vitest run --tags-filter='@smoke'   # deploy gate

7. The exclusion filter

npx vitest run --tags-filter='!@db'     # unit job

8. The tag with a retry

tags: [{ name: "@flaky", retry: 3 }]    # three attempts

9. The output map

outputFile: { junit: "./reports/junit.xml" }   # per-reporter path

10. The changed run

npx vitest run --changed=origin/main    # affected tests only

Visual

The Shard Split

┌──────────────────────────────────────────────────────────┐
│  SHARD 1/4            SHARD 2/4                          │
│  api.test.ts          user.test.ts                       │
│  db.test.ts           order.test.ts                      │
│                                                          │
│  SHARD 3/4            SHARD 4/4                          │
│  auth.test.ts         util.test.ts                       │
│  cart.test.ts         mail.test.ts                       │
│                                                          │
│  Each shard = one CI job. Files split evenly.            │
│  A single slow file still lands on one shard.            │
└──────────────────────────────────────────────────────────┘

The Merge Flow

┌──────────────────────────────────────────────────────────┐
│  JOB 1  vitest run --shard=1/4 --reporter=blob           │
│  JOB 2  vitest run --shard=2/4 --reporter=blob           │
│  JOB 3  vitest run --shard=3/4 --reporter=blob           │
│  JOB 4  vitest run --shard=4/4 --reporter=blob           │
│              │                                           │
│              ▼                                           │
│  .vitest-reports/  ◄── uploaded artifacts                │
│              │                                           │
│              ▼                                           │
│  MERGE JOB  vitest merge-reports                         │
│              --reporter=default --reporter=junit         │
│              │                                           │
│              ▼                                           │
│  terminal summary + junit.xml for the CI test tab        │
└──────────────────────────────────────────────────────────┘

Tag Selection

┌──────────────────────────────────────────────────────────┐
│  TAGGED TESTS                                            │
│    test('login', { tags: ['@smoke'] }, ...)              │
│    test('checkout', { tags: ['@smoke', '@slow'] }, ...)  │
│    test('migration', { tags: ['@db'] }, ...)             │
│                                                          │
│  FILTERS                                                 │
│    --tags-filter='@smoke'        only smoke tests        │
│    --tags-filter='!@db'          everything but db       │
│                                                          │
│  CONFIG                                                  │
│    tags: [{ name: '@slow', timeout: 60000 }]             │
│    strictTags: true   ── unknown tag = failure           │
└──────────────────────────────────────────────────────────┘

The Reporter Matrix

┌──────────────────────────────────────────────────────────┐
│  REPORTER          CI USE                                │
│  default           human log in the job output           │
│  github-actions    inline annotations on the diff        │
│  junit             xml for the CI test-results tab       │
│  json              custom dashboards and trend data      │
│  blob              per-shard artifact for merge-reports  │
│                                                          │
│  Combine: --reporter=default --reporter=junit            │
│  Set output: --outputFile.junit=./reports/junit.xml      │
└──────────────────────────────────────────────────────────┘

Summary

ItemValue
Shard unitTest file
Shard form<index>/<count>
Blob directory.vitest-reports
Merge commandvitest merge-reports
Tag declaration{ tags: [...] }
Tag filter--tags-filter
Typo guardstrictTags: true
Annotation reportergithub-actions
XML reporterjunit
Multi-output routingoutputFile map
CI-only reversalallowOnly becomes false

Key takeaways:

  • Sharding divides files, not tests. A file’s entire suite runs in one shard, so an unbalanced suite produces an unbalanced matrix and the slowest shard sets the wall clock.
  • The blob reporter is what makes sharding legible. Each shard writes a fragment, and vitest merge-reports turns the fragments back into the single report that the default, junit, and json reporters expect.
  • Tags add a selection axis that is independent of the file layout. A smoke test and a database test can share a file, and --tags-filter still separates them.
  • strictTags is the protection against the invisible typo. An undeclared tag never matches a filter, so without the guard a misspelled tag silently removes the test from the job that was meant to run it.
  • Tags can carry behaviour. A tag entry may attach retry and timeout, which keeps the slow-test numbers in one place instead of scattered through the test bodies.
  • CI needs more than one reporter. The default reporter serves the human, github-actions serves the diff, junit serves the results tab, and json serves the dashboard — all from one run, with outputFile routing each format.
  • --changed and --shard do not stack well. The first shrinks the file list and the second divides it, so the combination can produce empty shards that fail the matrix.
  • Two defaults flip in CI. allowOnly becomes false so a committed .only fails, and passWithNoTests stays false so an empty job fails rather than passing vacuously.

Remember: CI integration is three independent mechanisms that happen to be configured in the same file. --shard and the blob reporter solve the wall-clock problem by dividing the files and then recombining the pieces; tags solve the subset problem by naming tests independently of where they live; reporters solve the reporting problem by letting one run produce several formats at once. Get the balance right — files small enough to shard evenly, tags declared in config so the guard can catch typos, and one output path per format — and the pipeline becomes a fast, readable, and fail-loud version of the local run.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!