Testing & Debugging

Unit Testing

Unit tests verify individual functions and components in isolation. With Jest or Vitest, you get fast, reliable feedback on every change — catching bugs before they ever reach production.

How do you write unit tests in JavaScript?

A unit test calls a small piece of code, such as a function, with known inputs and checks the output with assertions. Use Vitest or Jest: write test("adds numbers", () => { expect(add(2, 3)).toBe(5); }) in a *.test.js file and run npx vitest. Good unit tests are fast, independent and test behaviour, not implementation details.

// sum.test.js
import { describe, test, expect } from "vitest";
import { sum } from "./sum.js";

describe("sum", () => {
  test("adds two numbers", () => expect(sum(2, 3)).toBe(5));
  test("handles negatives", () => expect(sum(-1, 1)).toBe(0));
});

Jest vs Vitest

FeatureJestVitest
Module systemCJS by default (ESM needs config)ESM native
SpeedMediumFast (shares Vite transforms)
Configjest.config.jsvitest.config.ts (reuses vite.config)
Watch modejest --watchvitest (on by default)
Coveragejest --coveragevitest --coverage
Browser modejsdom (simulated)jsdom + real browser
Snapshot✅ Built-in✅ Built-in
Best forNode.js, React (CRA, CJS)Vite, modern ESM projects

Matchers Quick Reference

Equality

  • toBe(val) — ===
  • toEqual(val) — deep
  • toStrictEqual(val) — strict deep
  • not.toBe(val) — negate any

Truthiness

  • toBeTruthy()
  • toBeFalsy()
  • toBeNull()
  • toBeUndefined()
  • toBeDefined()

Numbers

  • toBeGreaterThan(n)
  • toBeGreaterThanOrEqual(n)
  • toBeLessThan(n)
  • toBeCloseTo(n, precision)

Strings

  • toContain('substring')
  • toMatch(/regex/ or 'str')
  • toHaveLength(n)

Arrays / Objects

  • toContain(item)
  • toContainEqual({obj})
  • toHaveLength(n)
  • toMatchObject({partial})

Errors

  • toThrow()
  • toThrow(ErrorClass)
  • toThrow('message')
  • toThrow(/regex/)

Common Pitfalls

Using toBe() for object/array comparison — always fails because reference !== reference
Use toEqual() for deep value equality, toBe() only for primitives and same-reference checks.
Testing implementation details (internal variables, private methods) — tests break on refactor
Test observable behavior: inputs → outputs, not how it works internally. Tests should survive refactoring.
Forgetting to await async assertions — test passes vacuously before the promise resolves
Always await expect(promise).resolves or return the promise. Add async keyword to test callback.
Mocking too much — test passes but doesn't prove anything real about the system
Mock only external dependencies (DB, HTTP, timers). Keep the unit under test real.

Interactive Demo

Code Editor

<pre id="out"></pre>

Preview

Unit Testing: summary

Key points

  • Use toBe for primitives and toEqual for deep object and array equality.
  • Mock only external boundaries (network, time, randomness).
  • Test edge cases: empty input, zero, null and very large values.
  • Run tests in CI on every pull request.

Frequently asked questions

›Jest or Vitest?

Vitest for Vite-based and new projects: it's fast and Jest-compatible. Jest remains common in existing codebases.