Unit vs Integration vs End-to-End Tests
Compare unit, integration and end-to-end tests with one JavaScript feature tested at each level: scope, speed, dependencies and what each catches.

The words unit, integration and end-to-end are used loosely, and teams spend hours arguing about what counts as which. The useful distinction is not the name but the scope: how much of the system a test runs for real, and how much it replaces with something fake. That scope decides how fast the test is, how many kinds of bugs it can catch, how precisely a failure points at the cause and how often it breaks for reasons that are not bugs. This post compares unit vs integration vs end-to-end tests by testing one feature, a user registration, at each level, using Vitest 4 on Node.js 24 for the first two and Playwright for the third. You will see what each test needs, what it proves, what it misses and how to decide which level to write for a given piece of code. For how the three fit into a whole strategy, see the discussion of the testing pyramid and the testing trophy. The definitions follow common usage and the Vitest documentation and Playwright documentation.
The feature under test
Registration has three parts. A pure validation function checks the email and password. A service function applies the rules and saves the user through a repository. An HTTP endpoint receives the form data, calls the service and returns JSON.
export function validateRegistration({ email, password }) {
const errors = {};
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email ?? "")) {
errors.email = "Enter a valid email";
}
if ((password ?? "").length < 8) {
errors.password = "Use at least 8 characters";
}
return errors;
}import { validateRegistration } from "./validate.js";
export async function register(input, users) {
const errors = validateRegistration(input);
if (Object.keys(errors).length > 0) {
return { ok: false, errors };
}
if (await users.findByEmail(input.email)) {
return { ok: false, errors: { email: "Email is already registered" } };
}
const user = await users.insert({ email: input.email });
return { ok: true, user };
}import express from "express";
import { register } from "./service.js";
export function createApp(users) {
const app = express();
app.use(express.json());
app.post("/register", async (req, res) => {
const result = await register(req.body, users);
res.status(result.ok ? 201 : 422).json(result);
});
return app;
}(three pieces: validation, a service that uses a repository, and an HTTP endpoint)Each level of test will cover a different amount of this code.
Unit tests: one piece, nothing else
A unit test runs a small piece of code in isolation, a function or a class, with no network, no database and no file system. Its inputs are plain values, and its output is checked directly. It is the fastest kind of test, because nothing slow is involved.
import { describe, expect, test } from "vitest";
import { validateRegistration } from "./validate.js";
describe("validateRegistration", () => {
test("accepts a valid email and password", () => {
expect(validateRegistration({ email: "[email protected]", password: "longenough" })).toEqual({});
});
test("rejects an email without a domain", () => {
expect(validateRegistration({ email: "ada@", password: "longenough" })).toEqual({
email: "Enter a valid email",
});
});
test("rejects a short password", () => {
expect(validateRegistration({ email: "[email protected]", password: "short" })).toEqual({
password: "Use at least 8 characters",
});
});
test("handles missing fields", () => {
expect(Object.keys(validateRegistration({}))).toEqual(["email", "password"]);
});
}); ✓ validate.test.js (4 tests)
Test Files 1 passed (1)
Tests 4 passed (4)A unit test shines for logic with many cases, such as validation rules. It is cheap to write more cases for each rule, the run takes milliseconds and a failure names the exact rule that broke. What it cannot tell you is whether the service calls the validation, or whether the endpoint passes the request body to the service. A unit test of the service needs a decision: what to do with the repository, which is a collaborator. The usual answer is a test double, a small fake with the same methods.
import { expect, test } from "vitest";
import { register } from "./service.js";
function fakeUsers(existing = []) {
const rows = [...existing];
return {
findByEmail: async (email) => rows.find((user) => user.email === email) ?? null,
insert: async (data) => {
const user = { id: rows.length + 1, ...data };
rows.push(user);
return user;
},
};
}
test("registers a new user", async () => {
const result = await register({ email: "[email protected]", password: "longenough" }, fakeUsers());
expect(result).toEqual({ ok: true, user: { id: 1, email: "[email protected]" } });
});
test("rejects a duplicate email", async () => {
const users = fakeUsers([{ id: 1, email: "[email protected]" }]);
const result = await register({ email: "[email protected]", password: "longenough" }, users);
expect(result).toEqual({ ok: false, errors: { email: "Email is already registered" } });
}); ✓ service.unit.test.js (2 tests)
Test Files 1 passed (1)
Tests 2 passed (2)This is still a unit test of the service: the repository is replaced by an in-memory fake, so no database is involved. It runs the real validation, since validate.js is cheap and deterministic, which many teams count as part of the same unit. The test proves the service's decisions are right, assuming the repository behaves like the fake. That assumption is the gap that the next level fills.
Integration tests: pieces working together
An integration test runs several real parts together, with the boundaries between them included. For this feature, that means the endpoint, the service and a real repository backed by a real database, perhaps SQLite in memory or a container, and a real HTTP request. The test checks that the pieces agree with each other.
import request from "supertest";
import { beforeEach, expect, test } from "vitest";
import { createApp } from "./app.js";
import { createUserRepository } from "./user-repository.js";
import { createTestDatabase } from "./test-database.js";
let app;
beforeEach(async () => {
const db = await createTestDatabase();
app = createApp(createUserRepository(db));
});
test("creates a user and returns 201", async () => {
const response = await request(app)
.post("/register")
.send({ email: "[email protected]", password: "longenough" });
expect(response.status).toBe(201);
expect(response.body.user.email).toBe("[email protected]");
});
test("returns 422 for a second registration with the same email", async () => {
const body = { email: "[email protected]", password: "longenough" };
await request(app).post("/register").send(body);
const response = await request(app).post("/register").send(body);
expect(response.status).toBe(422);
expect(response.body.errors.email).toBe("Email is already registered");
}); ✓ register.integration.test.js (2 tests)
Test Files 1 passed (1)
Tests 2 passed (2)The second test finds a bug that the unit tests with a fake could not: the real repository must actually enforce uniqueness and return the existing row from findByEmail. If its SQL query used the wrong column, the service tests would stay green, since they used a fake, and only this one would fail. Integration tests also catch mistakes in JSON parsing, status codes, middleware order and serialization.
They cost more. They need a test database, careful setup and cleanup between tests, and they run in tens or hundreds of milliseconds, not microseconds. When one fails, the cause could be in any of the parts, so the failure is less precise than a unit test's.
End-to-end tests: the whole system as a user sees it
An end-to-end test runs the real application, front end and back end, in a real browser, and acts like a person: it opens a page, fills in fields, clicks and looks at what appears. Nothing between the user and the data is replaced.
import { expect, test } from "@playwright/test";
test("a visitor can register and sees a welcome message", async ({ page }) => {
await page.goto("http://localhost:3000/register");
await page.getByLabel("Email").fill(`ada+${Date.now()}@example.com`);
await page.getByLabel("Password").fill("longenough");
await page.getByRole("button", { name: "Create account" }).click();
await expect(page.getByRole("heading", { name: "Welcome" })).toBeVisible();
});Running 1 test using 1 worker
✓ 1 register.e2e.spec.js:3:5 › a visitor can register and sees a welcome message
1 passedThis test proves the thing that matters most: a person can actually register. It covers the form, the JavaScript that submits it, the network, the server, the database, the redirect and the welcome page. Nothing else gives that confidence. The price is high. It needs the whole stack running, takes seconds, depends on timing and on the environment's state, and fails for reasons unrelated to the feature, such as a slow server or a changed label. The unique email, built from Date.now(), avoids a collision with data from earlier runs, which is typical of the care these tests need.
Comparing the three
| Unit | Integration | End-to-end | |
|---|---|---|---|
| Runs for real | One function or class | Several parts and boundaries | The whole system |
| Replaced | Collaborators | External services | Usually nothing |
| Typical speed | Milliseconds | Tens to hundreds of milliseconds | Seconds |
| Failure points to | A specific line or rule | A region of the system | Anywhere |
| Catches | Logic errors | Wiring, queries, serialization | Broken user journeys, environment problems |
| Misses | Wiring and integration bugs | Browser and deployment issues | Subtle logic cases, cheaply |
| Flakiness risk | Very low | Low to moderate | Moderate to high |
Choosing the level
Write the lowest-level test that can catch the bug you are worried about. If the risk is a rule with many cases, such as validation, use unit tests. If the risk is that two parts do not agree, such as a query and a table, use an integration test. If the risk is that a user cannot complete a journey, use an end-to-end test, and keep these few.
A useful rule from experience: when a bug is found, write the test at the lowest level that reproduces it. A wrong regular expression gets a unit test. A missing database constraint gets an integration test. A button that does nothing in the browser gets an end-to-end test. Over time the suite reflects the bugs you actually have.
Naming helps teams stay consistent. Put the level in the file name, .unit.test.js, .integration.test.js and .e2e.spec.js, and configure the runner to run them in separate commands, so the fast ones run on every save and the slow ones in the background or in CI.


