Software Development

Unit vs Integration vs End-to-End Testing Explained

December 3, 2026 · 12 min read

Unit vs Integration vs End-to-End Testing Explained

Every team agrees that software needs tests. The harder questions are which tests, and how many of each. The answer usually comes down to three levels: unit tests check one small piece of logic in isolation, integration tests check that pieces work together, and end-to-end tests drive the whole application the way a user would. The unit vs integration testing debate matters because each level catches different bugs at a different cost, and the right mix is what makes a test suite fast, trustworthy and cheap to maintain.

The tools have changed quickly. In the State of JavaScript 2025 survey, Vitest and Playwright showed the biggest year-on-year growth in usage of any tools in the survey, while Jest remains the most widely used test runner. This guide explains each level with tested JavaScript examples built on a small shopping-basket API, compares them side by side, and shows how to balance them in continuous integration.

The Three Levels at a Glance

Unit testsIntegration testsEnd-to-end tests
What they testOne function or class in isolationSeveral parts together: code, database, HTTP, queuesThe whole system through the user interface
SpeedMillisecondsMilliseconds to secondsSeconds to minutes
What they catchLogic errors and edge casesWiring, configuration, queries and contract mismatchesBroken user journeys and environment problems
When they failPoints straight at the problemNarrows it to a few componentsSays something is wrong, somewhere
Maintenance costLowMediumHighest; prone to flakiness
Typical toolsVitest, Jest, node:test, pytest, JUnitThe same runners plus Supertest, Testcontainers, MSWPlaywright, Cypress, Selenium

What Is Unit Testing?

A unit test checks a small, self-contained piece of code, usually a single function, with no network, database or file system involved. Here is the pricing logic for our example shop. It is a pure function: the same input always gives the same output, which makes it ideal for unit testing:

// pricing.mjs: pure business rules, no I/O (perfect for unit tests)
const COUPONS = { WELCOME10: 0.1, VIP20: 0.2 };

export function quote(lines, couponCode) {
  if (lines.length === 0) throw new Error("Basket is empty");
  const subtotal = lines.reduce((sum, line) => sum + line.unitPrice * line.quantity, 0);
  const rate = COUPONS[couponCode?.toUpperCase()] ?? 0;
  const discount = Math.round(subtotal * rate * 100) / 100;
  return { subtotal, discount, total: Math.round((subtotal - discount) * 100) / 100 };
}

The unit tests cover the normal case, an edge case and an error case. They run in a few milliseconds, so developers can run them on every save:

// pricing.test.mjs: unit tests, fast and isolated (no network, no database)
import { test } from "node:test";
import assert from "node:assert/strict";
import { quote } from "./pricing.mjs";

test("adds up line totals", () => {
  assert.deepEqual(quote([{ unitPrice: 8.5, quantity: 2 }], undefined), { subtotal: 17, discount: 0, total: 17 });
});
test("applies a coupon, ignoring case", () => {
  assert.equal(quote([{ unitPrice: 15, quantity: 2 }], "welcome10").total, 27);
});
test("rejects an empty basket", () => {
  assert.throws(() => quote([], "VIP20"), /Basket is empty/);
});

Good unit tests are fast, independent of each other and focused on behaviour rather than implementation details. If renaming a private variable breaks a test, the test is checking the wrong thing.

What Is Integration Testing?

Integration tests check that components work together correctly. Most production bugs live in the seams: a misspelt column name, a missing header, a route that parses JSON differently from what the client sends. Here is the API that connects the pricing logic to an HTTP endpoint and a database, here an in-memory SQLite database through Node.js's built-in node:sqlite module, which is still marked experimental in Node.js 22:

// server.mjs: HTTP API + database, wired together (what integration tests check)
import http from "node:http";
import { DatabaseSync } from "node:sqlite";
import { quote } from "./pricing.mjs";

export function createDatabase() {
  const db = new DatabaseSync(":memory:");
  db.exec(`CREATE TABLE products (sku TEXT PRIMARY KEY, name TEXT, price REAL);
           INSERT INTO products VALUES ('MUG', 'Coffee mug', 8.5), ('TEE', 'T-shirt', 15);`);
  return db;
}

export function createServer(db) {
  const findPrice = db.prepare("SELECT price FROM products WHERE sku = ?");
  return http.createServer(async (req, res) => {
    const send = (status, body) => {
      res.writeHead(status, { "content-type": "application/json" });
      res.end(JSON.stringify(body));
    };
    if (req.method !== "POST" || req.url !== "/api/quote") return send(404, { error: "Not found" });
    let body = "";
    for await (const chunk of req) body += chunk;
    try {
      const { items, coupon } = JSON.parse(body);
      const lines = items.map(({ sku, quantity }) => {
        const row = findPrice.get(sku);
        if (!row) throw new Error(`Unknown product: ${sku}`);
        return { unitPrice: row.price, quantity };
      });
      send(200, quote(lines, coupon));
    } catch (err) {
      send(400, { error: err.message });
    }
  });
}

The integration tests start a real server on a free port, send real HTTP requests and check real responses, including the error path:

// api.test.mjs: integration tests, a real HTTP server and a real (in-memory) database
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import { createServer, createDatabase } from "./server.mjs";

let server, baseUrl;
before(async () => {
  server = createServer(createDatabase());
  await new Promise((resolve) => server.listen(0, resolve));       // port 0 = any free port
  baseUrl = `http://127.0.0.1:${server.address().port}`;
});
after(() => server.close());

const post = (body) =>
  fetch(`${baseUrl}/api/quote`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });

test("POST /api/quote prices items from the database", async () => {
  const res = await post({ items: [{ sku: "MUG", quantity: 2 }, { sku: "TEE", quantity: 1 }], coupon: "VIP20" });
  assert.equal(res.status, 200);
  assert.deepEqual(await res.json(), { subtotal: 32, discount: 6.4, total: 25.6 });
});
test("POST /api/quote returns 400 for an unknown product", async () => {
  const res = await post({ items: [{ sku: "HAT", quantity: 1 }] });
  assert.equal(res.status, 400);
  assert.match((await res.json()).error, /Unknown product: HAT/);
});

Notice what these tests catch that the unit tests cannot: the route path, JSON parsing, the SQL query, the database contents, the status codes and the response format. For production databases, tools such as Testcontainers start a real PostgreSQL or MySQL instance in Docker for each test run, so integration tests exercise exactly the database engine you deploy. Our Node.js REST API guide shows the same approach for a full API.

Running Unit and Integration Tests Together

Node.js's built-in test runner finds both files and runs them, with no extra dependencies:

$ node --test
✔ POST /api/quote prices items from the database
✔ POST /api/quote returns 400 for an unknown product
✔ adds up line totals
✔ applies a coupon, ignoring case
✔ rejects an empty basket
ℹ tests 5
ℹ pass 5
ℹ fail 0

All five tests pass in well under a second. That speed matters: a suite developers can run constantly gets run constantly, and problems are found minutes after they are introduced rather than days later.

What Is End-to-End Testing?

End-to-end (E2E) tests drive the complete application in a real browser or device, exactly as a user would: clicking buttons, filling in forms and checking what appears on screen. This Playwright test checks the most important journey in our shop, applying a coupon at checkout:

// checkout.spec.mjs: an end-to-end test drives a real browser through the running app (Playwright)
import { test, expect } from "@playwright/test";

test("a shopper can apply a coupon and see the discounted total", async ({ page }) => {
  await page.goto("http://localhost:3000/basket");
  await page.getByRole("button", { name: "Add T-shirt" }).click();
  await page.getByLabel("Coupon code").fill("WELCOME10");
  await page.getByRole("button", { name: "Apply" }).click();
  await expect(page.getByTestId("order-total")).toHaveText("£13.50");
});

E2E tests give the most confidence, because they exercise the front end, back end, database and configuration together. They are also the slowest and most fragile: animations, network timing and test data can all cause intermittent failures. Keep them for critical journeys such as sign-up, checkout and payment, and use stable selectors based on roles, labels and test IDs, as the example does. When a test does fail, Playwright can record a trace with screenshots, network calls and console output, which turns a vague "it failed in CI" into a specific, reproducible problem. For apps on phones and tablets, our mobile app testing guide covers device-specific tools.

Unit vs Integration Testing: The Key Differences

  • Isolation: unit tests replace collaborators with fakes or avoid them entirely; integration tests use the real thing, or a close copy such as a test database.
  • Confidence: passing unit tests prove the logic is right; passing integration tests prove the parts are connected correctly. You need both.
  • Diagnosis: a failing unit test points to one function. A failing integration test tells you which conversation between components broke.
  • Mocks: heavy mocking in unit tests can hide integration bugs, because the mock behaves the way you assumed, not the way the real dependency behaves.
  • Cost: unit tests are cheapest to write and run; integration tests need set-up such as databases, ports and test data.

Which Test Catches Which Bug?

Thinking about real bugs makes the differences concrete. Here is how each level would fare against four problems that could hit our shop:

BugUnit testIntegration testEnd-to-end test
Coupon applies 20% instead of 10%Catches it, and points to the lineCatches itCatches it, slowly
A database column is renamed but the query is notMisses itCatches itCatches it
The front end sends qty instead of quantityMisses itMisses it unless the client is tested tooCatches it
Production is missing an environment variableMisses itMisses itCatches it if run against that environment

No single level catches everything, which is why a healthy suite combines them, with each bug caught by the cheapest test able to catch it.

Other Kinds of Tests Worth Knowing

  • Static analysis: type checkers and linters catch whole classes of bugs before any test runs.
  • Component tests: render a single UI component with realistic inputs, a middle ground between unit and E2E tests for front-end code.
  • Contract tests: tools such as Pact check that a service and its consumers agree on request and response formats, which is especially valuable with microservices.
  • Smoke tests: a handful of quick checks after each deployment confirm the system is alive.
  • Performance and security tests: load tests show how the system behaves under stress, and security scans look for known vulnerabilities.

Pyramid, Trophy or Something Else?

The classic test pyramid, introduced by Mike Cohn in his book Succeeding with Agile, recommends many unit tests, fewer integration tests and a small number of end-to-end tests. Kent C. Dodds later proposed the testing trophy, inspired by Guillermo Rauch's advice to write tests, not too many, mostly integration, arguing that modern tools make integration tests fast enough to deliver the best confidence for the cost. Google's web.dev team summarises these and other shapes in its guide to test strategies.

The honest answer is that the right shape depends on your system. Libraries and algorithm-heavy code benefit from lots of unit tests. CRUD-style web apps, where most bugs live in the wiring, benefit from more integration tests. Almost everyone should keep E2E tests few and focused.

Testing in Your CI Pipeline

Tests deliver value when they run automatically. A practical set-up runs unit and integration tests on every pull request, blocks merging when they fail, and runs the slower E2E suite before deployment or in a merge queue. Our guides to CI/CD and GitHub Actions show how to wire this up, and our comparison of Git branching strategies explains why fast, reliable tests are what make short-lived branches and frequent merging safe.

Reviewers should read tests as carefully as production code: a pull request with no tests, or with tests that only check the happy path, deserves a question. Our guide to code review best practices includes a checklist.

Common Testing Mistakes

  • Testing implementation details, so every refactor breaks tests that should have passed.
  • Mocking everything, which produces green tests and broken software.
  • Too many end-to-end tests, making the suite slow and flaky until people ignore failures.
  • Chasing 100% coverage instead of covering the risky paths: money, permissions and data changes.
  • Shared test data that makes tests depend on the order they run in.
  • Writing tests last, when the design is already hard to test. Writing them first, as in test-driven development, keeps code testable, and the habits in our guide to clean code keep tests readable.

Frequently Asked Questions

What is the difference between unit and integration testing?

Unit tests check a single piece of logic in isolation, without databases or networks. Integration tests check that several components, such as an API, its database and its configuration, work correctly together.

What is end-to-end testing?

End-to-end testing drives the complete application through its user interface, the way a real user would, to verify that critical journeys such as sign-up and checkout work across every layer.

How many unit, integration and E2E tests should I write?

There is no fixed ratio. Many teams aim for lots of fast unit and integration tests and a small set of E2E tests for critical journeys, adjusting the balance to where their bugs actually occur.

Should integration tests use a real database?

Where practical, yes. Using the same database engine as production, often started in Docker with Testcontainers, catches query and schema problems that mocks and in-memory substitutes can miss.

What are the best testing tools for JavaScript in 2026?

Vitest, Jest and Node's built-in test runner are popular for unit and integration tests, and Playwright and Cypress for end-to-end tests. Vitest and Playwright saw the fastest growth in the State of JavaScript 2025 survey.

Why are end-to-end tests flaky?

They depend on many moving parts, including timing, animations, networks and shared test data. Waiting for conditions instead of fixed delays, using stable selectors and isolating test data make them far more reliable.

Build Software You Can Change with Confidence

We set up test strategies that balance unit vs integration testing and end-to-end coverage, wire them into CI and help teams ship web and mobile apps faster with fewer regressions. Talk to us about improving your test suite.

Want this built for you?

Our team offers Website Deploy On Vercel — get a free quote.

View Services