Skip to main content

Web frameworks · Intermediate · 34 min

Test the library app: loan rules in Vitest, journeys in Playwright

By Padding · Updated 18 Nov 2026
Next.js 16.4 · Vitest 5.1.1 · Playwright 1.65.1 · Better Auth 1.7 · Node.js 26 · node:26 image

You will unit test part 6's loan rules with Vitest 5 against a fresh SQLite file per test, and drive the librarian journey through the production build with Playwright 1.65, ending with one npm test command that would have caught the double-lend bug from part 6.

On this page

Part 6 made lending safe: a transaction checks that the book is on the shelf and that the member holds fewer than three books before it writes the loan, and part 2's partial unique index refuses a second open loan for the same book. Part 7 made the catalogue fast without showing a lent book as available. Right now the only proof of any of that is you clicking through the app. In this part you write the proof down as tests, so the next change to the lending code cannot quietly bring the double-lend bug back.

You test at two levels, each for what it does best:

  • Unit tests with Vitest for the loan rules. Part 6 already put them in src/lib/loan-rules.ts, with the database and the clock as parameters, refusals returned as values and relative imports, so Vitest can load the module as it is. Each test gets a brand-new SQLite file, so tests never share data and run in about a second.
  • Browser tests with Playwright for the librarian's journey: sign in, add a book, lend it, return it. They run against the production build, on a separate database seeded fresh for every run, so they never touch data/library.db.

This page covers what is specific to the library app. For the ideas behind each tool, see testing UI code with Vitest and Testing Library and writing end-to-end browser tests with Playwright.

The browser tests find things the way a person does, by labels and button names. They expect these from earlier parts; if your wording differs, change the locator in step 8 to match your page, not the other way round:

  • /sign-in has fields labelled Email and Password and a Sign in button (part 5).
  • /books/new has fields labelled Title, Author and Year and an Add book button, and goes to the new book's page after saving (part 4).
  • A book's page shows On the shelf or text starting On loan. A signed-in librarian also sees part 6's LoanDesk: a Member select with a Lend for 14 days button while the book is on the shelf, or a Record return button while it is out. Visitors see neither.

The tests ask for getByRole("button", { name: "Lend" }) and { name: "Return" }. Unless you pass exact: true, Playwright matches a role's name as a case-insensitive substring, so "Lend" finds Lend for 14 days and "Return" finds Record return. If your buttons say something without those words, change the locator.

Step 1 · Install Vitest and Playwright

Work in the project from part 7. Install both test runners as development dependencies at exact versions, then download the Chromium build that this Playwright version drives:

Bash
cd ~/community-library-demo
npm install --save-exact --save-dev vitest@5.1.1 @playwright/test@1.65.1 @types/node@26.6.6
npx playwright install --with-deps chromium

The @types/node upgrade is part of the same command on purpose. create-next-app in part 1 added @types/node 20, and Vitest 5 asks for 22 or later, so without it npm stops with ERESOLVE could not resolve. Version 26 matches the Node.js you run.

On Ubuntu, --with-deps installs the system libraries Chromium needs with apt, so it asks for your sudo password. On macOS it needs nothing extra. Chromium is around 150 MB. Playwright keeps it in a shared cache (~/.cache/ms-playwright on Linux, ~/Library/Caches/ms-playwright on macOS) and every project on the machine that uses Playwright 1.65.1 reuses it, which matters on prepaid data.

Add the scripts this part uses, and keep Playwright's output folders out of Git:

Bash
npm pkg set scripts.test:unit="vitest run" scripts.test:e2e="playwright test" scripts.test="npm run test:unit && npm run test:e2e" scripts.e2e:db="tsx scripts/e2e-db.ts"
printf '\n# Playwright output\n/test-results/\n/playwright-report/\n' >> .gitignore

vitest run runs the tests once and exits. Plain vitest would stay open and rerun on every save, which is handy while you write tests but not for a final check.

Check it worked

Bash
npx vitest --version
npx playwright --version

The first prints something like vitest/5.1.1 linux-x64 node-v26.13.1 and the second Version 1.65.1. If playwright install stopped with a list of missing libraries, run it again and enter your sudo password when asked.

Step 2 · Check that part 6's loan rules are ready to test

A unit test needs code it can call without a running app. Part 6 wrote the rules that way on purpose, so this step only confirms that src/lib/loan-rules.ts is what the tests below expect. Open it and check four things:

  • The database is a parameter. lendBook(db, { bookId, memberId, now }) and returnBook(db, { bookId, now }) take the connection first, so a test can pass a connection to a throwaway file. The module never imports server-only and holds no connection of its own.
  • The clock is a parameter. now defaults to the current time, so a test can fix it and know the exact due date. isOverdue takes it too.
  • A refusal is a value. A broken rule comes back as { ok: false, reason: "on-loan" }, a fixed code a test can compare exactly, and the server actions turn it into wording. An exception means only that something really broke.
  • The imports are relative. ../db/connect and ../db/schema load everywhere with no extra setup. Next.js and tsx read the @/ alias from tsconfig.json; Vitest does not unless you configure it.

behavior: "immediate" starts each lend with BEGIN IMMEDIATE, so the checks and the insert happen while holding SQLite's write lock, and a second writer waits (better-sqlite3 waits up to five seconds by default) instead of reading stale data. That is the behaviour the tests pin down.

Check it worked

Load the module outside Next.js, then type-check the whole app:

Bash
npx tsx --eval 'console.log(Object.keys(require("./src/lib/loan-rules.ts")).sort().join(" "))'
npx next typegen
npx tsc --noEmit

The first command prints LOAN_DAYS MAX_OPEN_LOANS isOverdue lendBook returnBook, the names part 6 exports. next typegen writes the route types (PageProps, LayoutProps) that next build would otherwise create, and tsc --noEmit then prints nothing. If the list of names differs, compare your file with the listing in part 6 before you go on: the tests below import these names.

Step 3 · Give each test its own database

Tests that share a database depend on each other's leftovers: one test lends a book, and the next fails because it is out. Give every test a new SQLite file in the system's temporary folder, with the real migrations from drizzle/ applied, so the tables are exactly the ones the app uses:

Bash
mkdir -p tests/unit
cat > tests/unit/test-db.ts <<'TS'
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { migrate } from "drizzle-orm/better-sqlite3/migrator";
import { connect } from "../../src/db/connect";

export type TestDb = ReturnType<typeof createTestDb>;

export function createTestDb() {
  const dir = mkdtempSync(join(tmpdir(), "library-test-"));
  const file = join(dir, "library.db");
  const connections: ReturnType<typeof connect>[] = [];

  // Every call opens another connection to the same file, like a second
  // server process would.
  const open = () => {
    const db = connect(file);
    connections.push(db);
    return db;
  };

  const db = open();
  migrate(db, { migrationsFolder: "drizzle" });

  return {
    db,
    open,
    cleanup() {
      for (const connection of connections) connection.$client.close();
      rmSync(dir, { recursive: true, force: true });
    },
  };
}
TS
cat > vitest.config.mts <<'TS'
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    include: ["tests/unit/**/*.test.ts"],
    environment: "node",
  },
});
TS

connect(file) is the same function the app and the seed script use, so foreign keys and WAL mode are on in tests too. migrate() applies every file in drizzle/ in order, including the Better Auth tables from part 5, and records them in __drizzle_migrations just as npm run db:migrate does. The config tells Vitest to look only in tests/unit, so it never picks up the Playwright files you write later. Its .mts extension marks it as an ES module; the project's package.json has no "type" field, and with a plain .ts name Vite prints a warning about loading ESM syntax as CommonJS.

Check it worked

Bash
npx tsx --eval 'const { createTestDb } = require("./tests/unit/test-db.ts"); const t = createTestDb(); console.log(t.db.$client.prepare("select count(*) as books from books").get()); t.cleanup()'

It prints { books: 0 }: the tables exist and are empty. Each call makes its own folder under the system's temporary folder and cleanup() deletes it, so nothing is left behind.

Step 4 · Unit test the loan rules

Write the tests. Each one builds a small library of five books and two members in its own database, calls the rules, and checks both what the function returned and what is now in the loans table:

Bash
cat > tests/unit/loan-rules.test.ts <<'TS'
import { and, count, eq, isNull } from "drizzle-orm";
import { afterEach, describe, expect, it } from "vitest";
import { books, loans, members } from "../../src/db/schema";
import {
  isOverdue,
  lendBook,
  LOAN_DAYS,
  MAX_OPEN_LOANS,
  returnBook,
  type LibraryDb,
} from "../../src/lib/loan-rules";
import { createTestDb, type TestDb } from "./test-db";

const NOW = new Date("2026-11-02T09:00:00Z");
const DAY_MS = 24 * 60 * 60 * 1000;

let current: TestDb | undefined;

afterEach(() => {
  current?.cleanup();
  current = undefined;
});

function library() {
  current = createTestDb();
  const { db, open } = current;
  const bookIds = db
    .insert(books)
    .values([
      { title: "Arrow of God", author: "Chinua Achebe", year: 1964 },
      { title: "Kintu", author: "Jennifer Nansubuga Makumbi", year: 2014 },
      { title: "Homegoing", author: "Yaa Gyasi", year: 2016 },
      { title: "Purple Hibiscus", author: "Chimamanda Ngozi Adichie", year: 2003 },
      { title: "Stay With Me", author: "Ayọ̀bámi Adébáyọ̀", year: 2017 },
    ])
    .returning({ id: books.id })
    .all()
    .map((row) => row.id);
  const [ama, kofi] = db
    .insert(members)
    .values([{ name: "Ama Mensah" }, { name: "Kofi Boateng" }])
    .returning({ id: members.id })
    .all()
    .map((row) => row.id);
  return { db, open, bookIds, ama, kofi };
}

function openLoansFor(db: LibraryDb, bookId: number) {
  const row = db
    .select({ total: count() })
    .from(loans)
    .where(and(eq(loans.bookId, bookId), isNull(loans.returnedAt)))
    .get();
  return row?.total ?? 0;
}

describe("lendBook", () => {
  it("lends a book that is on the shelf, due 14 days later", () => {
    const { db, bookIds, ama } = library();

    const result = lendBook(db, { bookId: bookIds[0], memberId: ama, now: NOW });

    expect(result).toEqual({
      ok: true,
      loanId: expect.any(Number),
      dueAt: new Date(NOW.getTime() + LOAN_DAYS * DAY_MS),
    });
    const [loan] = db.select().from(loans).all();
    expect(loan.lentAt).toEqual(NOW);
    expect(loan.returnedAt).toBeNull();
  });

  it("refuses a book that is already out, even from a second connection", () => {
    const { db, open, bookIds, ama, kofi } = library();
    const secondDesk = open();

    const first = lendBook(db, { bookId: bookIds[0], memberId: ama, now: NOW });
    const second = lendBook(secondDesk, { bookId: bookIds[0], memberId: kofi, now: NOW });

    expect(first.ok).toBe(true);
    expect(second).toEqual({ ok: false, reason: "on-loan" });
    expect(openLoansFor(db, bookIds[0])).toBe(1);
  });

  it("refuses a fourth book while a member holds three", () => {
    const { db, bookIds, ama, kofi } = library();
    for (const bookId of bookIds.slice(0, MAX_OPEN_LOANS)) {
      expect(lendBook(db, { bookId, memberId: ama, now: NOW }).ok).toBe(true);
    }

    expect(lendBook(db, { bookId: bookIds[3], memberId: ama, now: NOW })).toEqual({
      ok: false,
      reason: "member-at-limit",
    });
    expect(lendBook(db, { bookId: bookIds[3], memberId: kofi, now: NOW }).ok).toBe(true);
  });

  it("refuses books and members that do not exist", () => {
    const { db, bookIds, ama } = library();

    expect(lendBook(db, { bookId: 999, memberId: ama })).toEqual({ ok: false, reason: "no-such-book" });
    expect(lendBook(db, { bookId: bookIds[0], memberId: 999 })).toEqual({
      ok: false,
      reason: "no-such-member",
    });
    expect(db.select().from(loans).all()).toHaveLength(0);
  });
});

describe("returnBook", () => {
  it("puts a book back on the shelf so it can go out again", () => {
    const { db, bookIds, ama, kofi } = library();
    lendBook(db, { bookId: bookIds[1], memberId: ama, now: NOW });

    const back = returnBook(db, { bookId: bookIds[1], now: new Date(NOW.getTime() + 3 * DAY_MS) });

    expect(back).toEqual({ ok: true, loanId: expect.any(Number) });
    expect(openLoansFor(db, bookIds[1])).toBe(0);
    expect(lendBook(db, { bookId: bookIds[1], memberId: kofi, now: NOW }).ok).toBe(true);
  });

  it("refuses to return a book that is not out", () => {
    const { db, bookIds } = library();

    expect(returnBook(db, { bookId: bookIds[2] })).toEqual({ ok: false, reason: "not-on-loan" });
  });
});

describe("isOverdue", () => {
  const dueAt = new Date("2026-11-16T09:00:00Z");

  it("is overdue only after the due date and only while the book is out", () => {
    expect(isOverdue({ dueAt, returnedAt: null }, new Date("2026-11-16T09:00:00Z"))).toBe(false);
    expect(isOverdue({ dueAt, returnedAt: null }, new Date("2026-11-17T08:00:00Z"))).toBe(true);
    expect(
      isOverdue({ dueAt, returnedAt: new Date("2026-11-20T10:00:00Z") }, new Date("2026-11-21T08:00:00Z")),
    ).toBe(false);
  });
});
TS
npm run test:unit

The second test is the one that matters most. secondDesk is another connection to the same file, standing in for a second librarian's request handled by another server process. The two lends run one after the other, not at the same instant; part 6's race script is how you watch the race itself. What the test pins down is the result the race must always have: one loan, and a clear on-loan refusal for the other desk, not a crash.

Check it worked

Vitest ends with a summary like this, with your own timings under it:

Text
 Test Files  1 passed (1)
      Tests  7 passed (7)

If every test fails with Can't find meta/_journal.json file, Vitest was started from another folder and could not find drizzle/. Run it from ~/community-library-demo.

Step 5 · Watch a test catch the double-lend bug

A test you have never seen fail proves little. Bring back part 6's bug on purpose: lending without first checking for an open loan. Keep a copy of the good file first:

Bash
cp src/lib/loan-rules.ts /tmp/loan-rules.ts.good

Open src/lib/loan-rules.ts and delete this one line in lendBook, then save:

TypeScript
      if (open) return { ok: false, reason: "on-loan" };

Run the unit tests again:

Bash
npm run test:unit

One test fails, "refuses a book that is already out, even from a second connection", with SqliteError: UNIQUE constraint failed: loans.book_id. Part 2's partial index still kept the data right, but the second librarian would have seen an error page instead of a message, and the test noticed. The member-limit rule has no index behind it, so for that rule the code is the only defence and the "fourth book" test is the only alarm.

Put the good file back and run the tests again:

Bash
cp /tmp/loan-rules.ts.good src/lib/loan-rules.ts
npm run test:unit

Check it worked

The last run ends with Tests 7 passed (7) again. If any test still fails, compare src/lib/loan-rules.ts with the listing in part 6.

Step 6 · Build a seeded database for the browser tests

The browser tests need a known starting point: the twenty seeded books, the three members and a librarian whose password the tests know. Build it in a separate file, data/e2e.db, from nothing before every run. The script refuses to touch any file whose name does not contain e2e, so a mistyped variable can never wipe data/library.db:

Bash
cat > scripts/e2e-db.ts <<'TS'
import { execFileSync } from "node:child_process";
import { randomBytes } from "node:crypto";
import { mkdirSync, rmSync } from "node:fs";
import { basename, dirname } from "node:path";
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { migrate } from "drizzle-orm/better-sqlite3/migrator";
import { connect } from "../src/db/connect";
import * as schema from "../src/db/schema";

async function main() {
  const file = process.env.DATABASE_FILE ?? "";
  const email = process.env.E2E_LIBRARIAN_EMAIL ?? "";
  const password = process.env.E2E_LIBRARIAN_PASSWORD ?? "";

  if (!basename(file).includes("e2e")) {
    throw new Error(`Refusing to rebuild "${file}". Set DATABASE_FILE to a file with e2e in its name.`);
  }
  if (!email || !password) {
    throw new Error("Set E2E_LIBRARIAN_EMAIL and E2E_LIBRARIAN_PASSWORD.");
  }

  // Start from nothing: the database and SQLite's -wal and -shm files.
  for (const suffix of ["", "-wal", "-shm"]) rmSync(file + suffix, { force: true });
  mkdirSync(dirname(file), { recursive: true });

  const db = connect(file);
  migrate(db, { migrationsFolder: "drizzle" });

  // The same seed script as part 2, pointed at this file.
  execFileSync("npx", ["tsx", "scripts/seed.ts"], {
    env: { ...process.env, DATABASE_FILE: file },
    stdio: "inherit",
  });

  // Create the librarian through Better Auth, so the password is hashed and
  // stored exactly as the app's own sign-in expects.
  const auth = betterAuth({
    database: drizzleAdapter(db, { provider: "sqlite", schema }),
    emailAndPassword: { enabled: true },
    secret: process.env.BETTER_AUTH_SECRET ?? randomBytes(32).toString("base64"),
    baseURL: process.env.BETTER_AUTH_URL ?? "http://localhost:3100",
  });
  await auth.api.signUpEmail({ body: { name: "Test Librarian", email, password } });

  db.$client.close();
  console.log(`Rebuilt ${file} with the seed data and one librarian.`);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
TS

Three things to know about it:

  • It uses migrate() and part 2's seed script rather than copying data/library.db, so the browser tests always run on the current schema and never on your library's real records.
  • It builds its own small Better Auth instance with sign-up switched on. Your app's instance from part 5 can keep sign-up off; both hash passwords the same default way, so the librarian created here can sign in to the app. If part 5 marks librarians in another way as well, for example with a role column, set that here too.
  • The email and password come from environment variables. Step 7 makes Playwright generate a new random password for every run, so there is no password in the code or in Git.

Check it worked

Build the file once by hand, with a throwaway password, and count what is in it:

Bash
DATABASE_FILE=data/e2e.db E2E_LIBRARIAN_EMAIL=check@example.com E2E_LIBRARIAN_PASSWORD="$(openssl rand -base64 18)" npm run e2e:db
node -e 'const db = require("better-sqlite3")("data/e2e.db", { readonly: true }); console.log(db.prepare("select (select count(*) from books) as books, (select count(*) from members) as members, (select count(*) from user) as librarians").get())'

The first command prints the seed script's Added 20 books, 3 members and 4 loans. and then Rebuilt data/e2e.db with the seed data and one librarian. The count prints { books: 20, members: 3, librarians: 1 }. Now check the guard:

Bash
{ DATABASE_FILE=data/library.db npm run e2e:db 2>&1 || true; } | grep -o 'Refusing to rebuild "data/library.db"'

It prints Refusing to rebuild "data/library.db" and your library's database is untouched. data/ is already in .gitignore from part 2, so e2e.db stays out of Git.

Step 7 · Configure Playwright to test the production build

Playwright's webServer option runs a command before the tests and stops it afterwards. Here the command rebuilds the test database, makes a production build against it and starts it on port 3100, so it never clashes with a dev server on 3000:

Bash
cat > playwright.config.ts <<'TS'
import { randomBytes } from "node:crypto";
import { defineConfig, devices } from "@playwright/test";

const port = 3100;
const baseURL = `http://localhost:${port}`;

// New credentials and auth secret for every run. Workers inherit these
// variables from the main Playwright process, so all of them see the same values.
const env = process.env;
env.E2E_LIBRARIAN_EMAIL ??= "librarian@e2e.example.com";
const password = (env.E2E_LIBRARIAN_PASSWORD ??= randomBytes(18).toString("base64url"));
const authSecret = (env.E2E_AUTH_SECRET ??= randomBytes(32).toString("base64"));

export default defineConfig({
  testDir: "tests/e2e",
  // The tests share one database, so run them one at a time, in file order.
  fullyParallel: false,
  workers: 1,
  reporter: "list",
  use: {
    baseURL,
    trace: "retain-on-failure",
  },
  projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
  webServer: {
    command: `npm run e2e:db && npm run build && npm run start -- --port ${port}`,
    url: baseURL,
    reuseExistingServer: false,
    timeout: 300_000,
    env: {
      DATABASE_FILE: "data/e2e.db",
      E2E_LIBRARIAN_PASSWORD: password,
      BETTER_AUTH_SECRET: authSecret,
      BETTER_AUTH_URL: baseURL,
    },
  },
});
TS

Why each setting is there:

  • Production build, not the dev server. Part 7's caching only behaves like production in next build plus next start. A test against next dev would pass even if a cached page showed a lent book as on the shelf.
  • reuseExistingServer: false. Every run gets a fresh database and build. A leftover server from a crashed run would make the tests start from yesterday's data, so Playwright stops with an error if port 3100 is busy.
  • timeout: 300_000. Five minutes for the database, the build and the first response. A build on a small laptop can take two or three minutes.
  • The env block is added to Playwright's own environment for the server command. Next.js reads real environment variables before .env.local, so these win over your part 5 settings for this run only.
  • trace: "retain-on-failure" keeps a recording of any failing test in test-results/, which you can open with npx playwright show-trace.

Check it worked

Load the config the way Playwright will and print three of its settings:

Bash
npx tsx --eval 'const config = require("./playwright.config.ts").default; console.log(config.webServer.url, config.workers, config.testDir)'

It prints http://localhost:3100 1 tests/e2e. A typing mistake in the file shows up here as an error with a line number instead.

Step 8 · Test the librarian journey in the browser

Write three tests: what a visitor sees, the full librarian journey, and the double-lend case from part 6 as a librarian with two tabs open would meet it:

Bash
mkdir -p tests/e2e
cat > tests/e2e/library.spec.ts <<'TS'
import { expect, test, type Page } from "@playwright/test";
import Database from "better-sqlite3";

// Book ids from part 2's seed script.
const WEEP_NOT_CHILD = 3;
const SO_LONG_A_LETTER = 4;

async function signIn(page: Page) {
  await page.goto("/sign-in");
  await page.getByLabel("Email").fill(process.env.E2E_LIBRARIAN_EMAIL ?? "");
  await page.getByLabel("Password").fill(process.env.E2E_LIBRARIAN_PASSWORD ?? "");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page).not.toHaveURL(/\/sign-in/);
}

// Read the test database directly: the page can only show what the app chose to show.
function openLoansFor(bookId: number) {
  const db = new Database("data/e2e.db", { readonly: true });
  try {
    const row = db
      .prepare("select count(*) as open from loans where book_id = ? and returned_at is null")
      .get(bookId) as { open: number };
    return row.open;
  } finally {
    db.close();
  }
}

test("a visitor sees the shelf status but no lending controls", async ({ page }) => {
  await page.goto(`/books/${WEEP_NOT_CHILD}`);

  await expect(page.getByRole("heading", { level: 1 })).toHaveText("Weep Not, Child");
  await expect(page.getByText("On the shelf").first()).toBeVisible();
  await expect(page.getByRole("button", { name: "Lend" })).toHaveCount(0);
});

test("a librarian adds a book, lends it and takes it back", async ({ page }) => {
  const title = "Market Day Stories";
  await signIn(page);

  await page.goto("/books/new");
  await page.getByLabel("Title").fill(title);
  await page.getByLabel("Author").fill("Test Author");
  await page.getByLabel("Year").fill("2024");
  await page.getByRole("button", { name: "Add book" }).click();

  await expect(page.getByRole("heading", { level: 1 })).toHaveText(title);
  await expect(page.getByText("On the shelf").first()).toBeVisible();

  await page.getByLabel("Member").selectOption({ label: "Ama Mensah" });
  await page.getByRole("button", { name: "Lend" }).click();
  await expect(page.getByText(/^On loan/).first()).toBeVisible();
  await expect(page.getByRole("button", { name: "Lend" })).toHaveCount(0);

  await page.getByRole("button", { name: "Return" }).click();
  await expect(page.getByText("On the shelf").first()).toBeVisible();
  await expect(page.getByRole("button", { name: "Lend" })).toBeVisible();
});

test("lending from a stale second tab does not lend the book twice", async ({ context }) => {
  const firstTab = await context.newPage();
  await signIn(firstTab);
  const secondTab = await context.newPage();
  for (const tab of [firstTab, secondTab]) {
    await tab.goto(`/books/${SO_LONG_A_LETTER}`);
    await expect(tab.getByRole("button", { name: "Lend" })).toBeVisible();
  }

  await firstTab.getByLabel("Member").selectOption({ label: "Ama Mensah" });
  await firstTab.getByRole("button", { name: "Lend" }).click();
  await expect(firstTab.getByText(/^On loan/).first()).toBeVisible();

  // The second tab still shows the form from before the loan.
  await secondTab.getByLabel("Member").selectOption({ label: "Chukwuemeka Obi" });
  const lend = secondTab.waitForResponse((response) => response.request().method() === "POST");
  await secondTab.getByRole("button", { name: "Lend" }).click();
  const response = await lend;
  await response.finished();

  expect(response.status(), "a refusal, not a server error").toBeLessThan(500);
  await expect(secondTab).toHaveURL(/problem=on-loan/);
  await expect(secondTab.getByText("This book was already on loan, so it was not lent again.")).toBeVisible();
  expect(openLoansFor(SO_LONG_A_LETTER)).toBe(1);
  await secondTab.reload();
  await expect(secondTab.getByText(/^On loan/).first()).toBeVisible();
});
TS
npm run test:e2e

How the third test works. Both tabs share one browser context, so they share the sign-in cookie, like one librarian with the same book open twice. The first tab lends the book. The second tab's page was loaded before that, so it still offers Lend. Clicking it sends a server action, which is an HTTP POST, and waitForResponse catches it. The test then checks the refusal the way the librarian meets it and the way the database records it. The action answered without a server error: part 6's action refuses by redirecting back to the book page, so the test does not pin an exact status, only one below 500, while a crash from the unique index would be a 500. The second tab lands on ?problem=on-loan and shows part 6's message, "This book was already on loan, so it was not lent again." And the database, which the screen cannot show, holds exactly one open loan for the book.

getByText(/^On loan/) matches any text that starts with "On loan", so "On loan" and "On loan to Ama Mensah" both pass. .first() is there because a page may show the status in more than one place.

Check it worked

The first run takes a few minutes: Playwright prints nothing while the database is rebuilt and the app builds, then lists the tests:

Text
Running 3 tests using 1 worker

  ✓  1 [chromium] › tests/e2e/library.spec.ts:29:1 › a visitor sees the shelf status but no lending controls (412ms)
  ✓  2 [chromium] › tests/e2e/library.spec.ts:37:1 › a librarian adds a book, lends it and takes it back (2.1s)
  ✓  3 [chromium] › tests/e2e/library.spec.ts:60:1 › lending from a stale second tab does not lend the book twice (1.8s)

  3 passed (2.4m)

Your timings and line numbers will differ. If the librarian tests time out in signIn on getByLabel("Email"), your part 5 form labels its field differently: open /sign-in, read the label, and change the locator. When a test fails, test-results/ holds its trace; npx playwright show-trace followed by the path to trace.zip opens a step-by-step replay.

Step 9 · Run the whole suite and rebuild for your own data

npm test runs the unit tests first and stops there if any fail, which saves you the build. When they pass, it runs the browser tests:

Bash
npm test

The browser tests left a production build in .next that was made from data/e2e.db, and part 7's caching may have stored pages from it. Before you start the app on your own library's data again, rebuild it:

Bash
npm run build

Check it worked

npm test ends with Tests 7 passed (7) from Vitest and 3 passed from Playwright, and exits with status 0 (echo $? prints 0). The final npm run build finishes with the route table from part 7, made from data/library.db. Run npm test before every commit that touches lending, sign-in or caching, and, as part 9 says, on your laptop before each deploy, so a broken build never reaches the server.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.