Skip to content
Tutorials Center
My learning

Topics

Lesson 120 of 156 ยท Under the Hood

Testing JavaScript

Learn to test JavaScript - write unit tests with arrange-act-assert, build a tiny test runner, use test doubles, and see how Vitest, Jest and Playwright fit in.

Every time you change code, you risk breaking something that used to work. You can click through the app by hand after each change, but that's slow, boring and easy to skip. An automated test is a small piece of code that runs your code and checks the result. Run hundreds of them in a second, every time you save, and you'll know right away when something breaks.

Tests do more than catch bugs. They let you refactor without fear, they document how a function is supposed to behave, and writing them pushes you toward simpler code. In this lesson you'll build a tiny test runner of your own to see exactly how testing tools work, learn how to structure good tests, isolate code from slow or unpredictable parts, and see how professional tools like Vitest, Jest and Playwright fit together.

What a test really is

At its heart, a test is just three things: run some code, compare the result with what you expected, and complain loudly if they differ. You could write one with an if and a throw (Throwing Errors):

JavaScript
const result = add(2, 3);
if (result !== 5) {
  throw new Error(`Expected 5 but got ${result}`);
}

That if + throw is called an assertion. Testing libraries wrap it in readable helpers like expect(add(2, 3)).toBe(5), collect many tests, run them all even when some fail, and print a report. There's no magic involved โ€” so let's build one.

Build a tiny test runner

The runner below has test() to register a test, an expect() helper with three matchers, and run() to execute everything and print a summary. Read it once, then run it. One test fails on purpose so you can see what a failure looks like.

JS A test runner in 40 lines

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The failing test found a real bug: initials() breaks on extra spaces because split(" ") produces empty strings, ""[0] is undefined, and calling toUpperCase() on undefined throws a TypeError. Fix it by splitting on runs of whitespace โ€” name.trim().split(/\s+/) โ€” and run again. This is the testing loop in miniature: a failing test points at a bug, you fix the code, the test goes green and stays there to stop the bug from returning.

Notice a few design choices that real tools share:

  • Each test runs inside its own try...catch, so one failure doesn't stop the rest.
  • toBe() uses Object.is() (strict equality that also treats NaN as equal to itself), while toEqual() compares structure, because [2, 4] === [2, 4] is false (Comparison).
  • toThrow() receives a function, not a value. If you wrote expect(JSON.parse("{oops")), the error would be thrown before expect even ran.
  • The runner awaits every test, so async tests work too.

Structuring a good test: arrange, act, assert

Most good tests follow the same three-part shape, often called AAA:

  1. Arrange: set up the inputs and any objects the code needs.
  2. Act: call the one thing you're testing.
  3. Assert: check the result.
JavaScript
test("applies a 10% discount to orders over $100", () => {
  // Arrange
  const order = { items: [{ price: 80 }, { price: 40 }] };

  // Act
  const total = checkoutTotal(order);

  // Assert
  expect(total).toBe(108);
});

A few habits make tests far more useful:

  • One behavior per test, with a name that reads like a sentence: "rejects passwords shorter than 8 characters". When it fails, the name alone tells you what broke.
  • Test behavior, not implementation. Check what a function returns or does, not which private helpers it calls. Then you can rewrite its insides freely.
  • Cover the edges. Empty arrays, zero, negative numbers, missing fields, very long strings, the exact boundary (100 versus 100.01). Bugs live at edges.
  • Keep tests independent. Each test should set up its own data; never rely on another test running first.
JS Edge cases find the bugs

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Three checks fail, for two different reasons. The pagination failures are a real off-by-one bug: page 1 should start at index 0, so the fix is (page - 1) * perPage. The cents one is the classic floating-point surprise โ€” 0.1 + 0.2 is 0.30000000000000004 โ€” and the fix belongs in the code (work in whole cents) or in the assertion (compare with a tolerance; real tools offer toBeCloseTo()). Best Practices and Common Mistakes explains why.

Test doubles: fakes, stubs and spies

Pure functions โ€” same input, same output, no side effects โ€” are the easiest things to test. Real code also talks to the network, reads the clock, picks random numbers or writes to storage. Those make tests slow, flaky or impossible to predict.

The fix is to replace the unpredictable part during the test with a test double:

  • A stub or fake returns canned answers ("the API returned these 3 products"; "today is March 15").
  • A spy records how it was called, so you can assert that an email was "sent" exactly once with the right address.

The easiest way to make that possible is dependency injection: instead of reaching for fetch or Date.now() directly, a function receives them as parameters, with real defaults.

JS Injecting a fake clock and a fake API

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The fake API returns a real new Response(...), so ok, status and json() behave exactly as they would with fetch. Testing both the happy path and the error path is what turns "it works on my machine" into "it works".

Don't over-mock. If a test replaces almost everything, it ends up testing your mocks instead of your code. Fake only the slow or unpredictable edges (network, time, randomness), and let the real logic run.

Kinds of tests

Tests come in layers, often drawn as a pyramid โ€” many small, fast tests at the bottom and a few big, slow ones at the top:

Kind What it checks Speed Typical tools
Unit one function or class, in isolation milliseconds Vitest, Jest, Node's node:test
Integration several pieces together, such as a component plus its data layer fast Vitest/Jest + Testing Library
End-to-end (E2E) the whole app in a real browser, like a user would use it seconds Playwright, Cypress

Write lots of unit tests for logic, some integration tests for how parts connect, and a handful of E2E tests for the flows that must never break: signing up, checking out, saving work.

Real tools: Vitest and Jest

In a real project you'll install a test runner with npm (Tooling) instead of writing your own. Vitest and Jest share nearly the same API, so the tests look like this in either one:

JavaScript
// cart.test.js
import { describe, test, expect, vi } from "vitest"; // Jest provides these globally
import { checkoutTotal, sendReceipt } from "./cart.js";

describe("checkoutTotal", () => {
  test("applies 10% off orders over $100", () => {
    expect(checkoutTotal({ items: [{ price: 80 }, { price: 40 }] })).toBe(108);
  });

  test("keeps cents accurate", () => {
    expect(checkoutTotal({ items: [{ price: 0.1 }, { price: 0.2 }] })).toBeCloseTo(0.3);
  });
});

test("sends exactly one receipt", async () => {
  const mailer = { send: vi.fn() };                 // a spy (jest.fn() in Jest)
  await sendReceipt({ email: "[email protected]" }, mailer);
  expect(mailer.send).toHaveBeenCalledTimes(1);
  expect(mailer.send).toHaveBeenCalledWith("[email protected]", expect.any(String));
});

You run them from the terminal with npx vitest (which re-runs affected tests as you save) or npx jest. Both can measure coverage: which lines your tests actually executed. Coverage is a useful map of untested code, but 100% coverage doesn't mean the tests check the right things.

Jest in practice: setup, async tests and mocks

Jest is the most widely used JavaScript test runner, and a lot of existing projects (especially React and Node ones) use it. Here's what you need to start using it and what each part does. The code in this section is read-only because Jest needs Node and npm, but a runnable stand-in follows so you can see how the pieces work.

Setting up

Terminal
npm install --save-dev jest
JSON
{
  "scripts": { "test": "jest", "test:watch": "jest --watch", "coverage": "jest --coverage" }
}

Jest finds files named *.test.js or *.spec.js, and everything inside __tests__ folders. Running npm test runs them all in parallel workers, and npm run test:watch re-runs only the tests affected by the files you changed.

Jest transforms code before running it, which is how it historically handled import syntax: with Babel, configured in babel.config.js. Native ES modules ("type": "module" in package.json) work too, but Jest still marks that support as experimental and needs node --experimental-vm-modules to enable it. If you hit import errors, check the "ECMAScript Modules" page of the Jest docs for your version. Vitest, with its near-identical API, avoids this setup by supporting ES modules natively.

Matchers you will use every day

expect(value) returns an object of matchers, each checking one kind of thing:

Matcher Checks Example
toBe(x) Same value or reference (Object.is) expect(2 + 2).toBe(4)
toEqual(x) Deep equality of objects and arrays expect(user).toEqual({ id: 1, name: "Ada" })
toBeCloseTo(x, digits) Floating-point numbers expect(0.1 + 0.2).toBeCloseTo(0.3)
toContain(x) An item in an array or a substring expect(list).toContain("pear")
toMatch(regex) A string against a pattern expect(id).toMatch(/^user-\d+$/)
toThrow(msg) A function throws expect(() => parse("")).toThrow("empty")
toHaveBeenCalledWith(...) How a mock was called expect(send).toHaveBeenCalledWith("[email protected]")
.not Negates any matcher expect(list).not.toContain("kiwi")

Async tests

A test that finishes before its promise settles proves nothing: it passes while the assertion never runs. Jest gives you three safe ways to write async tests. They all make Jest wait.

JavaScript
// 1. async/await: the most readable
test("loads the user", async () => {
  const user = await loadUser(7);
  expect(user.name).toBe("Ada");
});

// 2. resolves / rejects matchers: return or await the expectation
test("rejects for unknown ids", async () => {
  await expect(loadUser(-1)).rejects.toThrow("not found");
  await expect(loadUser(7)).resolves.toMatchObject({ name: "Ada" });
});

// 3. count assertions, to make sure the catch block really ran
test("reports the error", async () => {
  expect.assertions(1);
  try {
    await loadUser(-1);
  } catch (error) {
    expect(error.message).toBe("not found");
  }
});

The classic mistake is forgetting await before expect(...).rejects: the test ends immediately, passes, and any failure shows up later as an unrelated error, or never. If a test passes suspiciously on the first try, use expect.assertions(n) to prove the checks ran.

Mocks, spies and module mocks

Jest includes the test doubles described earlier:

JavaScript
const send = jest.fn();                       // an empty spy
send.mockReturnValue(true);                   // always returns true
send.mockResolvedValue({ ok: true });         // returns a promise that resolves
send.mockRejectedValueOnce(new Error("x"));   // next call rejects, later calls don't

jest.spyOn(Math, "random").mockReturnValue(0.5);  // replace ONE method on a real object
jest.spyOn(console, "error").mockImplementation(() => {});  // silence expected errors

jest.spyOn() wraps a real method so you can watch it or replace it temporarily, and mockRestore() puts the original back. To replace a whole module, use jest.mock():

JavaScript
import { fetchUser } from "./api.js";
jest.mock("./api.js");                        // every export becomes a mock function

test("greets the user by name", async () => {
  fetchUser.mockResolvedValue({ name: "Ada" });
  expect(await greetUser(7)).toBe("Hello, Ada!");
  expect(fetchUser).toHaveBeenCalledWith(7);
});

Jest hoists jest.mock() calls to the top of the file so the mock exists before the real import runs. That's a feature of its Babel transform; with native ES modules you'd use jest.unstable_mockModule() instead.

Mocks remember calls between tests, so reset them: beforeEach(() => jest.clearAllMocks()) clears the call history, and setting restoreMocks: true in the Jest config restores spied methods automatically. Leaked mock state is the number one cause of tests that pass alone but fail in a group.

Fake timers

Code with setTimeout, setInterval or debouncing would make tests slow if they had to wait for real time. Fake timers replace the clock with one you control:

JavaScript
test("debounce waits 300 ms", () => {
  jest.useFakeTimers();
  const onSearch = jest.fn();
  const search = debounce(onSearch, 300);

  search("a"); search("ab"); search("abc");
  jest.advanceTimersByTime(299);
  expect(onSearch).not.toHaveBeenCalled();

  jest.advanceTimersByTime(1);
  expect(onSearch).toHaveBeenCalledTimes(1);
  expect(onSearch).toHaveBeenCalledWith("abc");

  jest.useRealTimers();
});

A test double this small is easy to build yourself. The editor below defines a miniature fn() with mockResolvedValue, mockRejectedValue and mockImplementationOnce, plus a fake scheduler with advanceTimersByTime(), and uses them to test the same two ideas. Reading how little code is behind jest.fn() takes away most of the mystery.

JS A tiny jest.fn() and fake timers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real Jest does the same thing globally: jest.useFakeTimers() swaps out setTimeout, setInterval and Date, so your code needs no changes. The version here takes the timers as a parameter, which is the dependency injection idea from earlier in this lesson.

Jest or Vitest?

For a new project built on Vite, Vitest is usually the smoother choice: same matchers and nearly the same mocking API (vi.fn(), vi.spyOn(), vi.mock()), but faster and ES-module-native. For an existing codebase, or one that uses React Native or older tooling, Jest is already there and well supported. What you learned above transfers directly: the tests differ mostly in jest. versus vi. and in where the describe, test and expect functions come from. See also Best Practices for how to keep a test suite healthy.

End-to-end tests with Playwright

E2E tools drive a real browser: they open your site, click buttons, type into fields and check what appears. A Playwright test reads almost like instructions to a person:

JavaScript
// signup.spec.js
import { test, expect } from "@playwright/test";

test("a visitor can subscribe to the newsletter", async ({ page }) => {
  await page.goto("http://localhost:5173/");
  await page.getByLabel("Email").fill("[email protected]");
  await page.getByRole("button", { name: "Subscribe" }).click();
  await expect(page.getByText("Thanks for subscribing")).toBeVisible();
});

Finding elements by label and role, the way a user would, makes E2E tests sturdier and doubles as a basic accessibility check.

Test-driven development (TDD) flips the order: write a failing test first, write just enough code to pass it, then clean up the code while the test keeps you safe ("red, green, refactor"). Even if you don't follow TDD strictly, writing a failing test before fixing a bug proves your fix actually works.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What are the three parts of the arrange-act-assert pattern?

    Arrange prepares the data, act runs the one behavior you're testing, and assert compares the outcome with your expectation.
  2. 2. Why does expect(() => parse(input)).toThrow() pass a function instead of expect(parse(input))?

    Arguments are evaluated before a function is called, so the error would escape the test. Wrapping the call lets the matcher run it inside try...catch.
  3. 3. Which assertion is right for checking that a function returns the array [1, 2]?

    Two separate arrays are never strictly equal. toEqual() compares contents, while toBe() checks identity.
  4. 4. Your function calls fetch and Date.now(). What makes it easiest to unit test?

    Dependency injection lets tests swap slow or unpredictable parts for stubs and spies, keeping tests fast and repeatable.
  5. 5. Which kind of test should you usually have the most of?

    Unit tests are fast, precise and cheap to maintain, so they form the base of the testing pyramid. E2E tests are valuable but slower and more fragile.

Summary

  • A test runs code and asserts on the result; test runners collect tests, isolate failures and report.
  • Use toBe() for primitives and identity, toEqual() for structure, and pass a function to toThrow().
  • Structure tests as arrange, act, assert; test one behavior, name it clearly, and cover edge cases.
  • Replace network, time and randomness with stubs, fakes and spies โ€” dependency injection makes this easy.
  • In Jest, make async tests wait (await, .resolves/.rejects, expect.assertions), reset mocks between tests, use jest.fn(), jest.spyOn(), jest.mock() and fake timers.
  • Build a pyramid: many unit tests (Vitest, Jest), some integration tests, a few E2E tests (Playwright).

Next: Best Practices and Common Mistakes โ€” habits that keep JavaScript readable and the bugs almost everyone writes at least once.