Back to Blog
Testing Like a Pro with Vitest (2025)

Testing Like a Pro with Vitest (2025)

Ansh Gupta
2 min read
TestingVitestTypeScriptReactUnit TestingBest Practices

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.

AG

About Ansh Gupta

Frontend Developer with 3 years of experience building modern web applications. Based in Indore, India, passionate about React, TypeScript, and creating exceptional user experiences.

Learn more about me