Back to Blog
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.ts
→utils/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 meRelated Articles
React Reading List for Busy Developers (2025)
Short, high‑signal concepts you should actually read: patterns, performance, server components, forms, and testing.
Aug 23, 20251 min readRead more →
Test Strategy for Modern Web Apps (2025)
A pragmatic testing strategy: what to unit test, what to integration test, and how to keep suites fast and useful.
Aug 22, 20251 min readRead more →
AI for Frontend: 12 Practical Patterns for 2025
Real-world ways to add AI to frontend apps — autocomplete, summarization, server actions, streaming UI, privacy-aware inference, and more.
Aug 18, 20252 min readRead more →