| | |

Vitest 23 🧪 Vitest UI — Visual test explorer and debugging

⏱️ Estimated read: 9 min | |

Command-line test execution offers speed and automation, but inspecting complex failure states, reviewing visual diffs, and managing large test trees exclusively through terminal logs can slow down complex debugging workflows. Vitest UI provides an interactive, browser-based visual dashboard that runs alongside your development server, giving developers a graphical control panel to inspect test structures, rerun individual suites, examine console output, and update snapshots visually.

Configuring and utilizing Vitest UI effectively bridges the gap between automated test execution and visual state inspection. This chapter explores installation workflows, live UI interactive features, static HTML reporting, and best practices for leveraging graphical explorers during debugging.

Key point: Vitest UI (@vitest/ui) provides an interactive browser-based dashboard for exploring test hierarchies, inspecting failure logs, updating snapshots, and debugging tests in real time.

Why X exists

The terminal text log limitation problem.

Complex nested assertion failures, massive object diffs, and long stack traces are often difficult to parse within standard linear terminal windows.

The selective rerun friction challenge.

Isolating and re-running a single nested test case via CLI flags often requires typing precise file paths or test name patterns repeatedly during active troubleshooting.

The snapshot review bottleneck.

Reviewing visual or string snapshot mismatches requires switching context to external diff tools unless an integrated UI highlights changes side-by-side.

The CI review sharing challenge.

Sharing test execution results with non-technical stakeholders or team members usually requires raw log dumps rather than clean, navigable summaries.

The interactive debugging visibility gap.

Developers often need a centralized overview of test execution status, runtime durations, and file dependencies without cluttering IDE extension panes.

a. Installing and Launching Vitest UI

Vitest UI is an optional package that runs on top of Vite’s development server infrastructure. To use it, you must install the package as a development dependency and launch Vitest with the --ui flag.

Bash

# Install the official Vitest UI package via npm
npm install -D @vitest/ui

JSON

{
  "scripts": {
    "test:ui": "vitest --ui"
  }
}

Running npm run test:ui starts Vitest in watch mode and spins up a local web server (typically at http://localhost:51204/__vitest__/). The interface connects to the running Vitest process via WebSockets, updating test statuses automatically as source files change.

b. Interactive Dashboard Features and Snapshot Management

The Vitest UI dashboard organizes tests into a hierarchical tree structure reflecting your project directories and test files. Clicking any test block displays its execution duration, console logs, stack traces, and associated assertion details in real time.

TypeScript

// src/components.test.ts
import { describe, expect, it } from 'vitest';

describe('UI Component State Suite', () => {
  it('renders modal component correctly', () => {
    const componentHtml = '<div class="modal">Active</div>';
    expect(componentHtml).toMatchSnapshot();
  });
});

When a snapshot test fails inside the dashboard, Vitest UI presents an interactive diff viewer. Developers can inspect expected versus actual outputs and click an explicit Update Snapshot button directly within the browser interface to accept changes without returning to the terminal.

c. Generating Static HTML Reports for CI Workflows

While the live UI requires an active development server, Vitest can also generate a static, read-only HTML report for continuous integration pipelines and automated review workflows.

TypeScript

// vitest.config.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    reporters: ['default', 'html'],
  },
});

Configuring the html reporter instructs Vitest to compile a self-contained report folder (or a single inlined file when singleFile is enabled) containing all test execution metrics. This report can be uploaded as a CI artifact, allowing teams to inspect test results and error traces in a browser view post-build.

Complete Example Session

TypeScript

// ============================================
// PART 1: JEST/VITEST CONFIGURATION FOR HTML REPORTER
// ============================================
export const vitestUiConfig = {
  test: {
    reporters: ['default', 'html'],
    outputFile: {
      html: './reports/vitest/index.html',
    },
  },
};

TypeScript

// ============================================
// PART 2: PACKAGE SCRIPT SETUP
// ============================================
export const packageScripts = {
  scripts: {
    "test:ui": "vitest --ui --api.port=51204",
    "test:report": "vitest run --reporter=html"
  }
};

TypeScript

// ============================================
// PART 3: SAMPLE SERVICE MODULE UNDER TEST
// ============================================
export function formatCurrency(amount: number, currency: string): string {
  const symbol = currency === 'USD' ? '$' : '€';
  return `${symbol}${amount.toFixed(2)}`;
}

TypeScript

// ============================================
// PART 4: UI TEST SUITE WITH SNAPSHOT ASSERTION
// ============================================
import { describe, expect, it } from 'vitest';

describe('Currency Formatter UI Suite', () => {
  it('formats USD currency correctly', () => {
    const result = formatCurrency(125.5, 'USD');
    expect(result).toMatchSnapshot();
  });
});

TypeScript

// ============================================
// PART 5: ERROR LOGGING SIMULATION FOR UI INSPECTION
// ============================================
describe('Error Trace Inspection Suite', () => {
  it('captures detailed stack traces for debugging', () => {
    const debugPayload = { code: 500, message: 'Internal Server Error' };
    expect(debugPayload.code).toBe(500);
  });
});

TypeScript

// ============================================
// PART 6: CONSOLE OUTPUT CAPTURE VERIFICATION
// ============================================
describe('Console Output Tab Verification', () => {
  it('logs diagnostic info visible in Vitest UI console panel', () => {
    console.warn('Diagnostic warning message for UI inspection');
    expect(true).toBe(true);
  });
});

TypeScript

// ============================================
// PART 7: RUNTIME STATUS TRACKING VIA WEBSOCKETS
// ============================================
// Vitest UI streams live test execution events to the browser dashboard

TypeScript

// ============================================
// PART 8: STATIC ARTIFACT GENERATION HOOK
// ============================================
import { existsSync } from 'node:fs';
import { resolve } from 'node:path';

export function verifyHtmlReportExists(): boolean {
  return existsSync(resolve('./reports/vitest/index.html'));
}

TypeScript

// ============================================
// PART 9: BROWSER TRACE VIEWER INTEGRATION
// ============================================
export const browserTraceConfig = {
  test: {
    browser: {
      enabled: true,
      traceView: true,
    },
  },
};

TypeScript

// ============================================
// PART 10: SESSION FINALIZATION
// ============================================
// Vitest UI session and static reporting pipelines configured successfully

Quick Reference

Vitest UI CLI Commands and Flags

Command / FlagAction Performed
npm i -D @vitest/uiInstalls the visual interface package
vitest --uiLaunches the interactive dashboard web server
vitest run --reporter=htmlGenerates a static HTML test report
--api.port <number>Configures a custom port for the UI server

Reporter Configuration Properties

PropertyValue TypePurpose
reportersArraySpecifies active reporters ('default', 'html', etc.)
outputFileObjectDefines custom filesystem output paths for reports
singleFileBooleanInlines all assets into a single standalone HTML report

Best Practices

✅ Do This:

TypeScript

npm i -D @vitest/ui                                                         // ✅

❌ Don’t Do This:

TypeScript

// manually build custom web dashboards to inspect test failure logs         // ❌

✅ Do This:

TypeScript

reporters: ['default', 'html']                                              // ✅

❌ Don’t Do This:

TypeScript

// rely exclusively on transient terminal output for complex test debugging  // ❌

✅ Do This:

TypeScript

singleFile: true                                                            // ✅

❌ Don’t Do This:

TypeScript

// commit massive multi-file HTML report directories to version control      // ❌

✅ Do This:

TypeScript

vitest --ui                                                                 // ✅

❌ Don’t Do This:

TypeScript

// attempt to rerun tests from a static HTML report (reports are read-only) // ❌

Common Pitfalls

PitfallWhy It HappensFix
Error: Cannot find module '@vitest/ui'The UI package is not installed in the project dependenciesRun npm install -D @vitest/ui to install the required package
UI dashboard fails to update on file changesRunning Vitest in run mode (vitest run) instead of watch modeLaunch Vitest UI using standard watch mode (vitest --ui)
Unable to update snapshots from HTML reportStatic HTML reports generated via the HTML reporter are strictly read-onlyUse the live development UI (vitest --ui) to interactively update snapshots
Missing console logs in UI panelLogs written outside test lifecycle hooks or asynchronous timing issuesEnsure log statements occur within active test execution blocks

Real-World Examples

1. Launching Vitest UI via Custom NPM Script

JSON

{
  "scripts": {
    "ui": "vitest --ui"
  }
}

2. Configuring HTML Reporter Output Path in Vitest Config

TypeScript

export default defineConfig({
  test: {
    reporters: ['default', 'html'],
    outputFile: {
      html: './dist/test-report.html',
    },
  },
});

3. Generating a Single-File Inlined HTML Report for CI

TypeScript

export default defineConfig({
  test: {
    reporters: ['html'],
    // singleFile bundles all assets into one shareable artifact
  },
});

4. Inspecting Component Snapshots Visually in Dashboard

TypeScript

it('matches dashboard card layout snapshot', () => {
  const card = renderCard({ title: 'Analytics' });
  expect(card).toMatchSnapshot();
});

5. Reviewing Captured Console Output Logs in UI Panel

TypeScript

it('logs initialization metrics', () => {
  console.info('Service initialized successfully');
  expect(true).toBe(true);
});

6. Filtering Test Files Directly Inside the Dashboard

Bash

# Start UI targeting a specific directory
npx vitest --ui src/components

7. Replaying Browser Traces in Vitest UI

TypeScript

export default defineConfig({
  test: {
    browser: {
      enabled: true,
      traceView: true, // Enables browser interaction playback in UI
    },
  },
});

8. Running Vitest UI on a Custom Port

Bash

npx vitest --ui --api.port 8080

9. Integrating HTML Report Generation into CI Workflows

YAML

- name: Run Vitest and Generate Report
  run: npx vitest run --reporter=html

10. Archiving Test Reports as CI Artifacts

YAML

- name: Upload Test Report Artifact
  uses: actions/upload-artifact@v4
  with:
    name: vitest-html-report
    path: ./coverage/index.html

Visual

Vitest UI Architecture and Data Flow

┌────────────────────────────────────────────────────────┐
│  Source Files / Test Files                             │
└───────────────────────────┬────────────────────────────┘
                            │
                            ▼
┌────────────────────────────────────────────────────────┐
│  Vitest Watch Process + WebSocket API Server           │
└───────────────────────────┬────────────────────────────┘
                            │
            ┌───────────────┴───────────────┐
            ▼                               ▼
┌───────────────────────┐       ┌───────────────────────┐
│ Live Browser UI       │       │ Static HTML Report    │
│ (`vitest --ui`)  │ (CI / Read-Only) │
└───────────────────────┘       └───────────────────────┘

Live UI vs. Static HTML Report Capabilities

┌────────────────────────────────────────────────────────┐
│ LIVE UI (--ui): Rerun Tests, Update Snapshots, Edit │
├────────────────────────────────────────────────────────┤
│ STATIC REPORT (html): Read-Only Review & Inspection│
└────────────────────────────────────────────────────────┘

Dashboard Diagnostic Panel Layout

┌────────────────────────────────────────────────────────┐
│ Test Explorer Tree ──► Selected Test Results & Diffs   │
├────────────────────────────────────────────────────────┤
│ Console Logs Tab   ──► Captured stdout / stderr output │
├────────────────────────────────────────────────────────┤
│ Stack Trace Tab    ──► File Paths & Line Number Links   │
└────────────────────────────────────────────────────────┘

Summary

ItemValue
ConceptVisual Test Explorer and Debugging in Vitest
Package Requirement@vitest/ui
Execution Flagvitest --ui
Communication ModelLive WebSocket connection to Vite dev server
CI AlternativeStatic HTML reporter (reporters: ['html'])
Snapshot ManagementInteractive visual diff review and snapshot updates
Artifact SharingSingle-file inlining option (singleFile)
Primary BenefitEnhances debug visibility and simplifies test navigation
Trace IntegrationSupports browser interaction playback via traceView
Report StateLive UI is interactive; HTML reports are read-only

Key takeaways:

  • Visualize test execution. Use vitest --ui to spin up a browser dashboard that maps your entire test tree and streams results in real time.
  • Manage snapshots interactively. Inspect visual and string diffs inside the browser and update outdated snapshots with a single click.
  • Generate CI reports. Configure the html reporter to produce navigable test summaries for continuous integration review.
  • Isolate diagnostic data. View captured console logs, error stack traces, and test run durations in a centralized graphical panel.
  • Choose the right mode. Leverage the live UI for local development workflows and static HTML reports for automated CI artifact storage.
  • Streamline troubleshooting. Eliminate the friction of parsing long terminal logs by inspecting assertion failures visually.

Remember: Vitest UI bridges the gap between automated terminal testing and graphical developer tooling. By combining live WebSocket test exploration, interactive snapshot updating, and static HTML reporting, engineering teams can debug complex codebases with maximum visibility and minimal friction.

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!