Code of the Day
AdvancedTooling & Types

Testing JavaScript

Write and run tests with a modern JS test runner.

JavaScript / TSAdvanced8 min read
Recommended first
By the end of this lesson you will be able to:
  • Write a test with a describe/it/expect structure
  • Test asynchronous code
  • Mock dependencies to isolate a unit

The testing fundamentals lesson covered the why and what; this is the how in JavaScript. Modern runners — Vitest and Jest lead — share almost identical syntax, so the skills transfer directly.

describe / it / expect

Tests are grouped with describe, defined with it (or test), and assert with expect (arrange–act–assert from the testing lesson):

import { describe, it, expect } from "vitest";
import { sumTo } from "./math.js";

describe("sumTo", () => {
  it("sums 1..n inclusive", () => {
    expect(sumTo(3)).toBe(6);     // arrange + act + assert
  });

  it("handles zero", () => {
    expect(sumTo(0)).toBe(0);     // the boundary case
  });
});

Run the suite with vitest (or jest); a failure prints the expected and actual values. expect offers many matchers — toBe, toEqual (deep equality, for objects/arrays — recall reference vs value!), toThrow, and more.

Testing async code

Because await works in tests, asynchronous code tests naturally — async test, await the result (the promises lesson):

it("loads a user", async () => {
  const user = await loadUser(1);
  expect(user.name).toBe("Ada");
});

Mocking dependencies

To test a unit in isolation, replace its slow or external dependencies (network, time, randomness) with mocks — fakes you control:

import { vi } from "vitest";
const fetchUser = vi.fn().mockResolvedValue({ name: "Ada" });

Mock the boundary (the API call), not your own logic — over-mocking tests the mocks instead of the code. This keeps fast and deterministic (the testing-pyramid base).

Wire the suite into CI (the build-and-release lesson) so it runs on every push, and write the test that would have caught the last bug you shipped. Tests are the safety net that makes refactoring — and reviewing AI-generated code — safe.

Where to go next

That completes the JavaScript/TS Advanced tier — and the current curriculum. Revisit the Fundamentals: nearly everything here is those durable ideas wearing a language's syntax.

Finished reading? Mark it complete to track your progress.

On this page