Unit tests with Vitest

Vitest is the Vite-native test runner for modern frontend projects. It uses the same config as Vite, so there is almost nothing to set up. Write a .test.ts file next to the function you are testing, run npm test, watch it pass.

src/utils/format.test.ts
typescript
import { describe, it, expect } from 'vitest';
import { formatPrice } from './format';

describe('formatPrice', () => {
  it('formats USD with two decimals', () => {
    expect(formatPrice(9.5)).toBe('$9.50');
  });

  it('handles zero', () => {
    expect(formatPrice(0)).toBe('$0.00');
  });

  it('rounds to two decimals', () => {
    expect(formatPrice(19.999)).toBe('$20.00');
  });
});

Testing a pure formatting function.

Quiz: Quiz

Loading practice…