Vitest has left us at a clear boundary: it can't render async components, it doesn't know what 'use cache' is, it doesn't stream anything and it has no cookies. In other words, it tests almost none of what makes a Next.js application special. For that you have to actually run it, built, with its database, and use it from a browser.
Playwright automates that use: it opens pages, fills in fields, clicks and checks what's visible, in Chromium, Firefox and WebKit. These tests are the ones that most resemble a person, and also the slowest and most delicate, so there should be few of them and they should be well chosen. You'll write the ones for AgendaViva's main flows, the permission tests, the accessibility tests and the ones that freeze the shell to check what appears instantly. If you want to go deeper into the tool, the portal has a Playwright with TypeScript course; here we focus on what changes with Next.js.
- What to test against
The documentation recommends running tests against the production build, and with Cache Components that's more important than ever: in development there's no prefetching, the cache behaves differently, errors are shown differently and routes are compiled when visited, with waits that don't exist outside it.
That sets an order, because our build reads the database (05-02):
flowchart LR
A["Migrate and seed<br/>agendaviva_e2e"] --> B["next build"]
B --> C["next start :3100"]
C --> D["Sign in and save<br/>the sessions"]
D --> E["Tests"]
We use a separate database and a separate port. That way the development application can keep running, and no test touches its data. The configuration goes in its own file, which is committed because it contains no real secrets:
docker compose exec db createdb -U agendaviva agendaviva_e2e # Once
npm install -D @playwright/test @next/playwright@16 @axe-core/playwright
npx playwright install chromium firefox# .env.e2e
DATABASE_URL=postgresql://agendaviva:agendaviva_local@localhost:5432/agendaviva_e2e
NEXT_PUBLIC_SITE_URL=http://localhost:3100
INTERNAL_URL=http://localhost:3100
QUERY_DELAY_MS=0
TRUSTED_PROXIES=0
EXPOSE_TESTING_API=1
# Empty on purpose: they override whatever is in .env.local
SITE_NOTICE=
WEATHER_URL=
MAIL_URL=
OIDC_ISSUER={
"scripts": {
"e2e:data": "node --env-file=.env.e2e node_modules/drizzle-kit/bin.cjs migrate && node --env-file=.env.e2e --import tsx scripts/seed.ts",
"e2e:build": "node --env-file=.env.e2e node_modules/next/dist/bin/next build",
"e2e:server": "node --env-file=.env.e2e node_modules/next/dist/bin/next start --port 3100",
"e2e": "playwright test",
"e2e:all": "npm run e2e:data && npm run e2e:build && npm run e2e"
}
}node --env-fileloads the variables before Next.js does. Whatever is already in the environment takes precedence over.env.local, even if it's empty, and in our schema an empty string means "not configured" (06-03). Hence the last four lines.@next/playwrightmust have the same major version as Next.js; we'll talk about it in section 6.- Mail and the forecast are switched off. A test mustn't depend on an external service or write to anyone.
- Add to
.gitignore!.env.e2e,/playwright/.auth/,/test-results/and/playwright-report/.
Seeding also empties attempts and the sessions, so every run starts with no limits used up. Building takes a minute; while you're writing tests without touching the application, npm run e2e is enough.
- The configuration
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test'
const BASE_URL = 'http://localhost:3100'
export default defineConfig({
testDir: './e2e',
fullyParallel: true,
forbidOnly: Boolean(process.env.CI),
retries: process.env.CI ? 1 : 0,
reporter: process.env.CI ? [['github'], ['html', { open: 'never' }]] : 'list',
use: {
baseURL: BASE_URL,
locale: 'en-US',
timezoneId: 'America/Bogota', // The guide must show Vallenar's time all the same
trace: 'on-first-retry',
},
projects: [
{ name: 'sessions', testMatch: /.*\.setup\.ts/ },
{ name: 'chromium', use: devices['Desktop Chrome'], dependencies: ['sessions'] },
{ name: 'firefox', use: devices['Desktop Firefox'], dependencies: ['sessions'], grep: /@all/ },
{ name: 'mobile', use: devices['Pixel 7'], dependencies: ['sessions'], grep: /@mobile/ },
],
webServer: {
command: 'npm run e2e:server',
url: BASE_URL,
reuseExistingServer: !process.env.CI,
stdout: 'pipe', // The server log, alongside the test log
gracefulShutdown: { signal: 'SIGTERM', timeout: 5000 },
},
})webServerstarts the application and waits for it to respond. It doesn't build: if you forget to, you'll test the previous version. That's the price of being able to repeat quickly.- A single browser for almost everything. Chromium runs the whole suite; the others, only what's tagged with
@allor@mobile. Multiplying every test by three rarely multiplies the bugs found by three. trace: 'on-first-retry'saves, when something fails and is retried, a recording with the DOM, the network and the console at every step.npx playwright show-traceopens it. It's the best tool for a failure that only happens in CI.- The distant time zone is a free test: if any date were formatted in the browser, it would show up seven hours off.
What about WebKit? Our session cookie carries Secure and the __Host- prefix when built for production. Chromium and Firefox accept it on http://localhost; WebKit treats Secure cookies over HTTP differently and may reject them. For signed-in tests on that engine, serve the application over HTTPS, for example in a review environment. What you must not do is weaken the cookie to make the test pass.
- Saved sessions
Signing in through the form before every test is slow: our sign-in is deliberately slow (scrypt, 08-02). And on top of that it gets blocked, because after ten attempts per account in fifteen minutes the rate limit kicks in. You sign in once per role and save the browser state.
// e2e/accounts.ts
import { DEV_PASSWORD } from '../scripts/seed-data'
export { DEV_PASSWORD }
export const ACCOUNTS = {
visitor: { email: '[email protected]', file: 'playwright/.auth/visitor.json' },
organizer: { email: '[email protected]', file: 'playwright/.auth/organizer.json' },
admin: { email: '[email protected]', file: 'playwright/.auth/admin.json' },
} as const
// e2e/sessions.setup.ts
import { expect, test as setup } from '@playwright/test'
import { ACCOUNTS, DEV_PASSWORD } from './accounts'
for (const [role, { email, file }] of Object.entries(ACCOUNTS)) {
setup(`sign in as ${role}`, async ({ page }) => {
await page.goto('/sign-in')
await page.getByRole('textbox', { name: 'Email' }).fill(email)
await page.getByLabel('Password').fill(DEV_PASSWORD)
await page.getByRole('button', { name: 'Sign in' }).click()
await expect(page.getByRole('button', { name: 'Sign out' })).toBeVisible()
await page.context().storageState({ path: file })
})
}The sessions project runs before the others because of dependencies. It waits to see "Sign out" before saving: until then the cookie might not be there. The files contain valid tokens, even if they're test ones; hence the .gitignore.
Don't set a default session in the configuration. Each test file declares who it signs in as, and if it doesn't, an anonymous visitor comes in, which is the normal case on a public website.
3.1. The console gets tested too
In 08-05 we said that a CSP block would show up as a console error and that it was worth turning it into a failure. It's done by extending test:
// e2e/base.ts
import { expect, test as base } from '@playwright/test'
const SERIOUS = /content security policy|hydrat|minified react error/i
export const test = base.extend<{ watchConsole: void }>({
watchConsole: [
async ({ page }, use) => {
const failures: string[] = []
page.on('pageerror', (error) => failures.push(error.message))
page.on('console', (message) => {
if (message.type() === 'error' && SERIOUS.test(message.text())) failures.push(message.text())
})
await use()
expect(failures, 'browser errors').toEqual([])
},
{ auto: true },
],
})
export { expect }Every test imports from here. auto: true enables it without asking for it. It covers exceptions, CSP blocks and hydration errors, which in production arrive summarized as a numbered React error. We don't include every console error, because the browser also logs the 404s some tests cause on purpose.
- Flows
// e2e/booking.spec.ts
import { ACCOUNTS } from './accounts'
import { expect, test } from './base'
test.describe('signed in', () => {
test.use({ storageState: ACCOUNTS.visitor.file })
test('books and cancels @all', async ({ page }) => {
await page.goto('/events/smartphone-photography')
await page.getByRole('spinbutton', { name: 'Spots' }).fill('2')
await page.getByRole('button', { name: 'Book' }).click()
await expect(page.getByRole('status').filter({ hasText: 'You\'ve booked 2 spots.' })).toBeVisible()
await expect(page.getByRole('button', { name: 'Book' })).toHaveCount(0)
await page.getByRole('link', { name: 'Manage my bookings' }).click()
await expect(page.getByRole('heading', { level: 1, name: 'My bookings' })).toBeVisible()
const cancel = page.getByRole('button', { name: 'Cancel the booking for Smartphone photography' })
await cancel.click()
await expect(page.getByRole('status').filter({ hasText: 'You\'ve canceled your booking' })).toBeVisible()
await page.reload() // Optimistic doesn't count: let the server say so
await expect(page.getByRole('heading', { level: 1, name: 'My bookings' })).toBeVisible()
await expect(page.getByRole('link', { name: 'Riverside Quartet' })).toBeVisible()
await expect(cancel).toHaveCount(0)
})
})
test('signed out, it sends you to sign in and back @mobile', async ({ page }) => {
await page.goto('/events/paper-and-ink')
await page.getByRole('link', { name: 'Sign in to book' }).click()
await expect(page).toHaveURL('/sign-in?returnTo=%2Fevents%2Fpaper-and-ink')
})- Assertions wait on their own.
expect(…).toBeVisible()retries for up to five seconds. That's all you need for streaming, actions and navigations: you wait for what the person would see. Don't usewaitForTimeout, which is either too long or too short, ornetworkidle:LiveAvailabilitypolls every twenty seconds and the page is never still. - Before checking for absence, check for presence.
toHaveCount(0)is also satisfied by a blank page. That's why the test first waits for the heading and for another booking. - The reload is essential after an optimistic update. Without it, the test would pass even if the server hadn't deleted anything.
- It works the same with slow JavaScript: forms with Server Actions queue the submission until they hydrate (06-01).
4.1. Hidden pages
With Cache Components, visited routes aren't unmounted: they stay in the document, hidden with <Activity> (02-01). After navigating from the event page to "My bookings" there are two pages in the DOM, and an ordinary locator can find the other one's element. Playwright flags it with a strict mode error, or waits forever for something hidden to become visible.
| Locator | Does it find hidden elements? | What to do |
|---|---|---|
getByRole |
No: it uses the accessibility tree | Always prefer it |
getByText, getByLabel, locator |
Yes | Add .filter({ visible: true }) |
It's what the documentation recommends, and one more reason for everything important to have a role and a name. In sessions.setup.ts we use getByLabel for the password, which doesn't have the textbox role; it works because it's the first page visited.
4.2. Several people
The publishing flow involves three roles. Each one needs its own context, that is, a browser with nothing in common with the others:
// e2e/publishing.spec.ts
import { createSlug } from '../lib/slug'
import { ACCOUNTS } from './accounts'
import { expect, test } from './base'
test('from draft to published', async ({ browser, page: anonymous }) => {
const title = `Test recital ${crypto.randomUUID().slice(0, 8)}`
const eventPage = `/events/${createSlug(title)}`
// It doesn't exist yet: a real 404, thanks to the proxy (07-02)
expect((await anonymous.goto(eventPage))?.status()).toBe(404)
const organizer = await browser.newPage({ storageState: ACCOUNTS.organizer.file })
await organizer.goto('/dashboard/events/new')
await organizer.getByRole('textbox', { name: 'Title' }).fill(title)
await organizer.getByRole('combobox', { name: 'Category' }).selectOption('concert')
await organizer.getByRole('textbox', { name: 'Summary' }).fill('A recital that only exists in the tests.')
await organizer.getByRole('textbox', { name: 'Description' }).fill('Some sample text. '.repeat(8))
await organizer.getByRole('combobox', { name: 'Venue' }).selectOption({ label: 'Mill Theater' })
await organizer.getByRole('spinbutton', { name: 'Capacity' }).fill('50')
await organizer.getByLabel('Start').fill('2028-07-01T20:00')
await organizer.getByLabel('End').fill('2028-07-01T21:30')
await organizer.getByRole('button', { name: 'Submit for review' }).click()
await expect(organizer).toHaveURL('/dashboard/events')
const admin = await browser.newPage({ storageState: ACCOUNTS.admin.file })
await admin.goto('/admin')
const pending = admin.getByRole('listitem').filter({ hasText: title })
await pending.getByRole('button', { name: 'Publish' }).click()
await expect(pending).toHaveCount(0)
// The cache has been invalidated: the event page and the listing show it
expect((await anonymous.goto(eventPage))?.status()).toBe(200)
await expect(anonymous.getByRole('heading', { level: 1, name: title })).toBeVisible()
await anonymous.goto('/events?category=concert&page=1')
await expect(anonymous.getByRole('link', { name: title })).toBeVisible()
await organizer.close()
await admin.close()
})Adjust the labels to those of your form. A single test checks creation, the rules, the review, the admin permission, invalidateEvent, the negative response the proxy had stored and the listing. It's long, and it's one of those that deserves to be: if it fails, something important has broken.
- Each test creates its own data with a unique name. That way it can run twice, or in parallel with others, without them stepping on each other. The booking test uses an event and a person no other test touches, and undoes what it did.
newPage({ storageState })creates a separate context. These pages don't get the console watcher, which belongs topage; if you care, extract the listener into a function and call it with each one.createSlugis imported from the real code. It's neutral, so the tests can use it.- Fixed dates expire. The seed data is from 2028. When that year comes, the listings will be empty and everything will fail at once: don't let anyone spend a day investigating it. Seeding relative to the current date would avoid it, at the cost of variable text.
- Permissions
The 10-03 tests proved ownership in the data. These check the whole: proxy, page and action, with real sessions. Every cell in the permissions table from 08-04 can be a test case.
// e2e/permissions.spec.ts
import { ACCOUNTS } from './accounts'
import { expect, test } from './base'
for (const path of ['/dashboard/events', '/admin', '/my-bookings', '/dashboard/events/evt-01/edit']) {
test(`${path} requires a session`, async ({ page }) => {
await page.goto(path)
await expect(page).toHaveURL(`/sign-in?returnTo=${encodeURIComponent(path)}`)
})
}
const FORBIDDEN = [
{ role: 'visitor', path: '/dashboard/events', secret: 'New event' },
{ role: 'organizer', path: '/admin', secret: 'Publish' },
{ role: 'organizer', path: '/dashboard/events/evt-08/edit', secret: 'Summer Choir' }, // Belongs to usr-03
{ role: 'admin', path: '/dashboard/events/evt-08/edit', secret: 'Summer Choir' },
] as const
for (const { role, path, secret } of FORBIDDEN) {
test.describe(role, () => {
test.use({ storageState: ACCOUNTS[role].file })
test(`doesn't see ${path}`, async ({ page }) => {
const response = await page.goto(path)
await expect(page.getByRole('heading', { name: /not found/i })).toBeVisible()
expect(await response?.text()).not.toContain(secret)
})
})
}The last line looks at the HTML received, not at what's visible. A piece of data that arrived in the RSC Payload and isn't rendered is a leak all the same (03-03), and this is the only way to catch it. The HTTP status here is 200, because notFound() acts after the shell (02-04); don't check it.
There's still the door that doesn't go through the pages: calling an action by hand. You can intercept a legitimate request and change one of its arguments:
// e2e/permissions.spec.ts (continued)
test.describe('a tampered action', () => {
test.use({ storageState: ACCOUNTS.visitor.file })
test('does not cancel with a made-up identifier', async ({ page }) => {
await page.route('**/my-bookings', async (route) => {
const isAction = route.request().method() === 'POST'
await route.continue(isAction ? { postData: JSON.stringify(['someone-elses-booking']) } : {})
})
await page.goto('/my-bookings')
const cancel = page.getByRole('button', { name: 'Cancel the booking for Jazz Night' })
// The promise, before the click: if it were created afterwards, the response could arrive first
const response = page.waitForResponse((r) => r.request().method() === 'POST')
await cancel.click()
await response
await page.reload()
await expect(cancel).toBeVisible()
})
})Your own booking is still there, because the server received a different identifier, and the other person's wasn't touched, as the integration test proves. The body format is internal to Next.js and may change: if the test fails after an upgrade, look at the request first. That's why there's one like this, and the bulk of the permissions is tested in the data.
- The shell and instant navigation
In 10-02 you used the Navigation Inspector to see the shell. @next/playwright offers the same for tests: inside instant(), the server and the router deliver only what's prerendered and prefetched; on leaving, the rest is released.
It's experimental, both the package and the option that enables it in a production build. The option is enabled only in the test build:
// next.config.ts (in experimental, next to serverActions)
exposeTestingApiInProductionBuild: process.env.EXPOSE_TESTING_API === '1',// e2e/shell.spec.ts
import { instant } from '@next/playwright'
import { expect, test } from './base'
test('the event page shows the important part without waiting for the server', async ({ page, baseURL }) => {
const title = page.getByRole('heading', { level: 1, name: 'Jazz Night' })
const spots = page.getByText(/\d+ of \d+ spots left/).filter({ visible: true })
await instant(
page,
async () => {
await page.goto('/events/jazz-night')
await expect(title).toBeVisible() // Cached and prerendered
await expect(spots).toHaveCount(0) // Uncached: not yet
},
{ baseURL },
)
await expect(spots).toBeVisible()
})
test('navigating from the home page to the guide is instant', async ({ page }) => {
await page.goto('/')
await instant(page, async () => {
await page.getByRole('navigation', { name: 'Main' }).getByRole('link', { name: 'Events' }).click()
await page.waitForURL('**/events')
await expect(page.getByRole('heading', { level: 1, name: 'Event guide' })).toBeVisible()
})
})Adjust the titles to yours. The first test is worth a whole module: if someone removes the 'use cache' from getEventDetails, or wraps the event page in a boundary with a cookie above it, it fails. And the other way round: if the availability gets cached by mistake, it fails too.
- Each way of arriving is tested separately.
gotoexamines the static shell; the click, what was prefetched below the shared layout. baseURLis needed whengotois the first navigation, because the mechanism uses a cookie and needs to know the origin.- Wait for the address before checking. An
<h1>from the previous page could satisfy the assertion. - Don't publish a build with
EXPOSE_TESTING_API=1. The variable must be set at build time and at start-up. - The cookie is shared between
localhostports. If another development application gets "frozen", delete it:next-instant-navigation-testing.
Since it's experimental, isolate these tests in their own file. If a version changes them, they can be adapted or skipped without dragging the others along.
- Accessibility
axe analyzes the page and detects objective defects: insufficient contrast, controls without a name, badly nested headings, incorrect ARIA attributes.
// e2e/accessibility.spec.ts
import { AxeBuilder } from '@axe-core/playwright'
import { expect, test } from './base'
const PATHS = ['/', '/events', '/events/jazz-night', '/venues', '/sign-in', '/sign-up']
for (const path of PATHS) {
for (const theme of ['light', 'dark'] as const) {
test(`${path} in ${theme} has no accessibility defects`, async ({ page }) => {
await page.emulateMedia({ colorScheme: theme })
await page.goto(path)
await expect(page.getByRole('heading', { level: 1 })).toBeVisible()
const { violations } = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag21aa', 'wcag22aa'])
.analyze()
expect(violations.map(({ id, nodes }) => `${id}: ${nodes[0].target}`)).toEqual([])
})
}
}Both themes are tested because the contrasts are different (09-01); with the "system" preference, which is the initial one, emulateMedia is enough to switch them. The test waits for the heading, so as not to analyze a half-loaded page; on one with important holes, wait for their content too. The list is reduced to text so the failure can be read without expanding an object.
An automated tool finds some of the problems, not all of them. It doesn't know whether an alt describes the image well, whether the focus order makes sense or whether the modal can be used with a screen reader. Add what can be automated and review the rest by hand:
test('the quick view opens and closes with the keyboard', async ({ page }) => {
await page.goto('/events')
await page.getByRole('link', { name: 'Jazz Night' }).press('Enter')
const dialog = page.getByRole('dialog', { name: 'Event quick view' })
await expect(dialog).toBeVisible()
await page.keyboard.press('Escape')
await expect(dialog).toHaveCount(0)
await expect(page).toHaveURL('/events')
})
- Tests that fail sometimes
A flaky test is worse than none: it teaches you to ignore failures. The cause is almost always one of these:
| Symptom | Cause | Remedy |
|---|---|---|
| Fails only in parallel | Two tests touch the same data | Each test with its own data |
| Fails the second time | It leaves leftovers, or expects the freshly seeded database | Create, use and undo; unique names |
| "Too many attempts" | Signing in through the form in every test | Saved sessions |
| Strict mode: two elements | A page hidden with <Activity> |
getByRole, or visible: true |
| Sees stale data | The cache responds, and the test wrote underneath it, in the database | Write through the application, which invalidates; or rebuild after seeding |
| Fails on a slow machine | Fixed waits | Assertions that retry |
| Fails at the end of the month, or in October | Dates relative to today, daylight saving change | Fixed dates and an explicit time zone |
The fifth row is specific to this world. If you change a title with SQL, the event page will keep showing the old one, and it's right: nobody notified it. Reseeding without rebuilding leaves shells that talk about data that no longer exists. That's why e2e:all seeds first.
retries: 1 in CI keeps one stumble from stopping everyone, but a test that passes on the second attempt is flagged as flaky in the report. Treat it as a bug: fix it or remove it.
How many? Enough to cover what can't break. In AgendaViva, about twenty: booking, canceling, signing in, signing up, publishing, the permissions, the shell, accessibility and the route status codes (404, 308, 503). Everything else, lower down the pyramid.
Common Mistakes and Tips
- Testing against
next devand believing you've tested prefetching or the cache. - Forgetting to build after changing the application.
waitForTimeoutandnetworkidle.- Checking for absence without having checked for presence.
- Not reloading after an optimistic update.
- Locators based on CSS classes or position.
- Sharing data between tests, or depending on their order.
- Signing in through the form in every one.
- Weakening security (cookies, CSP, limits) to make them pass.
- Committing the session states.
- Publishing the test build.
- Repeating here what Vitest already tests: twenty filter combinations in a browser.
Exercises
Exercise 1: status codes and headers
Without opening pages, using request, check: 200 on /events/jazz-night, 404 on /events/does-not-exist and /events/wp-login.php, 308 from /events/Jazz-Night to lowercase, that pages, including error pages, carry the CSP and nosniff, and that /api/v1/events doesn't contain organizerId.
Solution
// e2e/http.spec.ts
import { expect, test } from '@playwright/test'
for (const [path, status] of [
['/events/jazz-night', 200],
['/events/does-not-exist', 404],
['/events/wp-login.php', 404],
['/events/Jazz-Night', 308],
] as const) {
test(`${path} responds ${status}`, async ({ request }) => {
const response = await request.get(path, { maxRedirects: 0 })
expect(response.status()).toBe(status)
const headers = response.headers()
if (status === 308) {
expect(headers.location).toContain('/events/jazz-night')
} else {
expect(headers['x-content-type-options']).toBe('nosniff')
expect(headers['content-security-policy']).toContain("frame-ancestors 'none'")
}
})
}
test('the API does not publish internal fields', async ({ request }) => {
const text = await (await request.get('/api/v1/events')).text()
expect(text).toContain('jazz-night') // Presence, before absence
expect(text).not.toMatch(/organizerId|@example\.com/)
})There's no browser, so they take milliseconds. They're the cheapest tests at this level, and they catch what breaks when you touch proxy.ts or next.config.ts. They don't use ./base, because there's no console to watch.
Exercise 2: fixing a flaky test
It fails one time in ten. List the causes and rewrite it.
test('marks a favorite', async ({ page }) => {
await page.goto('/events', { waitUntil: 'networkidle' })
await page.locator('.text-xl').first().click()
await page.waitForTimeout(500)
await page.goto('/events/jazz-night')
expect(await page.getByLabel('Favorite').getAttribute('aria-pressed')).toBe('true')
})Solution
test('a favorite is kept when changing pages', async ({ page }) => {
const star = page.getByRole('button', { name: 'Favorite: Jazz Night' })
await page.goto('/events')
await expect(star).toBeVisible()
await expect(async () => {
await star.click()
await expect(star).toHaveAttribute('aria-pressed', 'true', { timeout: 500 })
}).toPass()
await page.goto('/events/jazz-night')
await expect(star).toHaveAttribute('aria-pressed', 'true')
})networkidle doesn't mean "ready". The class selector picks the first large text, which may not be the star, and the first event isn't necessarily the jazz one. The fixed wait is either too long or too short. getAttribute reads once, perhaps before hydration.
The tricky case is the last one: a button with onClick receives the click and does nothing if React hasn't hydrated it yet. With a form and an action that doesn't happen, but here it does. toPass repeats the block until it takes effect: click, and check it right away. Since toggling twice would unmark it, the attempt is only repeated if the previous one did not take effect. That a person could suffer the same thing is, by the way, one more argument for hydrating little and early.
Exercise 3: the complete sign-up
Sign-up sends a link by email (08-02). How would you test it end to end without a real mail server? Outline the steps and say what you'd leave out.
Solution
With the scripts/mail-api.mjs mock as a second server. In webServer you can declare a list, and in .env.e2e MAIL_URL would point to it. The mock would have to store the messages and offer them through a GET /messages?to=….
Steps: fill in /sign-up with a unique email address; check the neutral message; ask the mock for the message, retrying with expect.poll because it's sent after responding (07-04); extract the link; open it; check that opening it does not create the account, by requesting it twice; choose a password and see "Sign out". To finish, use the same link again and check that it's rejected.
And a second case: sign up with [email protected], check that the screen says exactly the same thing and that the email is the other one. Left out are the response time, which can't be measured well here, and the rate limits, which the integration tests already cover and which would use up the other tests' quota.
Conclusion
End-to-end tests use the built AgendaViva, with its own database seeded before building. They sign in once per role, search by role and name, wait for what's visible and check the result after reloading. They cover the flows that can't break, permissions with real sessions, accessibility and, with instant(), that the important part stays in the shell. And they treat the console as part of the result.
All these tests happen before publishing, with made-up data and in an environment we control. Afterwards come people, browsers and loads nobody foresaw, and the question changes: it's no longer whether it works, but how we'll find out that it has stopped working, and what information we'll have to know why. The last lesson of the module is Debugging, Instrumentation and Observability.
