Testing Fundamentals

Writing Your First Tests with Vitest

Get started with Vitest — the fast, modern test runner built for TypeScript and Vite-based projects.

Why Vitest

Vitest is the test runner of choice for modern TypeScript and Vite-based projects:

  • Fast — Vite-powered, runs tests in parallel, reruns only changed tests in watch mode
  • TypeScript-first — No configuration needed for TypeScript
  • Jest-compatible API — describe, it, expect work exactly like Jest
  • Native ESM support — No CommonJS transformation headaches

Installation and Setup

Install with npm install -D vitest, configure in vitest.config.ts with globals: true and the appropriate environment (node or jsdom), and add test scripts to package.json.

Test File Naming

Vitest discovers tests in files matching **/*.test.ts, **/*.spec.ts, or files inside **/__tests__/**. Keep test files next to the source files they test.

Basic Test Structure

Use describe() to group related tests, it() or test() to define individual tests, and expect() to make assertions. The API is Jest-compatible.

Essential Assertions

  • toBe() for exact equality (===)
  • toEqual() for deep equality
  • toContain() for array/string membership
  • toMatch() for regex matching
  • toThrow() for error testing
  • resolves/rejects for async assertions

Setup and Teardown

Use beforeAll/afterAll for expensive setup/teardown that runs once per describe block. Use beforeEach/afterEach to reset state before/after each test — never rely on test execution order.

Key Takeaways

  • Vitest is the recommended test runner for TypeScript/Vite projects — fast, TypeScript-native, Jest-compatible API
  • Test files are co-located with source files using .test.ts or .spec.ts naming
  • describe() groups tests, it() defines individual tests, expect() makes assertions
  • beforeEach/afterEach ensure each test starts with clean, predictable state
  • Watch mode (vitest --watch) provides instant feedback during development

Example

typescript
// src/utils/formatPrice.test.ts
Try it yourself — TYPESCRIPT