Module 07 · Lesson 7.2
Unit and Integration Tests
On this page
- What you will learn
- Unit tests: check one rule, fast
- Integration and end-to-end tests
- Test two people at the same moment (NFR-01)
- Test data and fixed clocks
- Step-by-step workflow
- Working with an assistant on tests
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
A chef tastes one sauce on a spoon before it goes anywhere near a plate. That is a unit test: one small thing, checked fast. Later the chef sends a whole dish to a table and watches whether the parts work together. That is an integration test. A good kitchen does both, and so does a good project.
In this lesson you write both kinds for the Tidewell booking system. You test the 24-hour rule with a unit test that runs in a fraction of a second. You test the booking service against a real PostgreSQL engine. Then you test the hardest promise of all: two people grabbing the same slot at the same moment.
What you will learn
- Write fast unit tests for a business rule, including its boundaries, using a fixed clock.
- Write integration tests that run the service against a real PostgreSQL engine and check the saved data.
- Test two people booking the same slot at once, and explain why the database rule makes it pass.
- Set up test data and fixed clocks so every run gives the same answer.
Before you start
- Completed From Criteria to Test Cases, or have test cases of your own with test ids.
- Access to any capable AI assistant.
- Optional: Node.js and the project from earlier lessons, if you want to run the examples.
Unit tests: check one rule, fast
A unit test checks one small piece of code on its own: usually one function. It uses no database and no network, so it runs in a few thousandths of a second. That speed matters. You can run hundreds of them every time you save a file.
The best target is a business rule: a decision the client owns. Tidewell's rule says that online changes need at least 24 hours of notice, and exactly 24 hours is allowed (decided by the practice manager on 2026-11-19). Here is the function that applies it.
// src/features/bookings/rules.ts
// Decision: practice manager, 2026-11-19. Online changes are allowed only if the
// appointment starts at least 24 hours from now; exactly 24 hours is allowed.
export const NOTICE_PERIOD_HOURS = 24;
export function isInsideNoticePeriod(startsAt: Date, now: Date): boolean {
const earliestAllowed = now.getTime() + NOTICE_PERIOD_HOURS * 60 * 60 * 1000;
return startsAt.getTime() < earliestAllowed;
}Rules with exact edges need several inputs. Rather than copy and paste the same test, write a small table of cases and run one test for each row. This is a table-driven test. Each row has the scenario id, a name, a start time and the answer the criterion demands.
// Unit tests: one function, no database, no waiting.
import assert from "node:assert/strict";
import { test } from "node:test";
import { isInsideNoticePeriod } from "./rules";
import { NOW } from "./seed";
const hoursFromNow = (hours: number) => new Date(NOW.getTime() + hours * 60 * 60 * 1000);
const cases = [
{ id: "FR-02.1", name: "25 hours away is outside the notice period", startsAt: hoursFromNow(25), inside: false },
{ id: "FR-02.2", name: "23 hours away is inside the notice period", startsAt: hoursFromNow(23), inside: true },
{ id: "FR-02.4", name: "exactly 24 hours away is allowed", startsAt: hoursFromNow(24), inside: false },
{ id: "FR-02.4", name: "one millisecond under 24 hours is inside", startsAt: new Date(hoursFromNow(24).getTime() - 1), inside: true },
];
for (const { id, name, startsAt, inside } of cases) {
test(`${id} ${name}`, () => {
assert.equal(isInsideNoticePeriod(startsAt, NOW), inside, `${name}: inside should be ${inside}`);
});
}What each part does
hoursFromNowbuilds a start time a given number of hours after the fixed clockNOW. Nothing here reads the real time.- The
caseslist is the test table from the previous lesson, written as data. Add a row to add a test. - The
forloop registers one test per row. The name starts with the scenario id, for exampleFR-02.4 exactly 24 hours away is allowed. - The last argument of
assert.equalis a message. When a test fails, that message tells the reader which promise broke. Without it, they only seetrue !== false. - The row 'one millisecond under 24 hours' sits right next to the boundary. A boundary needs a test on the line, and one on each side.
✔ FR-02.1 25 hours away is outside the notice period (0.5948ms)
✔ FR-02.2 23 hours away is inside the notice period (0.079ms)
✔ FR-02.4 exactly 24 hours away is allowed (0.0498ms)
✔ FR-02.4 one millisecond under 24 hours is inside (0.0408ms)
ℹ tests 4
ℹ suites 0
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 292.5539Read the times in brackets: each unit test takes well under a millisecond. Your numbers will differ, because test runners print how long they took, and that depends on your computer. The duration_ms at the end is mostly start-up cost, not the tests themselves.
Integration and end-to-end tests
A unit test cannot tell you whether the SQL is right, whether the ownership check really uses the patient id, or whether a refusal leaves the data alone. For that you need an integration test: it runs several parts together, here the booking service and a real PostgreSQL database.
You do not need a database server for this. PGlite is a real PostgreSQL engine that runs inside Node. Every test creates its own fresh database, applies the three migrations and loads the seed data. That costs about a second on a normal computer. It means no test can leave a mess for the next one, which is worth the wait for a small suite. If you grow to hundreds of tests, share one database and empty the tables between tests instead.
You already met integration tests in the last lesson: scenarios.test.ts runs cancelBooking against PGlite for FR-02.1 to FR-02.4 and FR-05.1. They follow three habits worth copying.
- Start from known data.
givenBookinginserts the starting booking directly, so the test does not depend on the code it is checking. - Check the data, not only the answer. After a refusal, the test reads the booking back and checks it is still
booked. After a cancellation, it checks the history table. A response can say 'cancelled' while nothing was saved. - Check how it failed.
assert.rejectslets you test the status code and the phone number in the message. A test that only says 'it threw an error' would pass for any error, including a crash.
A word on end-to-end tests
An end-to-end test opens a real browser, clicks through the running app and looks at the screen, as a patient would. It is the closest to real use. It is also the slowest and the most fragile, because it depends on the whole system being up and on the page wording. Keep these for a handful of journeys that matter most. FR-02.1 is a good one.
// A real browser drives the running app. Names must match your own screens.
import { expect, test } from "@playwright/test";
test("FR-02.1 a patient cancels a booking more than 24 hours away", async ({ page }) => {
// Given: the test database holds a booking for the signed-in test patient, three days away.
await page.goto("/my-bookings");
const booking = page.getByRole("listitem").filter({ hasText: "Clinician A" });
// When: the patient opens the cancel screen and confirms.
await booking.getByRole("link", { name: "Cancel booking" }).click();
await page.getByRole("button", { name: "Yes, cancel this booking" }).click();
// Then: the screen says the booking is cancelled.
await expect(page.getByRole("status")).toContainText("Your booking is cancelled");
});Type-checked but not run here. It needs the app running, a test database and a signed-in test patient. The names in quotes must match your own screens.
page.getByRole(...)finds things the way a person or a screen reader would: by role and visible name. If it cannot find a button, a real patient with a screen reader probably cannot either.- The comments show the Given, When and Then steps. The test name starts with the scenario id.
- The file ends in
.spec.ts, not.test.ts, so the Node test runner leaves it alone. Playwright has its own command and its own configuration, where you set the app's address.
Playwright needs browsers installed and an app to talk to, so this example was type-checked and not run for this lesson. Follow Playwright's installation guide (opens in a new tab) to try it in your own project. Cypress is a well-known alternative.
Test two people at the same moment (NFR-01)
NFR-01 says that two people changing the same slot cannot produce two bookings for it. This is the promise that a shared spreadsheet could never keep. To test it, fire two booking requests at once and check that exactly one wins.
// NFR-01: two people booking the same slot at the same moment.
import assert from "node:assert/strict";
import { test } from "node:test";
import { handleCreateBooking, type Deps } from "./handlers";
import { freshDatabase, NOW } from "./seed";
import { givenBooking, SLOT } from "./helpers";
test("NFR-01 two bookings for the same slot at the same moment: one 201 and one 409", async () => {
const db = await freshDatabase();
const asPatient = (patientId: number): Deps => ({ db, now: () => NOW, patientId, log: () => {}, newRef: () => "ref-test" });
const bookSlot = () =>
new Request("http://localhost/api/bookings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ slotId: SLOT.farAway }),
});
const [first, second] = await Promise.all([
handleCreateBooking(bookSlot(), asPatient(1)),
handleCreateBooking(bookSlot(), asPatient(2)),
]);
assert.deepEqual([first.status, second.status].sort(), [201, 409]);
const { rows } = await db.query<{ live: number }>(
"SELECT count(*)::int AS live FROM bookings WHERE slot_id = $1 AND status = 'booked'",
[SLOT.farAway],
);
assert.equal(rows[0].live, 1);
});
test("NFR-01 the database itself refuses a second live booking for one slot", async () => {
const db = await freshDatabase();
await givenBooking(db, 1, SLOT.farAway);
await assert.rejects(givenBooking(db, 2, SLOT.farAway), { code: "23505" });
});What each part does
handleCreateBookingis the real handler from Module 4, the code that the route filesrc/app/api/bookings/route.tscalls. The test sends it realRequestobjects, as the web server would.Promise.allstarts both calls without waiting for the first to finish. Two patients ask for the same slot together.[first.status, second.status].sort()puts the two answers in order. We do not care which patient won, only that the answers are one201(created) and one409(slot taken).- The final query counts live bookings for the slot and expects exactly one. This catches code that returned
409but still saved something. - The second test skips the code entirely and inserts two bookings straight into the database. PostgreSQL itself refuses, with error code
23505, which means 'unique rule broken'.
✔ NFR-01 two bookings for the same slot at the same moment: one 201 and one 409 (1082.838ms)
✔ NFR-01 the database itself refuses a second live booking for one slot (717.7254ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 12201.1789Why the database rule, not the timing, guarantees it
Who is first? It does not matter. If the two requests are checked one after the other, the second finds the slot already taken. If they arrive in the same instant on a real server, PostgreSQL still lets only one of them write a live booking for that slot. The unique index is the guard at the door, and it works at any speed.
Test data and fixed clocks
A test that gives a different answer on a different day is worse than no test, because people stop trusting it. Two habits prevent that: fixed time and known data.
| Risk | Bad habit | Good habit |
|---|---|---|
| The time changes | The rule calls new Date() inside itself. | The rule receives now as a parameter. Tests pass a fixed date. |
| Data from the last test | Tests share one database and leave rows behind. | Each test creates its own database, or empties the tables first. |
| Real people's data | A copy of the live database. | Synthetic data only: Patient A, example.com emails, phone numbers from the fictional range. |
| Hidden order | Test 2 only passes if test 1 ran first. | Every test builds its own starting state, so any order works. |
The seed file follows these habits. It exports the fixed clock and builds a fresh database with four slots at known distances from it.
// Synthetic test data. Fixed clock for every test: 2026-11-30 10:00 UTC.
import { PGlite } from "@electric-sql/pglite";
import { join } from "node:path";
import { migrate } from "./migrate";
export const NOW = new Date("2026-11-30T10:00:00Z");
export const MIGRATIONS_DIR = join(import.meta.dirname, "migrations");
export async function freshDatabase(): Promise<PGlite> {
const db = new PGlite();
await migrate(db, MIGRATIONS_DIR);
await db.exec(`
INSERT INTO clinicians (display_name) VALUES ('Clinician A'), ('Clinician B');
INSERT INTO patients (full_name, email, phone) VALUES
('Patient A', 'patient.a@example.com', '01632 960001'),
('Patient B', 'patient.b@example.com', '01632 960002');
INSERT INTO slots (clinician_id, starts_at, ends_at) VALUES
(1, '2026-12-01T09:00:00Z', '2026-12-01T09:45:00Z'),
(1, '2026-12-01T10:00:00Z', '2026-12-01T10:45:00Z'),
(1, '2026-12-01T11:00:00Z', '2026-12-01T11:45:00Z'),
(1, '2026-12-03T09:00:00Z', '2026-12-03T09:45:00Z');`);
return db;
}Now run all three test files together. This is the whole suite so far: unit, integration and concurrency. Your times will differ, and the order may differ too, because Node runs test files side by side.
✔ NFR-01 two bookings for the same slot at the same moment: one 201 and one 409 (1611.3845ms)
✔ NFR-01 the database itself refuses a second live booking for one slot (958.2379ms)
✔ FR-02.1 25 hours away is outside the notice period (1.0576ms)
✔ FR-02.2 23 hours away is inside the notice period (0.1997ms)
✔ FR-02.4 exactly 24 hours away is allowed (0.0893ms)
✔ FR-02.4 one millisecond under 24 hours is inside (0.0561ms)
✔ FR-02.1 cancelling outside the notice period cancels the booking (1506.6301ms)
✔ FR-02.2 cancelling inside the notice period leaves the booking unchanged and says to phone (928.4164ms)
✔ FR-02.3 someone else's booking is unchanged and looks like it does not exist (1205.265ms)
✔ FR-02.4 a booking exactly 24 hours away can be cancelled online (1139.4473ms)
✔ FR-05.1 a cancellation is recorded with who made it and when (1069.036ms)
ℹ tests 11
ℹ suites 0
ℹ pass 11
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 16317.0757Now run the traceability check from the last lesson on all the files. The gap it reported for NFR-01 is closed. The end-to-end file is the Playwright test from earlier in this lesson.
FR-02.1 Cancel outside the notice period integration: scenarios.test.ts, unit: rules.test.ts, end-to-end: cancel-booking.spec.ts
FR-02.2 Cancel inside the notice period integration: scenarios.test.ts, unit: rules.test.ts
FR-02.3 Someone else's booking integration: scenarios.test.ts
FR-02.4 Exactly 24 hours is allowed integration: scenarios.test.ts, unit: rules.test.ts
FR-05.1 Changes are recorded integration: scenarios.test.ts
NFR-01 No double booking integration: concurrency.test.ts
Every Must scenario has a test.Step-by-step workflow
Step 1: Start with the rules
Write the unit tests for every business rule first. They are cheap, and they pin down the boundaries.
What you should see: A table-driven test file for each rules module, with ids in the names.
Step 2: Add integration tests for each endpoint's scenarios
For each scenario, set up the starting data with a helper, call the service, then check the response and the saved data.
What you should see: One integration test per scenario that touches the database.
Step 3: Write the concurrency test for NFR-01
Fire two requests with
Promise.all. Expect one success and one refusal, and one row.What you should see: A test that fails if the unique rule is ever removed.
Step 4: Fix the clock and the data
Pass
nowinto every rule. Use fresh databases and synthetic data.What you should see: The suite gives the same answers tomorrow as today.
Step 5: Add a few end-to-end journeys
Choose the two or three journeys the client cares about most. Keep each one short.
What you should see: A small end-to-end file that does not slow every change.
Step 6: Run the traceability check
Run the script from the last lesson. Add a test for any Must scenario it reports.
What you should see: 'Every Must scenario has a test.'
- Unit tests
Milliseconds, many
- Integration tests
Real database, about a second
- Concurrency test
The database rule
- End-to-end tests
A browser, a few
Run the cheap tests most often. Run the expensive ones on every pull request.
Working with an assistant on tests
| Task | Assistant's part | Your part |
|---|---|---|
| Write unit tests for a rule | Drafts a table of cases, including edge values. | Check each expected value against the criterion. Add the boundary on the line. |
| Write integration tests | Drafts setup helpers and tests for each scenario. | Make sure each test checks the saved data, and that the database is real, not a fake. |
| Write the concurrency test | Drafts the Promise.all pattern. | Check that it expects one success and one refusal, and counts the rows. |
| Set up test data | Proposes seed rows. | Make sure all data is synthetic and the clock is fixed. |
| Decide what the tests protect | Nothing. It does not know your promises. | Link every test to a scenario id. |
Conclusion and your next step
Unit tests check rules quickly, with a fixed clock and a case on every boundary. Integration tests check that the service and a real database agree, and they look at the saved data. The concurrency test shows that the database rule, not luck or timing, stops a double booking. A few end-to-end tests cover the journeys that matter.
Your next step: write the unit tests for your capstone's main rule and one integration test per Must scenario, then add a concurrency test for your most important uniqueness rule. Then continue to Reviewing Assistant-Written Tests, where you learn to tell a test that protects you from one that only looks busy.
To go deeper on testing with an assistant, read Prompt Engineering for QA: Property-Based, Mutation, and Contract Testing with AI or use the AI-Generated Code Review Checklist.
Reusable prompt
Integration test writer
Asks for tests that check a service against a real database for given scenarios, with expected results taken from the criteria and not from the code.
You are helping me write integration tests. Write only tests. Do not change the code under test.
Fictional clinic: Tidewell Physiotherapy. Stack: TypeScript, Node's built-in test runner (node:test and node:assert/strict), PGlite (a real PostgreSQL engine inside Node) for the database.
Fixed clock: 2026-11-30 10:00 UTC. Use synthetic data only (Patient A, Patient B).
Helpers that exist: freshDatabase() returns a new migrated database with seed data; givenBooking(db, patientId, slotId) inserts a booking; asPatient(db, patientId) builds the service context.
Function under test: cancelBooking(ctx, bookingId) in src/features/bookings/service.ts. I am NOT pasting its code on purpose: base your expected results only on these criteria.
FR-02.1 Outside the notice period (25 hours away): status becomes cancelled.
FR-02.2 Inside the notice period (23 hours away): booking unchanged, 422, message gives 01632 960 123, Monday to Friday, 8:00 to 18:00.
FR-02.3 Someone else's booking: unchanged, 404, existence not revealed.
FR-02.4 Exactly 24 hours away: allowed.
Rules for the tests:
1. Each test name starts with its scenario id.
2. Each test follows Given, When, Then, and the Then part checks the saved data as well as the response.
3. Do not mock the database or the function under test.
4. Every test must be able to fail. Say, for each test, what change to the code would make it fail.Show the reusable template
Replace each {{placeholder}} with your own details.
You are helping me write integration tests. Write only tests. Do not change the code under test.
Context: {{organisation_and_stack}}
Fixed clock: {{fixed_clock}}. Use synthetic data only.
Helpers that exist: {{existing_helpers}}
Function under test: {{function_and_file}}. I am NOT pasting its code on purpose: base your expected results only on these criteria.
{{scenarios}}
Rules for the tests:
1. Each test name starts with its scenario id.
2. Each test follows Given, When, Then, and the Then part checks the saved data as well as the response.
3. Do not mock the database or the function under test.
4. Every test must be able to fail. Say, for each test, what change to the code would make it fail.Expected output and limitations
Test code with one test per scenario, names starting with the scenario ids, a Given, When, Then shape, assertions on both the response and the saved data, and a note under each test saying what code change would make it fail.
test("FR-02.2 inside the notice period: unchanged, told to phone", async () => {
const db = await freshDatabase();
const bookingId = await givenBooking(db, 1, SLOT.inside); // Given: booking 23 h away
await assert.rejects(cancelBooking(asPatient(db, 1), bookingId), ... 422 ... phone ...); // When / Then
assert.equal(await statusOf(db, bookingId), "booked"); // Then: data unchanged
});
// Would fail if: the notice check is removed, the status is not 422, or the booking is cancelled anyway.Limitations to keep in mind
- The assistant may invent helper names that do not exist in your project. Run the tests to find out.
- It may check only the response and skip the database. Ask for the saved-data check explicitly and look for it.
- 'Would fail if' notes are claims, not proof. Test them by breaking the code, as the next lesson shows.
Common errors and how to fix them
A test passes today and fails next week.
Why it happens: The code reads the real clock, or the test depends on data left by another test.
Fix: Pass the time in as a parameter, use a fixed date, and let every test build its own data.
The concurrency test is flaky: it sometimes passes and sometimes fails.
Why it happens: The test depends on which request arrives first, or does not check the final count of rows.
Fix: Do not assert who wins. Assert that the answers are one success and one refusal, and that exactly one live row exists.
Integration tests are slow, so people stop running them.
Why it happens: Every test starts a new database, and the suite has grown large.
Fix: Share one database and empty the tables between tests, and keep rule checks in fast unit tests.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Tests for a Ferngate stock rule
Ferngate's workshop wants a rule: taking a part must never push its stock below zero. Write the table of cases for a unit test of this rule, then describe one integration test for 'a mechanic records a part taken' and one concurrency test for two mechanics taking the last part together.
You will need
- The rule: stock after taking = stock before minus the quantity taken, and it must not be below zero.
- Note: the low-stock threshold is still 'to be agreed' with the owner.
- Note: two mechanics use two tablets, and the connection is unreliable.
Acceptance criteria
Your work is done when every one of these is true.
Hints (2)
- Where does the guard against negative stock belong: in the code only, or also in the database? Think about which one holds when two mechanics act together.
- A database CHECK that stock is not below zero would give the second mechanic a clean refusal.
Show a model answer
A strong answer has a unit table with rows such as stock 5 taking 5 (allowed, leaves 0), stock 5 taking 6 (refused), stock 0 taking 1 (refused) and taking 0 or a negative number (invalid input). The integration test starts with a part holding 3, records 1 taken for a job and checks both the movement row and the new stock of 2. The concurrency test starts with stock 1 and has two mechanics take it together: one succeeds, one is refused, and stock ends at 0, never -1. The strongest answers note that the guarantee comes from a database rule such as a CHECK on stock, so both the code and the database refuse negative stock. They leave the low-stock threshold as a decision for the owner.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. The requirement says two bookings cannot exist for one slot. It does not say who wins. Asserting a winner is tempting because it feels more exact, but it makes the test depend on timing and fail for no real reason.
Show the answer and explanation
Answer: B. The no-double-booking rule is part of the database design. A fake that stores rows in an array would accept both bookings and the test would pass for the wrong reason. A real engine is not faster, so speed is the tempting but wrong reason.
Show the answer and explanation
Answer: A. A rule that depends on the real time gives different answers as the clock moves, so a test could pass today and fail tomorrow. Speed is not the issue, and nothing forbids
new Date(); the point is control.
Frequently asked questions
What is the difference between a unit test and an integration test?
A unit test checks one function on its own, without a database or network. An integration test checks that several parts work together, such as a service and a real database. Unit tests are faster, and integration tests find problems where parts meet.
How do I test code that uses a database?
Run the code against a real database made just for the test. PGlite is a PostgreSQL engine that runs inside Node, so you need no server. Build the tables, add known data, run the code, and then read the data back to check it.
How do I test for a race condition or double booking?
Start two actions at once, for example with Promise.all, and check that exactly one succeeds and the data has no duplicate. The real protection should be a database rule, such as a unique index, because tests cannot try every possible timing.
Should I use Node's test runner, Vitest or Jest?
All three work well. Node's built-in runner needs no extra package, which is why this lesson uses it. Vitest and Jest add more features, and many teams already know them. Pick one, write it in the project notes and use it consistently.
- Written by
- PromptFable Editorial
- Last updated 19 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- Test runner(opens in a new tab)
Node.js · Official documentation · Reference for test, assert, test reporters and running tests from the command line.
- PGlite(opens in a new tab)
PGlite · Official documentation · Documentation for the PostgreSQL engine that runs inside Node and is used here for integration tests.
- The Practical Test Pyramid(opens in a new tab)
Martin Fowler · Why most tests should be fast and low-level, with few that drive the whole application.
- Vitest(opens in a new tab)
Vitest · Official documentation · A popular alternative test runner for TypeScript projects.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.