EMZETT.
Login

Jest and Vitest: Writing JavaScript tests

In short: Jest and Vitest run JavaScript and TypeScript tests, offer mocks, snapshots and coverage; Vitest is especially fast and fits Vite projects.

In more detail: Both tools have almost the same syntax with describe, test/it and expect. Jest (Meta) has long been the standard, especially with React; Vitest is a younger, very fast framework with Vite support, ESM and TypeScript without additional configuration.

In Depth

A test

// sum.js
export const sum = (a, b) => a + b;
 
// sum.test.js
import { describe, it, expect } from 'vitest'; // with Jest: global
import { sum } from './sum.js';
 
describe('sum', () => {
  it('adds two numbers', () => {
    expect(sum(2, 3)).toBe(5);
  });
  it('handles negative numbers', () => {
    expect(sum(-1, -1)).toBe(-2);
  });
});

Start: npx vitest or npx jest (in watch mode changed tests rerun automatically).

Important features

  • Matchers: toBe, toEqual, toContain, toThrow, toBeNull, toHaveLength, resolves/rejects for promises.
  • Mocks and spies: vi.fn() / jest.fn(), vi.mock('module'), control time with useFakeTimers.
  • Snapshot tests: output is saved and compared on changes.
  • Hooks: beforeEach, afterEach.
  • Coverage: --coverage.
  • Asynchronous: async/await directly in the test.
  • UI tests: React Testing Library, Vue Test Utils (check what users see), with jsdom as a simulated browser.

Comparison

  • Vitest: fast start, uses the same configuration as Vite, ESM-native, Jest-compatible API.
  • Jest: very widespread, large ecosystem base, sometimes more complicated with ESM/TypeScript (Babel/ts-jest).
  • Node’s own test runner (node --test) for small projects without dependencies.
  • For browser tests Playwright or Cypress.

Good practice

Test behaviour, not implementation details. A clear arrange – act – assert structure. Keep tests fast and independent, mock only boundaries (network, time, database). Do not underestimate snapshot tests: too large snapshots are accepted blindly. Run tests in CI and keep them green.

See also: Unit test, Mocking and test doubles, Snapshot tests, Playwright