Writing
Testing2 min read

Testing Like a Pro with Vitest (2025)

Fast, delightful testing for React and TypeScript. Learn how to structure tests, mock networks, and measure coverage with minimal boilerplate.

AGAnsh GuptaFrontend Engineer
QA

Testing Like a Pro with Vitest (2025)

Vitest gives you Jest‑compatible APIs with Vite‑level speed. Here’s the no‑nonsense setup that teams actually use.

What To Test

  • Pure functions: business rules and utilities.
  • Components: render, user interactions, and critical states.
  • Async flows: API calls and failure handling.

Project Setup

  • Keep tests co‑located: utils/formatDate.tsutils/formatDate.test.ts.
  • Use happy path + edge cases + errors for each unit.
  • Run vitest --coverage in CI.

Example Patterns

// fetchUser.ts
export async function fetchUser(id: string) {
  const res = await fetch(`/api/users/${id}`);
  if (!res.ok) throw new Error('Failed');
  return res.json();
}

// fetchUser.test.ts
import { describe, it, expect, vi } from 'vitest'
import { fetchUser } from './fetchUser'

describe('fetchUser', () => {
  it('returns data on 200', async () => {
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: () => ({ id: '1' }) }))
    expect(await fetchUser('1')).toEqual({ id: '1' })
  })

  it('throws on non-200', async () => {
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false }))
    await expect(fetchUser('1')).rejects.toThrow('Failed')
  })
})

Golden Rules

  • Tests must be fast; slow tests don’t run.
  • Avoid over‑mocking; prefer realistic boundaries.
  • Snapshots only for stable UI fragments.

Write fewer, clearer tests that protect what matters most.

#Testing#Vitest#TypeScript#React#Unit Testing#Best Practices
AG

About Ansh

Frontend engineer with 4+ years building scalable SaaS products, design systems, CRM, analytics and omnichannel platforms.

More about me →

Related reading