Skip to content

No. 28Frontend8 min read2,048 words

A testing strategy: for web apps that actually pays off

A practical testing strategy for web apps: what to unit test, where integration tests catch real bugs, how few end-to-end tests you need, and what to skip.

Written by
Lazy Devs
Published
Updated
Sources
Cited inline

Key takeaways · 05

The short version

  1. 01Judge a test suite by confidence, not coverage: a red build should mean something a user cares about is broken, and a green build should mean you can ship.
  2. 02Unit test pure logic that branches (pricing, permissions, date math, parsers). Integration test the seams with a real test database. Keep end-to-end tests to the handful of flows that make or lose money.
  3. 03Integration tests against real infrastructure find more real bugs per test than mocked unit tests, because most production bugs live where your code meets the database, an API or an auth boundary.
  4. 04A flaky test is worse than no test. Control time, randomness, network and shared state, and fix or delete any test that fails intermittently.
  5. 05Run end-to-end tests against a production build, not the dev server, and keep the whole suite fast enough that nobody is tempted to skip it.
On this page · 07

A testing strategy that pays off is a small, layered suite: unit tests for logic that makes decisions, integration tests at the seams where your code meets a database or API, and a handful of end-to-end tests for the flows that make or lose money. It runs fast, rarely flakes, and when it goes red, something real is broken. That trust, not a coverage number, is the return on the investment.

Most codebases we inherit have one of two testing problems. Either there are almost no tests and the team ships with fingers crossed, or there are thousands of tests, a slow CI pipeline, and production still breaks in ways the suite never noticed. Both teams are paying for testing without getting what they actually want: the freedom to change code without fear.

Stop counting coverage, start counting confidence

Coverage percentage is the most overrated metric in testing. A line being executed during a test run tells you nothing about whether you asserted anything useful about it. You can reach high coverage with tests that would pass even if the function returned garbage.

The better question is: when this test fails, do you learn something true about your system? If a test breaks every time you rename a variable or restructure a component, it is testing your implementation, not your behaviour. Those tests are a liability. They make refactoring expensive, which is exactly what testing was supposed to make cheap.

The Testing Library project puts the principle well in its guiding principles: the more your tests resemble the way your software is used, the more confidence they can give you. A red build should mean "something a user cares about is broken," and a green build should mean "you can ship."

Coverage is still useful as a flashlight. Run it occasionally and look for critical code, payments, permissions, data deletion, that no test touches at all. Just do not turn it into a target.

The three test layers, and what each is for

You will have seen the test pyramid: many fast unit tests at the bottom, fewer integration tests in the middle, very few end-to-end tests at the top. It is a reasonable starting shape. For most web apps we tilt it slightly, putting more weight on integration tests, because that is where web app bugs actually live.

LayerWhat it testsSpeedTypical toolsSpend your effort on
StaticTypes, lint rulesInstantTypeScript, ESLintCatching whole classes of bugs for free
UnitOne function or component in isolationMillisecondsVitest, React Testing LibraryLogic that branches
IntegrationSeveral parts together, real databaseTens to hundreds of msVitest plus a disposable PostgresAPI routes, queries, auth checks
End-to-endThe whole app through a real browserSeconds per testPlaywrightThe flows that make or lose money

Do not skip the static layer. A strict TypeScript config catches an entire category of null and shape errors before a single test runs.

Unit tests for logic that branches

Pure functions with real branching logic are the cheapest, most valuable tests you will write: pricing rules, date math, permission checks, parsers, anything where the output depends on tricky input. No mocks, no setup, just input and output. Vitest is our default runner: it is fast, TypeScript-native and compatible with most Jest APIs.

// lib/pricing.ts
export function applyDiscount(
  cents: number,
  code: "WELCOME10" | "HALFOFF" | null,
): number {
  if (cents <= 0) throw new Error("price must be positive");
  switch (code) {
    case "WELCOME10":
      return Math.round(cents * 0.9);
    case "HALFOFF":
      return Math.round(cents * 0.5);
    default:
      return cents;
  }
}
// lib/pricing.test.ts
import { describe, it, expect } from "vitest";
import { applyDiscount } from "./pricing";
 
describe("applyDiscount", () => {
  it("rounds the WELCOME10 discount instead of leaving fractional cents", () => {
    // 1999 * 0.9 = 1799.1, which must not become a fractional value
    expect(applyDiscount(1999, "WELCOME10")).toBe(1799);
  });
 
  it("returns the original price when no code is given", () => {
    expect(applyDiscount(1999, null)).toBe(1999);
  });
 
  it("rejects non-positive prices", () => {
    expect(() => applyDiscount(0, "HALFOFF")).toThrow("price must be positive");
  });
});

Notice the first and last cases. The rounding bug and the zero-price guard are the kind of things that ship silently and show up as a confused support ticket weeks later. That is the test paying for itself.

For components, test behaviour the way a user experiences it: find elements by role and label, click, type, and assert on what appears. Testing Library's query priority pushes you towards getByRole and getByLabelText, which has a useful side effect: if a test cannot find your button by its role and name, a screen reader cannot either. That overlap is one of the reasons accessible code is easier to test, as we cover in our 80/20 accessibility guide.

One Next.js-specific caveat: the Next.js Vitest guide notes that Vitest does not currently support async Server Components. Unit test the logic those components call, and cover the rendered result with end-to-end tests.

Integration tests for the seams

This is where most bugs hide and where most teams under-invest. The seams are the places where your code meets something you do not fully control: the database, an API route, an auth boundary, a third-party service. A unit test with a mocked Postgres client proves your mock works. An integration test against a real database proves your query, your constraints and your migrations work.

For a Next.js route handler, call the handler directly against a disposable test database. A Postgres container started with Testcontainers or in your CI service config gives you the real engine, isolated per run.

// app/api/orders/route.test.ts
import { describe, it, expect, beforeEach, vi } from "vitest";
import { resetDb, seedUser } from "@/test/db";
 
// Replace only the session lookup; everything else is real.
const getSession = vi.hoisted(() => vi.fn());
vi.mock("@/lib/auth", () => ({ getSession }));
 
import { POST } from "./route";
 
beforeEach(async () => {
  await resetDb();
});
 
describe("POST /api/orders", () => {
  it("rejects a pro-only product for a user on the free plan", async () => {
    const user = await seedUser({ plan: "free" });
    getSession.mockResolvedValue({ userId: user.id });
 
    const res = await POST(
      new Request("http://test/api/orders", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ productId: "pro-only-sku", quantity: 1 }),
      }),
    );
 
    expect(res.status).toBe(403);
    const body = await res.json();
    expect(body.error).toMatch(/upgrade/i);
  });
});

This single test exercises request parsing, the authorization check, the database lookup and the error response. If any of those break, you find out here. That is a better return than four separate mocked unit tests that each assume the other three work. The only thing mocked is the session, because how a user logs in is not what this test is about.

For third-party HTTP APIs you cannot run locally, mock at the network boundary rather than inside your code. Mock Service Worker intercepts requests so your real client code, serialization and error handling still run. For payments, use your provider's test mode and replay real webhook payloads; webhook handling is a seam that breaks more often than people expect.

A few end-to-end tests for the money paths

End-to-end tests are slow and the most prone to flakiness, so you want few of them, and they should only cover paths where a failure means lost revenue or a locked-out user: sign up, log in, checkout or billing, and the one core action your product exists to do. If you have dozens of these, some of them are testing logic that belongs in a faster layer.

Run them with Playwright against a production build, not the dev server. The dev server compiles on demand and behaves differently, so a passing dev-server test can hide a production break.

// playwright.config.ts
import { defineConfig } from "@playwright/test";
 
export default defineConfig({
  testDir: "e2e",
  use: { baseURL: "http://localhost:3000" },
  webServer: {
    command: "npm run build && npm run start",
    url: "http://localhost:3000",
    reuseExistingServer: !process.env.CI,
    timeout: 180_000,
  },
});

End-to-end tests are also the natural place for a few high-value automated checks that do not fit elsewhere: an accessibility scan with axe on key pages, a check that structured data parses, and, after a migration, a test that every old URL still redirects where it should.

Make tests deterministic or delete them

A flaky test is worse than no test. It trains your team to hit "re-run" without thinking, and the day a real bug shows up as a red build, everyone assumes it is the flake again.

The usual culprits, and their fixes:

Source of flakinessSymptomFix
TimeFails near midnight, month end or in another timezoneFreeze the clock with vi.useFakeTimers() and vi.setSystemTime(); set TZ in CI
RandomnessFails one run in fiftySeed random sources or inject them
NetworkFails when a third party is slowMock at the network boundary with MSW
Shared statePasses alone, fails in the full suiteReset the database before each test; never rely on another test's data
Timing in the browserFails on slower CI machinesUse Playwright's auto-waiting assertions, never fixed sleeps
Order dependenceFails when tests run in parallelIsolate data per test, for example unique IDs per run

If a test fails once in fifty runs, it is broken. Fix the determinism or remove it. Retries in CI can buy time while you investigate, but a test that only passes on retry is hiding a problem, sometimes a real race condition in your product.

What to test, and what to skip

Skip tests for thin glue code. A component that takes props and renders them with no logic does not need a test. A config object does not need a test. A wrapper that forwards a call to a library you trust does not need a test. Testing these adds maintenance with no payoff.

Spend on anything that decides:

  • Money: prices, discounts, taxes, proration, refunds, currency rounding.
  • Permissions: who can see and change what, especially across tenants in a multi-tenant app.
  • Data integrity: migrations, constraints, deduplication, anything that deletes.
  • Anything irreversible: emails sent, charges made, records shared externally.
  • Bugs you have already had: every production bug gets a regression test before the fix ships.

A bad render is annoying. A wrong charge or a leaked record is a real problem, and that is exactly where a single sharp test buys you a lot of sleep.

How to add tests to a codebase that has none

When we take over a project with no tests, we do not stop feature work to write hundreds of them. We do it in this order:

  1. Turn on the static layer. Strict TypeScript and lint rules in CI, fixing errors as files are touched.
  2. Add end-to-end smoke tests for the three to five flows that make money. They protect you while you refactor everything underneath.
  3. Add integration tests around the scariest seams, usually payments, auth and anything multi-tenant.
  4. Write a regression test with every bug fix from now on.
  5. Extract and unit test the logic you find buried in components and route handlers as you touch it.

Within a few weeks of normal work, the most important parts of the codebase are covered, and the suite grew where the risk was. This is a core part of how we approach rescuing a stalled or inherited project, and it is one of the cheapest ways to start paying down technical debt.

The payoff, concretely

A suite built this way stays small relative to the codebase, and it runs in a few minutes because the slow end-to-end layer is tiny and the rest runs in parallel. When it goes red, it is almost always a real bug, so people trust it. When it is green, people ship without a meeting about it. That trust is the entire return on investment. Everything else is bookkeeping.

So do not chase coverage. Build a layered suite that tests behaviour at the seams where bugs live, keep it deterministic, and aim every test at code that makes a decision. A test you trust is worth fifty you ignore.

Every app we build under our web app development and maintenance and support work ships with a suite like this. If yours has stopped paying off, or never existed, let's talk.

Flags let you test in production safely; see our roundup of the best feature flag tools.

FAQ · 05 questions

Frequently asked questions

What percentage of code coverage should we aim for?

There is no number that guarantees quality. Coverage only tells you which lines ran during tests, not whether anything useful was asserted about them. Use coverage to spot untested critical code such as payments and permissions, and do not set a team-wide percentage target that encourages low-value tests.

What is the difference between unit, integration and end-to-end tests?

A unit test checks a single function or component in isolation. An integration test checks several parts working together, such as an API route with a real database. An end-to-end test drives the whole application through a browser the way a user would. Each layer is slower and more realistic than the one before it.

Should we mock the database in tests?

For logic tests, keep the database out entirely by testing pure functions. For anything that runs queries, prefer a real disposable database, such as a Postgres container, over a mock. A mocked database proves your mock behaves as you expected, not that your SQL, constraints and migrations actually work.

How many end-to-end tests does a web app need?

Usually a small number, often around a dozen, covering sign-up, login, checkout or billing, and the core action your product exists for. If you have many more, some of them are probably testing logic that belongs in faster unit or integration tests.

Which testing tools should a Next.js project use?

A common, well-supported setup is Vitest with React Testing Library for unit and component tests, a disposable Postgres database for integration tests, and Playwright for end-to-end tests. Next.js documents setups for Vitest, Jest, Playwright and Cypress.

Related service

Web App Development

Production React and Next.js apps, built to last.

Learn more

Next step

Want this built right?

This is the work we do every day. Tell us what you are building and we will show you exactly how we would ship it.

First reply
Within 1 business day
Typical start
1–2 weeks
Pricing
Fixed price per phase
You own
All code and accounts