Skip to content
Happy Programming Guide
Start learning
JavaScript

JavaScript Testing

Unit tests with Vitest, mocking, testing DOM code and async functions, and end-to-end tests with Playwright — plus what is actually worth testing.

A home office desk with a computer

A test is a small program that runs part of your code and checks the answer. In JavaScript that means Vitest or Jest for unit tests, Testing Library for anything touching the DOM, and Playwright for driving a real browser. This guide covers all three layers and, more importantly, how to decide what deserves a test.

Setting up#

Terminal
npm install --save-dev vitest
JSON
{
  "scripts": {
    "test": "vitest",
    "test:run": "vitest run",
    "test:coverage": "vitest run --coverage"
  }
}

Vitest works with ES modules out of the box and reuses your Vite configuration, which removes most of the setup that made Jest awkward in modern projects. Its API is close enough to Jest that most examples translate directly.

A first test#

JavaScript
// src/discount.js
export function applyDiscount(price, percent) {
  if (percent < 0 || percent > 100) {
    throw new RangeError("percent must be between 0 and 100");
  }
  return Math.round(price * (100 - percent)) / 100;
}
JavaScript
// src/discount.test.js
import { describe, it, expect } from "vitest";
import { applyDiscount } from "./discount";

describe("applyDiscount", () => {
  it("reduces the price by the given percentage", () => {
    // arrange
    const price = 100;

    // act
    const result = applyDiscount(price, 20);

    // assert
    expect(result).toBe(80);
  });

  it("rejects a percentage above 100", () => {
    expect(() => applyDiscount(100, 150)).toThrow(RangeError);
  });

  it("leaves the price unchanged at zero per cent", () => {
    expect(applyDiscount(19.99, 0)).toBe(19.99);
  });
});

The three-part shape is not decoration. Keeping setup, action and assertion visually separate makes a failing test readable a year later, when you have forgotten everything about it.

Table-driven tests#

JavaScript
it.each([
  [100, 0, 100],
  [100, 50, 50],
  [100, 100, 0],
  [19.99, 10, 17.99],
])("applyDiscount(%d, %d) returns %d", (price, percent, expected) => {
  expect(applyDiscount(price, percent)).toBe(expected);
});

Each row reports separately, so a failure tells you exactly which combination broke rather than just that something did.

The assertions you will use#

JavaScript
expect(value).toBe(3);                  // Object.is - for primitives
expect(object).toEqual({ a: 1 });       // deep equality
expect(array).toContain("item");
expect(array).toHaveLength(3);
expect(value).toBeNull();
expect(value).toBeUndefined();
expect(value).toBeTruthy();
expect(0.1 + 0.2).toBeCloseTo(0.3);     // floating point
expect(fn).toThrow("message");
await expect(promise).rejects.toThrow();
expect(spy).toHaveBeenCalledWith("a", 1);

Mocking#

JavaScript
import { vi, it, expect } from "vitest";

// A standalone function
const onSave = vi.fn();
onSave("draft");

expect(onSave).toHaveBeenCalledOnce();
expect(onSave).toHaveBeenCalledWith("draft");
JavaScript
// A whole module
vi.mock("./api", () => ({
  fetchUser: vi.fn(async (id) => ({ id, name: "Ana" })),
}));

import { fetchUser } from "./api";
import { getGreeting } from "./greeting";

it("greets the fetched user", async () => {
  expect(await getGreeting(1)).toBe("Hello, Ana");
  expect(fetchUser).toHaveBeenCalledWith(1);
});
JavaScript
// Timers
it("debounces", () => {
  vi.useFakeTimers();

  const fn = vi.fn();
  const debounced = debounce(fn, 500);

  debounced();
  debounced();
  expect(fn).not.toHaveBeenCalled();

  vi.advanceTimersByTime(500);
  expect(fn).toHaveBeenCalledOnce();

  vi.useRealTimers();
});

Fake timers turn a test that would take half a second into one that takes nothing, and they make timing deterministic. Always restore real timers afterwards, or later tests inherit the fake ones.

Network requests#

Terminal
npm install --save-dev msw
JavaScript
import { setupServer } from "msw/node";
import { http, HttpResponse } from "msw";
import { beforeAll, afterEach, afterAll, it, expect } from "vitest";

const server = setupServer(
  http.get("/api/products", () =>
    HttpResponse.json([{ id: 1, name: "Pen" }])),
);

beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

it("loads products", async () => {
  const products = await loadProducts();
  expect(products).toHaveLength(1);
});

it("handles a server error", async () => {
  server.use(
    http.get("/api/products", () => new HttpResponse(null, { status: 500 })),
  );

  await expect(loadProducts()).rejects.toThrow("Request failed");
});

Intercepting at the network level rather than mocking fetch means you are testing your real request code, including the response.ok check that people forget.

Testing DOM code#

Terminal
npm install --save-dev @testing-library/dom @testing-library/user-event jsdom
JavaScript
// vitest.config.js
export default { test: { environment: "jsdom" } };
JavaScript
import { screen, within } from "@testing-library/dom";
import userEvent from "@testing-library/user-event";
import { beforeEach, it, expect } from "vitest";
import { mountTodoList } from "./todo";

beforeEach(() => {
  document.body.innerHTML = '<div id="app"></div>';
  mountTodoList(document.querySelector("#app"));
});

it("adds an item and clears the field", async () => {
  const user = userEvent.setup();

  await user.type(screen.getByLabelText("New task"), "Buy milk");
  await user.click(screen.getByRole("button", { name: "Add" }));

  expect(screen.getByRole("listitem")).toHaveTextContent("Buy milk");
  expect(screen.getByLabelText("New task")).toHaveValue("");
});

Async code#

JavaScript
it("resolves with the data", async () => {
  await expect(loadUser(1)).resolves.toEqual({ id: 1, name: "Ana" });
});

it("rejects on a missing user", async () => {
  await expect(loadUser(999)).rejects.toThrow("Not found");
});

it("waits for the element to appear", async () => {
  render();
  expect(await screen.findByText("Loaded")).toBeInTheDocument();
});

Forgetting the await on an assertion is the classic async testing bug: the test finishes before the check runs and passes regardless. Vitest and Jest both warn about it, and it is worth reading those warnings.

End-to-end tests#

Terminal
npm init playwright@latest
JavaScript
import { test, expect } from "@playwright/test";

test("a visitor can add a product to the basket", async ({ page }) => {
  await page.goto("/products");

  await page.getByRole("link", { name: "Fountain pen" }).click();
  await page.getByRole("button", { name: "Add to basket" }).click();

  await expect(page.getByTestId("basket-count")).toHaveText("1");
  await expect(page.getByRole("alert")).toContainText("Added");
});

These run a real browser against a real application, so they catch things unit tests cannot — a broken route, a missing element, a CSS change that hides a button. They are also slow and more prone to flakiness, so keep them few and focused on the journeys that matter most: sign in, checkout, the main task your application exists for.

What to test#

Worth testing: business rules and calculations, validation, edge cases and boundaries, anything you have already had to fix once, and every bug you fix — write the failing test first, then make it pass.

Not worth testing: that a library works, that a getter returns what you set, styling, or implementation details such as which internal function was called.

JavaScript
// Tests an implementation detail - breaks on any refactor
expect(component.internalHelper).toHaveBeenCalled();

// Tests behaviour - survives refactoring
expect(screen.getByRole("alert")).toHaveTextContent("Saved");

The shape of a healthy suite#

Many fast unit tests, fewer integration tests, and a handful of end-to-end tests. The ratio matters because of feedback speed: a unit suite you can run on every save changes how you work, and one that takes four minutes does not get run.

Terminal
npx vitest --watch          # runs affected tests as you save
npx vitest run --coverage
npx playwright test --ui    # step through an end-to-end run

Questions people ask#

Vitest or Jest?

Vitest for new projects — native ES module support, much faster, and almost no configuration if you already use Vite. Jest remains fine in established codebases and has the larger body of existing material.

Should I write tests first?

Test-driven development works well when you can state the expected result up front — calculations, validation, parsing. It is more awkward for exploratory interface work. Writing the test first for every bug fix is valuable regardless.

How do I test something that uses the current date?

Inject the clock, or freeze it with vi.setSystemTime(new Date("2026-01-01")). A test whose result depends on when it runs will eventually fail for no reason.

What is a flaky test?

One that passes and fails without the code changing — usually a timing assumption, a shared fixture, or a real network call. Fix it or delete it; a test nobody trusts is worse than none.

Where to go next#

JavaScript habits that make code easy to testRead next

Keep reading

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *