Skip to content
FEE
Frontend Engineering Essentials
Entry Level
Hardened· 2026-07

[FEE-1101] Unit Testing with Vitest & Jest ​

INFO

A unit test isolates one function or module, supplies controlled inputs, and checks the outputs without touching a database, network, or DOM renderer. As of mid-2026 Vitest and Jest are both mainstream choices: Jest 30 (June 2025) shipped measured speedups and remains the default runner for React Native, while Vitest has passed Jest in weekly npm downloads. This article covers writing and configuring unit tests with Vitest, mocking correctly so a unit test stays a unit test, and treating snapshot tests and coverage percentages as tools rather than goals.

Context ​

A unit test verifies one function or module in isolation. It imports the subject under test, supplies controlled inputs, and asserts on the outputs. No database, network, or DOM renderer is involved. When a unit test fails, you know exactly which piece of logic broke and why, because nothing else was in scope.

This isolation is what makes unit tests the fastest and cheapest layer of the testing pyramid (see FEE-1100). A pure function like calculateDiscount(price, rate) has no side effects, no I/O, and no shared state. A test for it runs in microseconds, is deterministic across machines, and requires no test environment setup beyond importing the module.

Not all units are pure functions. A module that reads from localStorage, calls a network API, or dispatches to a global event bus has dependencies. Unit testing those modules requires mocking: replacing real dependencies with controlled stand-ins that return predictable values. Mocking is what keeps a unit test a unit test. When you mock the network call, the test is no longer testing whether the network works; it is testing whether your code responds correctly to what the network returns. Mock at external boundaries (network, storage, the clock), not internal functions; see Common Mistakes below and FEE-1104 for the full treatment.

Jest became the default JavaScript test runner during the 2010s, and its API (describe, it, expect, beforeEach, jest.fn(), jest.mock()) is now a shared vocabulary among frontend engineers. Most existing React documentation and Stack Overflow answers still use it. See Design Thinking below for why it won that position.

Vitest emerged in 2021 as a Vite-native alternative. It is intentionally API-compatible with Jest, so the migration path is largely find-and-replace (jest.fn → vi.fn, jest.mock → vi.mock). What Vitest changes is the execution model: it uses Vite's esbuild pipeline for transforms, so TypeScript and JSX are processed without a separate transpilation step, and it reuses Vite's live module graph in watch mode to re-run only the tests affected by a changed file. Relative speed depends heavily on suite shape, transform config, and isolation settings, so treat any specific cross-runner multiplier with suspicion. The one benchmark either project has published with real numbers is Jest's own: the Jest 30 release (June 2025) measured up to 37% faster runs and 77% lower memory usage than Jest 29 on the server test suite of one large TypeScript app (Jest blog).

As of mid-2026 both are mainstream, actively developed tools. Jest 30.x ships regularly and remains the default test runner for React Native; Vitest overtook Jest in weekly npm downloads during 2025-2026 (roughly 70M vs. 45M weekly as of June 2026, per npmtrends). Pick by build pipeline: in a Vite project use Vitest; in a Webpack or other non-Vite build, Jest remains the pragmatic choice.

Node's built-in test runner (node:test, stable since Node 20) is a third, zero-dependency option. It has no transform pipeline of its own, so it suits small libraries with no build step, but it lacks Vitest's watch-mode module graph and Jest's snapshot tooling. For application code with TypeScript, JSX, or path aliases, Vitest or Jest remain the practical choices.

Visual ​

Unit Test Lifecycle ​

The following diagram shows the lifecycle of a unit test suite. beforeAll runs once per describe block before any test. afterAll runs once after all tests complete. beforeEach and afterEach wrap every individual test. This is the correct place to reset mocks and shared fixtures.

Example ​

Vitest ↔ Jest quick reference ​

Every example below is written for Vitest. If you are working in a Jest 30 codebase, this table transposes the config keys, APIs, and CLI flags.

ConceptVitestJest
Config locationtest block in vite.config.tsjest.config.ts
Mock functionvi.fn()jest.fn()
Module mockvi.mock()jest.mock()
Spyvi.spyOn()jest.spyOn()
Auto-restore mocksrestoreMocks: truerestoreMocks: true
Update snapshotsvitest -ujest -u (or jest --updateSnapshot)
Single run (CI)vitest runjest (add --ci to fail on new snapshots)
Coveragevitest run --coveragejest --coverage

1. vitest.config.ts with coverage ​

The simplest Vitest setup adds a test block to vite.config.ts. The coverage block sets thresholds that fail the run if any metric falls below the specified percentage.

ts
// vitest.config.ts (or merge into vite.config.ts)
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    // Vitest defaults to a Node environment. This opts into jsdom for
    // DOM code (requires installing it separately: npm i -D jsdom).
    environment: 'jsdom',

    // Run setup files before each test file
    setupFiles: ['./src/test/setup.ts'],

    // Coverage configuration
    coverage: {
      // 'v8' is the default provider. Since Vitest 4.0 it uses AST-based
      // remapping (opt-in experimental in 3.2) that matches istanbul's
      // accuracy. 'istanbul' remains useful for non-V8 runtimes.
      provider: 'v8',

      // Which files to include in the report (even if never imported by a test)
      include: ['src/**/*.{ts,tsx}'],

      // Exclude test files and type-only files from coverage
      exclude: ['src/**/*.test.{ts,tsx}', 'src/**/*.d.ts'],

      // Fail the run if any threshold is not met
      thresholds: {
        lines: 80,
        branches: 75,
        functions: 80,
        statements: 80,
      },

      // Output formats: 'text' prints to terminal, 'lcov' uploads to Codecov
      reporter: ['text', 'lcov'],
    },
  },
})

Run coverage with: vitest run --coverage

2. A simple unit test ​

describe groups related tests. it (or test) names one scenario. beforeEach resets shared state before every test. expect asserts on the result.

ts
// src/utils/formatCurrency.ts
export function formatCurrency(amount: number, currency = 'USD'): string {
  if (!Number.isFinite(amount)) {
    throw new RangeError(`Invalid amount: ${amount}`)
  }
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency,
  }).format(amount)
}
ts
// src/utils/formatCurrency.test.ts
import { describe, it, expect, beforeEach } from 'vitest'
import { formatCurrency } from './formatCurrency'

describe('formatCurrency', () => {
  // beforeEach runs before every `it` block in this describe
  beforeEach(() => {
    // Nothing to reset here — pure function, no side effects.
    // In tests with mocks or shared state, this is where you reset them.
  })

  it('formats a whole-dollar amount', () => {
    expect(formatCurrency(1000)).toBe('$1,000.00')
  })

  it('formats cents correctly', () => {
    expect(formatCurrency(9.99)).toBe('$9.99')
  })

  it('respects a non-default currency', () => {
    expect(formatCurrency(42, 'EUR')).toBe('€42.00')
  })

  it('throws for non-finite amounts', () => {
    expect(() => formatCurrency(Infinity)).toThrow(RangeError)
    expect(() => formatCurrency(NaN)).toThrow(RangeError)
  })

  it('formats zero correctly', () => {
    expect(formatCurrency(0)).toBe('$0.00')
  })
})

3. Mocking with vi.fn() and vi.spyOn() ​

vi.fn() creates a mock function with no implementation. vi.spyOn() wraps an existing method so you can assert on calls without replacing the real implementation (unless you call .mockImplementation()).

ts
// src/services/analytics.ts
export const analytics = {
  track(event: string, data?: Record<string, unknown>): void {
    // Real implementation would send to a third-party service
    console.log('track', event, data)
  },
}
ts
// src/hooks/useCheckout.test.ts
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { analytics } from '../services/analytics'
import { submitOrder } from './useCheckout'

describe('submitOrder', () => {
  let trackSpy: ReturnType<typeof vi.spyOn>

  beforeEach(() => {
    // Create the spy fresh in each test. If it were created once at
    // describe scope, the afterEach below would restore analytics.track
    // to its real implementation after the first test, so later tests
    // would call the real analytics.track: negative assertions like
    // not.toHaveBeenCalled() would pass vacuously, and positive ones
    // would fail.
    trackSpy = vi.spyOn(analytics, 'track').mockImplementation(() => {})
  })

  afterEach(() => {
    vi.restoreAllMocks() // Restore analytics.track
    vi.unstubAllGlobals() // Restore global.fetch
  })

  it('tracks an order_placed event on success', async () => {
    const mockFetch = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ id: '42' }) })
    vi.stubGlobal('fetch', mockFetch)

    await submitOrder({ items: [{ sku: 'ABC', qty: 1 }] })

    expect(trackSpy).toHaveBeenCalledOnce()
    expect(trackSpy).toHaveBeenCalledWith('order_placed', { orderId: '42' })
  })

  it('does not track when the request fails', async () => {
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 500 }))

    await expect(submitOrder({ items: [] })).rejects.toThrow()
    expect(trackSpy).not.toHaveBeenCalled()
  })
})

4. Module mocking with vi.mock() ​

vi.mock() replaces an entire module with a factory function. The factory runs before any test in the file, which means the mock is in place before imports are resolved. This is how you replace a network layer, a third-party SDK, or a module that has side effects at import time.

ts
// src/api/userApi.ts
export async function fetchUser(id: string) {
  const res = await fetch(`/api/users/${id}`)
  if (!res.ok) throw new Error('User not found')
  return res.json()
}
ts
// src/services/userService.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest'

// vi.mock is hoisted to the top of the file by Vitest's transform.
// The string path must be a static literal (no variables).
vi.mock('../api/userApi')

import { fetchUser } from '../api/userApi'
import { getUserDisplayName } from './userService'

describe('getUserDisplayName', () => {
  beforeEach(() => {
    vi.mocked(fetchUser).mockReset()
  })

  it('returns full name when both name fields are present', async () => {
    vi.mocked(fetchUser).mockResolvedValue({
      firstName: 'Alice',
      lastName: 'Chen',
      email: 'alice@example.com',
    })

    const name = await getUserDisplayName('user-1')
    expect(name).toBe('Alice Chen')
  })

  it('falls back to email when name is missing', async () => {
    vi.mocked(fetchUser).mockResolvedValue({
      firstName: null,
      lastName: null,
      email: 'bob@example.com',
    })

    const name = await getUserDisplayName('user-2')
    expect(name).toBe('bob@example.com')
  })
})

5. Snapshot testing, and when to avoid it ​

toMatchSnapshot() serializes the value and writes it to a .snap file on first run. Subsequent runs compare against the stored snapshot. toMatchInlineSnapshot() stores the snapshot directly in the test file.

When snapshots are appropriate: stable, text-serialized output that is tedious to assert manually.

ts
// Good use: a deterministic string serialization
import { describe, it, expect } from 'vitest'
import { serializeFilter } from './queryBuilder'

describe('serializeFilter', () => {
  it('serializes a compound filter to a stable query string', () => {
    const filter = {
      status: ['active', 'pending'],
      createdAfter: '2025-01-01',
      tags: ['urgent'],
    }
    // The output is a flat string — easy to read in a .snap file,
    // meaningful to review when it changes.
    expect(serializeFilter(filter)).toMatchInlineSnapshot(
      `"status=active,pending&createdAfter=2025-01-01&tags=urgent"`
    )
  })
})

The two cited critiques agree on keeping snapshots short; Sapegin additionally recommends toMatchInlineSnapshot() so the value lives in the code-review diff instead of a separate .snap file, and Dodds recommends custom serializers to strip noise.

When to avoid snapshots: component JSX output. The snapshot is large, it changes on every style or markup tweak, and developers update it without reading it.

ts
// Avoid this pattern
import { render } from '@testing-library/react'
import { CheckoutForm } from './CheckoutForm'

it('renders correctly', () => {
  const { container } = render(<CheckoutForm />)
  // This snapshot will be 200+ lines of HTML. Nobody will review it.
  // When a class name changes, the developer runs -u and moves on.
  expect(container).toMatchSnapshot() // ← do not do this
})

// Prefer explicit assertions instead
it('shows the submit button', () => {
  render(<CheckoutForm />)
  expect(screen.getByRole('button', { name: /submit/i })).toBeInTheDocument()
})

it('disables the submit button when the form is invalid', () => {
  render(<CheckoutForm />)
  expect(screen.getByRole('button', { name: /submit/i })).toBeDisabled()
})

6. Running in CI ​

bash
# Non-watch, single run — use this in CI
vitest run

# With coverage output (fails if thresholds are not met)
vitest run --coverage

# JUnit reporter for CI systems that parse XML test results (GitHub Actions, GitLab CI)
vitest run --reporter=junit --outputFile=test-results/junit.xml

# Run a specific file pattern
vitest run src/utils/

GitHub Actions example:

yaml
- name: Run unit tests
  run: pnpm vitest run --coverage --reporter=junit --outputFile=test-results/junit.xml

- name: Upload coverage to Codecov
  uses: codecov/codecov-action@v4
  with:
    files: ./coverage/lcov.info

Best Practices ​

MUST use Vitest for all new Vite projects instead of adding a separate Jest configuration. Vitest reads the test block inside your existing vite.config.ts, so aliases, plugins, and environment variables are inherited automatically, with no moduleNameMapper duplication needed.

SHOULD configure restoreMocks: true globally rather than managing mock cleanup per test. Setting restoreMocks: true in vitest.config.ts calls vi.restoreAllMocks() before each test, clearing call history and restoring vi.spyOn originals left from the previous test. This is the safest default for sequential tests, but it is not safe with test.concurrent: restoring all spies mid-run can affect sibling tests still in flight, so concurrent suites need scoped mockReset/mockRestore calls instead. Leaving cleanup to per-test afterEach calls risks a missing cleanup in one file causing state bleed that surfaces as intermittent failures elsewhere.

SHOULD write explicit assertions instead of snapshot tests for component output. Snapshot tests of JSX trees are an anti-pattern: developers run vitest -u without reading the diff, so the snapshot approves whatever the code currently produces. Write assertions on specific, user-visible properties instead, such as toHaveTextContent, toBeDisabled, and toHaveAttribute; they force you to articulate what the test is actually verifying.

MUST treat coverage as a gap detector, not a quality gate. A threshold of 75-80% line coverage will flag files with zero tests without incentivizing assertion-free test padding. Coverage at 100% MUST NOT be interpreted as proof of test quality: a single expect(fn()).toBeTruthy() call covers a function for coverage purposes while asserting almost nothing.

Design Thinking ​

Why Jest became the default ​

Jest's early dominance was not accidental. When Create React App shipped Jest pre-configured with JSDOM, zero-config test execution, coverage, and snapshots, it eliminated the configuration tax that had made testing prohibitive for smaller teams. Running npx create-react-app gave you a working test suite. Jest became the default answer because it removed every friction point at once, and that ecosystem advantage persists today: legacy codebases, most popular libraries, and the bulk of Stack Overflow answers still reference Jest's API. Jest 30 (June 2025) improved performance and ESM support significantly, and it remains the default test runner for React Native. Staying on Jest in an existing Jest project is often the lowest-friction path.

Why Vitest is preferred for new Vite projects ​

The key insight is configuration duplication. A Vite project has vite.config.ts that already knows your aliases, plugins, environment variables, and TypeScript paths. A Jest project adds a separate jest.config.ts (or babel.config.js plus jest-setup.ts) that must replicate a subset of that knowledge. When you add a path alias to Vite, you must manually mirror it in Jest's moduleNameMapper. When you upgrade a Vite plugin, you may need to update a Jest transform to match. This drift becomes a maintenance burden over time.

Vitest solves this by accepting a test block inside vite.config.ts. There is no separate configuration file. Aliases, plugins, and environment variables are inherited automatically.

The performance difference is architectural. Jest was designed before ESM was standardized: it compiles everything to CommonJS by default and treats its ESM support as experimental. Vitest uses esbuild natively, which is written in Go and parallelizes transforms across CPU cores. Relative speed depends heavily on suite shape, transform configuration, and isolation settings, so a single cross-runner multiplier is not something to quote with confidence; benchmark your own suite and date the result if you need a number. In a CI pipeline that runs many times per day, any consistent per-run gap still compounds into real cost.

Watch mode in Vitest leverages Vite's module graph. When you change utils/formatDate.ts, Vitest knows which test files import that module (directly or transitively) and re-runs only those. Jest also re-runs only related tests in watch mode, but it resolves dependents from a statically built CommonJS module map (its haste map) checked against git status. Vitest instead reuses Vite's live ESM module graph, which stays accurate through aliases, plugins, and dynamic transforms without a separate resolver.

Vitest also ships a browser mode that runs tests in a real Chromium, Firefox, or WebKit instance via Playwright. As of Vitest 4.0 (October 2025), browser mode is stable and adds visual regression testing (toMatchScreenshot) in-browser. The single @vitest/browser package was dissolved into per-provider packages such as @vitest/browser-playwright, with context imports moving to vitest/browser. Browser mode closes the gap between the jsdom simulation that Jest and jsdom-configured Vitest use and a real browser DOM, which matters for browser APIs jsdom does not implement (Web Animations, ResizeObserver, canvas).

The snapshot testing tradeoff ​

Snapshot testing was introduced to solve a legitimate problem: verifying that a serialized output has not changed without writing dozens of individual assertions. It works well for stable, text-serialized values: a CLI command's formatted output, an SVG path string generated by a chart library, a date formatting function's locale output, a Redux action sequence.

It works poorly for component JSX trees. A component snapshot is often hundreds of lines of serialized HTML attributes, class names, and inline styles. When the snapshot fails (because a class name changed, a new data-testid was added, or a dependency upgraded its output format), the developer runs vitest -u and approves the new snapshot without reading it. The test passes; the regression ships.

Kent C. Dodds describes this pattern directly: "I've personally experienced this with a snapshot that's over 640 lines long. Nobody reviews it, the only care anyone puts into it is to nuke it and retake it whenever there's a change."

The alternative is explicit assertions: expect(button).toHaveTextContent('Submit'), expect(form).not.toHaveAttribute('disabled'). These are harder to write than one toMatchSnapshot() call, but they force you to articulate what you actually care about.

Why coverage percentage is a vanity metric ​

expect(add(2, 2)).toBe(4) gives 100% line coverage of the add function. It does not test add(-1, -1), add(0, 0), add(NaN, 1), or add(Number.MAX_SAFE_INTEGER, 1). Coverage tells you which lines the test runner executed; it says nothing about whether those lines were exercised with inputs that would reveal a bug.

A team that targets "90% coverage" as a metric will write tests that exercise code paths without asserting on anything meaningful. Line coverage increases with every line the test runner touches, regardless of what expect calls surround it.

Coverage is useful as a gap detector: if a function has 0% coverage, there are zero tests for it. Coverage at 100% tells you nothing about test quality. Ask one question of a suite instead: if calculateDiscount silently returned 0 for every input, which test would fail?

Common Mistakes ​

Mocking too much. When a test mocks every dependency of a module, what it tests is essentially the wiring of mock calls, not the real logic. If calculateTotal calls applyDiscount, and applyDiscount is mocked to return 0, the test for calculateTotal will never catch a bug in discount logic. Mock at the boundary (network, storage, time), not at every internal function boundary.

Testing implementation instead of behavior. A test that asserts expect(component.state.isLoading).toBe(true) breaks every time you rename or restructure internal state, even when the component's visible behavior is unchanged. Test what the user experiences: rendered text, ARIA state, emitted events.

Using vi.mock() with a dynamic path. Vitest hoists vi.mock() calls at transform time. The module path must be a static string literal, no template literals and no variables. A call like vi.mock(`../${dir}/api`) will silently fail.

References ​