Vite

Vitest unit tests, API mocks, and coverage gates

Reuse the Vite project configuration in Vitest, mock fetch in unit tests, and enforce V8 coverage thresholds in a CI workflow.

Vitest unit tests, API mocks, and coverage gates

When a Vite application and its tests transform the same imports differently, an alias can work in the browser and fail in the suite. I use Vitest to share the project’s transformation setup and keep test-specific settings in one place.

What Vitest shares with Vite

The runner can use the Vite configuration for plugins, aliases, and module transforms. That can remove a second set of mapping rules maintained only for tests. Test environments still differ from production. Node and jsdom are useful for controlled unit tests. Browser-specific behavior still needs a real browser test.

flowchart TD
    VITE["Vite configuration and transforms"] --> DEV["Application development"]
    VITE --> TEST["Vitest runner"]
    TEST --> ENV["Node or jsdom test environment"]
    TEST --> COVERAGE["V8 coverage report"]
    COVERAGE --> CI["CI threshold check"]

Configuring the test environment

Install the runner, a compatible coverage provider, and the DOM tools the example uses. The sample sets explicit test defaults, registers a setup file, and configures coverage thresholds.

1
2
# Install Vitest, the DOM environment, and the coverage provider
pnpm add -D vitest @vitest/coverage-v8 jsdom @testing-library/react @testing-library/jest-dom
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import path from 'path';

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  },
  test: {
    // 1. Enable global test helpers such as describe, it, and expect.
    globals: true,
    // 2. Choose a simulated DOM environment.
    environment: 'jsdom',
    // 3. Register shared test setup and DOM matchers.
    setupFiles: ['./src/test/setup.ts'],
    // 4. Configure V8 code coverage.
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
      exclude: ['node_modules/', 'src/test/**', '**/*.d.ts'],
      // Require a minimum of 80% coverage for the configured metrics.
      thresholds: {
        statements: 80,
        branches: 80,
        functions: 80,
        lines: 80
      }
    }
  }
});
1
2
3
4
5
6
7
8
// src/test/setup.ts
import '@testing-library/jest-dom';
import { afterEach, vi } from 'vitest';

// Restore mocked functions after each test.
afterEach(() => {
  vi.clearAllMocks();
});

Use the DOM environment only where a test needs it. Set up custom matchers in the shared setup file and clear or restore mock state between tests according to what the suite replaces. A leaked spy or global stub causes order-dependent failures.

Testing formatting and the API boundary

The formatting example checks the expected Korean won output and the explicit fallback for an invalid number. Testing locale-sensitive string output is useful when the display format is part of the contract.

1
2
3
4
5
6
7
8
// src/utils/formatters.ts
export function formatCurrency(amount: number, currency: string = 'KRW'): string {
  if (isNaN(amount)) return '0 \uC6D0';
  return new Intl.NumberFormat('ko-KR', {
    style: 'currency',
    currency
  }).format(amount);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/utils/formatters.spec.ts
import { describe, it, expect } from 'vitest';
import { formatCurrency } from './formatters';

describe('formatCurrency', () => {
  it('formats a valid amount as Korean won', () => {
    const result = formatCurrency(15000);
    // Verify the ko-KR currency format.
    expect(result).toMatch(/15,000/);
  });

  it('returns the fallback for NaN', () => {
    expect(formatCurrency(NaN)).toBe('0 \uC6D0');
  });
});

The API client test replaces the global fetch implementation so both success and error paths can run without network access. The success test inspects the parsed result and request arguments. The failure test checks the error produced by a non-success response.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/services/apiClient.ts
export interface UserResponse {
  id: number;
  name: string;
  role: string;
}

export async function fetchUserProfile(userId: number): Promise<UserResponse> {
  const response = await fetch(`/api/users/${userId}`, {
    headers: {
      Authorization: 'Bearer test-token'
    }
  });

  if (!response.ok) {
    throw new Error(`API error: ${response.status}`);
  }

  return response.json();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// src/services/apiClient.spec.ts
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { fetchUserProfile } from './apiClient';

describe('apiClient', () => {
  beforeEach(() => {
    vi.restoreAllMocks();
  });

  it('returns the parsed user on a successful GET', async () => {
    const mockUser = { id: 1, name: 'Namju Kim', role: 'admin' };

    // Mock the global fetch function.
    const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce({
      ok: true,
      status: 200,
      json: async () => mockUser
    } as Response);

    const data = await fetchUserProfile(1);

    expect(data).toEqual(mockUser);
    expect(fetchSpy).toHaveBeenCalledTimes(1);
    expect(fetchSpy).toHaveBeenCalledWith('/api/users/1', {
      headers: { Authorization: 'Bearer test-token' }
    });
  });

  it('throws on a 401 Unauthorized response', async () => {
    vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce({
      ok: false,
      status: 401
    } as Response);

    await expect(fetchUserProfile(99)).rejects.toThrow('API error: 401');
  });
});

The mock belongs at the network boundary, where it can exercise the client’s parsing and error behavior without replacing the function under test. Keep an integration test against the real API contract for cases a unit mock cannot represent.

Running tests and collecting coverage

Run the full suite once in CI mode. The recorded example showed 18 passing tests in four files and took 312 ms in that environment.

1
2
# Run the full suite once in CI mode
pnpm vitest run

Vitest terminal output after tests and fetch mocks pass Figure 1. The one-shot run reports passing tests and test files.

The coverage provider records which files, statements, branches, and functions ran. The example applies an 80% threshold. Coverage highlights places to inspect. Add cases for important behavior rather than only executing the uncovered line.

1
2
# Measure V8 coverage and enforce thresholds
pnpm vitest run --coverage

Vitest V8 coverage report and threshold result Figure 2. The report shows coverage by metric and whether the configured threshold passes.

Running the same checks in CI

The workflow installs from the lockfile and runs the non-interactive coverage command. A test or threshold failure makes that command exit unsuccessfully. Configure branch protection separately if the repository should block merging until the check passes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# .github/workflows/test.yml
name: Unit Test & Coverage

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
        with:
          version: 9
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'

      - run: pnpm install --frozen-lockfile
      - name: Run Vitest with Coverage
        run: pnpm vitest run --coverage

I verify the CI configuration with a known passing suite and an intentional local failure. That check catches a misplaced test glob or a command that silently omits coverage. Keep package and coverage provider versions compatible so a local run and CI interpret the settings the same way.

Next generation testing framework powered by Vite
This post is licensed under CC BY 4.0 by the author.