Testing Fundamentals with Vitest

Why and what to test, the testing trophy, and writing fast unit tests with Vitest (or Jest) including mocks and coverage.

Intermediate · about 5 hours · difficulty 2/5

Learn first: TypeScript Fundamentals, Build Tools and Bundlers

Tests let you refactor and ship without fear. The goal is not 100% coverage; it is confidence per minute spent. Test the behaviour users and other code rely on, not implementation details.

Types of tests

  • Static checks: TypeScript and ESLint catch a whole class of bugs for free.
  • Unit tests: pure functions and hooks such as price calculations, reducers, formatters and validators. Fast and precise.
  • Integration / component tests: render components with their children and check behaviour from the user's perspective. For UIs these usually give the best return.
  • End-to-end tests: a real browser runs through critical journeys like signup and checkout. Slow but the most realistic.

Vitest

Vitest is a fast test runner that reuses your Vite config, so TypeScript, JSX and path aliases just work. Its API matches Jest (describe, it/test, expect), which you will still find in many codebases.

  • Arrange, act, assert: set up data, run the code, check the result.
  • Matchers: toBe, toEqual, toThrow, toHaveBeenCalledWith.
  • Mocks and spies: vi.fn(), vi.spyOn(), vi.mock() for modules; fake timers with vi.useFakeTimers().
  • Watch mode while coding; coverage reports to find untested branches.

Good tests

Descriptive names ("applies a 10% discount for orders over 100"), one behaviour per test, no dependence on order, and minimal mocking. If a refactor that keeps behaviour breaks a test, the test was too coupled to implementation.

Good enough to move on

You can set up Vitest in a Vite project, unit test utility functions and a reducer including edge cases, mock a module and read a coverage report.

Key concepts

  • Why test and what to test
  • Unit, integration and end-to-end tests
  • Vitest setup and API
  • Jest: Same API, common in existing codebases
  • Matchers and assertions
  • Mocks, spies and fake timers
  • Coverage reports
  • Testing custom hooks

Mini project

Add Vitest to your catalogue app and unit test the cart reducer, price formatting and discount rules, including edge cases (empty cart, negative quantities), and a debounce helper using fake timers.

Check yourself

Why might a test that checks a component's internal state variable be worse than one that checks what the user sees?

Free resources