What Makes a Good Test?
What makes a good test: it fails for the right reason, reads like a spec, runs fast, stays independent and survives refactoring, with before and after examples.

A test suite can be large, green and nearly useless. It can also be small and the reason a team ships with confidence. The difference is not the number of tests or the percentage of code they touch. It is whether each test has a few specific qualities: it fails when behavior breaks and only then, it says clearly what broke, it runs fast enough to be used, it does not depend on other tests and it does not need rewriting each time the code is reorganized. This post lists what makes a good test, with a bad and a good version of the same test for each quality, using Vitest 4 on Node.js 24. The aim is a checklist you can apply to any test in a review, in any language. The ideas draw on the Vitest guide and long-standing testing practice, such as the F.I.R.S.T. properties of fast, isolated, repeatable, self-validating and timely tests.
It fails for the right reason, and only then
A test has two jobs. It must fail when the behavior it protects is broken, and it must stay green when the behavior is unchanged. A test that fails after a harmless refactor teaches people to ignore failures. A test that passes while the feature is broken gives false comfort.
The usual cause of tests that fail for the wrong reason is coupling to implementation: asserting how the code works instead of what it does. Take a function that formats a price.
export function formatPrice(cents) {
return `$${(cents / 100).toFixed(2)}`;
}A coupled test spies on internals.
import { expect, test, vi } from "vitest";
import { formatPrice } from "./price.js";
test("formatPrice uses toFixed", () => {
const spy = vi.spyOn(Number.prototype, "toFixed");
formatPrice(1999);
expect(spy).toHaveBeenCalledWith(2);
}); ✓ price.bad.test.js (1 test)It passes today, and it would fail if someone switched to Intl.NumberFormat, even though the output is identical. It would also stay green if the function returned the wrong string. A good test checks the observable result.
import { expect, test } from "vitest";
import { formatPrice } from "./price.js";
test("formats cents as dollars with two decimals", () => {
expect(formatPrice(1999)).toBe("$19.99");
expect(formatPrice(5)).toBe("$0.05");
expect(formatPrice(0)).toBe("$0.00");
}); ✓ price.good.test.js (1 test)Now a refactor that keeps the output leaves the test green, and a change that breaks the output turns it red. The test describes behavior, not mechanism.
It reads like a specification
When a test fails, the name is the first thing a developer reads. A good name states the situation and the expected result, so the failure message is almost a bug report.
import { describe, expect, test } from "vitest";
import { applyDiscount } from "./discount.js";
describe("applyDiscount", () => {
test("test1", () => {
expect(applyDiscount(100, "SAVE10")).toBe(90);
});
test("takes 10 percent off the total when the SAVE10 code is applied", () => {
expect(applyDiscount(100, "SAVE10")).toBe(90);
});
test("leaves the total unchanged for an unknown code", () => {
expect(applyDiscount(100, "NOPE")).toBe(100);
});
}); ✓ names.test.js (3 tests)The first name, test1, tells nobody anything. The others read as rules. If the second one fails, the output says "takes 10 percent off the total when the SAVE10 code is applied" failed, and the developer already knows which behavior is at stake. A useful trick is to read the names of a file aloud in order: they should describe the unit's behavior as a list.
The body of the test should also be easy to follow. Keep it short, show the input and the expected output near each other and avoid logic such as loops and conditions in the test, which can contain their own bugs. If a test needs a comment to explain what it does, the name or the structure needs work.
It tests one behavior
A test that checks five unrelated things stops at its first failure and hides the rest, and its name cannot describe it. Prefer one behavior per test, which does not mean one assertion: several assertions about the same result are fine.
import { expect, test } from "vitest";
import { createUser } from "./user.js";
test("creates a user with the given email, an id and the default role", () => {
const user = createUser({ email: "[email protected]" });
expect(user.email).toBe("[email protected]");
expect(user.id).toBeTypeOf("string");
expect(user.role).toBe("member");
}); ✓ one-thing.test.js (1 test)All three assertions describe one outcome, a new user. In contrast, a test that creates a user, then updates it, then deletes it and asserts after each step is three tests squeezed into one. When it fails, you do not know which operation broke without reading it closely.
It is independent and repeatable
A good test can run alone, in any order, in parallel with others, and give the same answer every time. A test that depends on another test having run first, or on leftover data, or on the date, is a time bomb.
import { expect, test } from "vitest";
const cart = [];
test("adds an item", () => {
cart.push("book");
expect(cart).toHaveLength(1);
});
test("starts empty", () => {
expect(cart).toHaveLength(0);
}); ✓ shared-state.test.js > adds an item
✗ shared-state.test.js > starts empty
AssertionError: expected [ 'book' ] to have a length of +0 but got 1The second test fails because the first one changed shared state. If the order changed, the results would change too. Create what each test needs inside the test, or in a beforeEach hook, so every test starts clean.
import { beforeEach, expect, test } from "vitest";
let cart;
beforeEach(() => {
cart = [];
});
test("adds an item", () => {
cart.push("book");
expect(cart).toHaveLength(1);
});
test("starts empty", () => {
expect(cart).toHaveLength(0);
}); ✓ isolated.test.js (2 tests)Time and randomness break repeatability in the same way. A test that compares a result to "today" fails at midnight or on the last day of a month. Control the clock instead.
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { isExpired } from "./token.js";
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-06-01T12:00:00Z"));
});
afterEach(() => {
vi.useRealTimers();
});
test("a token that expired yesterday is expired", () => {
expect(isExpired(new Date("2026-05-31T12:00:00Z"))).toBe(true);
});
test("a token that expires tomorrow is valid", () => {
expect(isExpired(new Date("2026-06-02T12:00:00Z"))).toBe(false);
}); ✓ clock.test.js (2 tests)It is fast
A slow suite is a suite that people run less often, and a suite that runs rarely finds bugs late. Speed is a quality of each test: do not call real networks, do not sleep for fixed times, do not load more than the test needs. Use fakes for slow collaborators, and run slow tests, such as end-to-end tests, separately from the quick ones.
A common cause of slowness is waiting on time. Replace a real delay with a fake timer.
import { expect, test, vi } from "vitest";
import { debounce } from "./debounce.js";
test("calls the function once after the delay", () => {
vi.useFakeTimers();
const fn = vi.fn();
const debounced = debounce(fn, 500);
debounced();
debounced();
vi.advanceTimersByTime(500);
expect(fn).toHaveBeenCalledTimes(1);
vi.useRealTimers();
}); ✓ debounce.test.js (1 test)The test covers a 500 millisecond delay without waiting for it, and gives the same result every time.
It is easy to diagnose when it fails
A good failure message tells you what was expected, what happened and where. The matcher you choose matters. Compare two ways to assert the same fact.
import { expect, test } from "vitest";
const user = { name: "Ada", roles: ["admin", "editor"] };
test("poor assertion", () => {
expect(user.roles.includes("owner")).toBe(true);
});
test("clear assertion", () => {
expect(user.roles).toContain("owner");
}); ✗ poor assertion
AssertionError: expected false to be true
✗ clear assertion
AssertionError: expected [ 'admin', 'editor' ] to include 'owner'Both fail, but only the second says what the array contained. Use specific matchers, toEqual for objects, toContain for membership, toThrow for errors, and keep each test's data small enough to read in the diff.
It tests the edges, not only the middle
The first case people write is the happy path, and the bugs live at the edges: empty input, zero, negative numbers, the maximum, duplicate items, unicode, a missing field. A good suite includes the ones that matter for the unit. A table-driven test makes this cheap.
import { expect, test } from "vitest";
import { clamp } from "./clamp.js";
test.each([
{ value: 5, min: 0, max: 10, expected: 5 },
{ value: -1, min: 0, max: 10, expected: 0 },
{ value: 11, min: 0, max: 10, expected: 10 },
{ value: 0, min: 0, max: 10, expected: 0 },
{ value: 10, min: 0, max: 10, expected: 10 },
])("clamp($value, $min, $max) is $expected", ({ value, min, max, expected }) => {
expect(clamp(value, min, max)).toBe(expected);
}); ✓ edges.test.js (5 tests)
✓ clamp(5, 0, 10) is 5
✓ clamp(-1, 0, 10) is 0
✓ clamp(11, 0, 10) is 10
✓ clamp(0, 0, 10) is 0
✓ clamp(10, 0, 10) is 10Each row is a separate test with its own name in the report. Adding a case costs one line.
It would fail if the code were wrong
The strongest check of a test is to break the code on purpose and see whether the test notices. Change a > to >=, return a constant, delete a line. If the test stays green, it is not protecting that code. This idea is the basis of mutation testing, which automates it. Even a manual version, done once for an important function, finds tests that assert nothing, such as a test that calls a function and never checks the result, or one whose assertion is inside a callback that never runs.
import { expect, test } from "vitest";
test("fetches the user", async () => {
const promise = Promise.reject(new Error("boom"));
promise.catch(() => {});
expect(true).toBe(true);
}); ✓ no-assert.test.js (1 test)The test passes and checks nothing about the user. Make sure every test has an assertion about the thing it names, and that async assertions are awaited, for example with await expect(promise).resolves....
A short checklist
Does it fail when the behavior breaks, and only then? Does the name describe the behavior? Does it test one thing? Can it run alone and in any order? Is it fast? Is the failure message clear? Are the edges covered? Would it fail if the code were wrong? Does it avoid testing internals? A test that answers yes to most of these is worth its upkeep; one that answers no to several is worth rewriting or deleting.


