JavaScriptEasy
What is Unit Testing?
Unit testing checks the smallest pieces of code (a function, a hook, a component) in isolation, with fast automated tests that assert specific outputs for given inputs, so you catch regressions early and can refactor safely.
Anatomy of a good unit test
- Arrange: set up inputs and dependencies.
- Act: call the unit.
- Assert: check the result or the effect.
- Tests should be fast, isolated, deterministic (no real network, clock or randomness) and focused on behaviour, not implementation details.
What to test
- Pure logic: formatting, validation, calculations, reducers, utility functions.
- Edge cases: empty inputs, boundaries, invalid data, errors.
- Components through their public behaviour: what the user sees and can do (React Testing Library encourages this).
Tools in the JavaScript ecosystem
- Vitest (fast, Vite-native, Jest-compatible API) and Jest as test runners.
- Node's built-in test runner (
node:test) for simple Node projects. - React Testing Library for components; MSW to mock network requests.
- Coverage reports from the runner (aim for meaningful coverage of critical logic, not a percentage target).
The testing pyramid (or trophy)
Many fast unit tests, fewer integration tests, and a small number of end-to-end tests (Playwright, Cypress). For front-end apps many teams favour integration-style component tests, since they give the most confidence per test.
Practices
- Write a failing test for each bug before fixing it.
- One reason to fail per test, with descriptive names ("returns 0 for an empty cart").
- Keep functions pure where possible; they are the easiest to unit test.
Code example
js
1// The unit under test: pure, so it's easy to test2export function calculateTotal(items, { taxRate = 0, discount = 0 } = {}) {3 if (!Array.isArray(items)) throw new TypeError("items must be an array");4 const subtotal = items.reduce((sum, i) => sum + i.price * i.qty, 0);5 const discounted = Math.max(0, subtotal - discount);6 return Math.round(discounted * (1 + taxRate) * 100) / 100;7}89// cart.test.js (Vitest; the same API works in Jest)10import { describe, it, expect } from "vitest";1112describe("calculateTotal", () => {13 it("returns 0 for an empty cart", () => {14 expect(calculateTotal([])).toBe(0);15 });1617 it("multiplies price by quantity and adds tax", () => {18 // Arrange19 const items = [{ price: 10, qty: 2 }, { price: 5, qty: 1 }];20 // Act21 const total = calculateTotal(items, { taxRate: 0.2 });22 // Assert23 expect(total).toBe(30);24 });2526 it("never goes below zero with a large discount", () => {27 expect(calculateTotal([{ price: 10, qty: 1 }], { discount: 50 })).toBe(0);28 });2930 it("rejects invalid input", () => {31 expect(() => calculateTotal(null)).toThrow(TypeError);32 });33});
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.