Throughout the course we've been leaving behind functions "to be tested in 10-03": the filters, the dates, the webhook signature, the destination after signing in. That wasn't by chance. They were written as pure functions, receiving the time or the environment as an argument, precisely so that testing them would be easy. The time has come to collect.
An automated test repeats a check every time the code changes. Unit tests are fast and precise: they tell you which function fails and with what input. In this lesson you'll set up Vitest in a Next.js project, where you have to resolve aliases, server-only modules and components that run in two places; you'll test logic, client components, Server Actions and queries against a real database, and you'll see where the line is beyond which another tool makes more sense.
- What to test at each level
| Level | What it runs | Takes | In AgendaViva |
|---|---|---|---|
| Types and linter | Nothing: it analyzes | Seconds | npm run typecheck, npm run lint |
| Unit | A function, with no network or database | Milliseconds | lib/, actions with their dependencies replaced |
| Component | A Client Component in a simulated browser | Tens of milliseconds | Forms, buttons |
| Integration | Queries against PostgreSQL | Hundreds of milliseconds | lib/data/: transactions, ownership |
| End-to-end | The built application in a real browser | Seconds | Complete flows (10-04) |
The question isn't how many tests to write, but which failure each one would catch. A practical rule of thumb:
- Test whatever has decisions: conditions, calculations, edge cases, permission rules.
- Don't test what only connects pieces, or what something else already guarantees: that Drizzle builds SQL, that React renders a
<p>or that Next.js redirects. - Every bug that reaches production first comes in as a failing test.
With Next.js there's a catch. Async Server Components, which are most of our components, can't be rendered with Vitest: the documentation recommends end-to-end tests for them. That's why the usual split in other React applications, with lots of component tests, leans both ways here: more pure functions at the bottom and more flows at the top.
- Setup
npm install -D vitest vite @vitejs/plugin-react jsdom
npm install -D @testing-library/react @testing-library/dom @testing-library/user-event @testing-library/jest-domWe'll use Vitest 5, on top of Vite 8, with Testing Library. These versions require a more modern Node than Next.js does: Vitest, 22.12 or later, and jsdom 31, the latest 22 or 24. Work with a current LTS version, as recommended in 01-02. Vite is only used to run the tests; the application is still built with Turbopack.
// vitest.config.mts
import { fileURLToPath } from 'node:url'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vitest/config'
import { TEST_DB_URL } from './tests/db/url'
const empty = fileURLToPath(new URL('./tests/empty.ts', import.meta.url))
export default defineConfig({
plugins: [react()],
resolve: {
tsconfigPaths: true, // The @/* alias from tsconfig.json
alias: { 'server-only': empty, 'client-only': empty },
},
test: {
projects: [
{
test: {
name: 'unit',
environment: 'node',
include: ['{lib,actions,app}/**/*.test.ts'],
},
},
{
test: {
name: 'components',
environment: 'jsdom',
include: ['{components,app}/**/*.test.tsx'],
setupFiles: ['./tests/setup-dom.ts'],
},
},
{
test: {
name: 'db',
environment: 'node',
include: ['tests/db/**/*.test.ts'],
globalSetup: ['./tests/db/migrate.ts'],
setupFiles: ['./tests/db/mocks.ts'],
env: { DATABASE_URL: TEST_DB_URL },
},
},
],
},
})// tests/empty.ts
export {}
// tests/setup-dom.ts
import '@testing-library/jest-dom/vitest'
import { cleanup } from '@testing-library/react'
import { afterEach } from 'vitest'
afterEach(cleanup) // Removes what was rendered from the document{
"scripts": {
"test": "vitest run --project unit --project components",
"test:watch": "vitest --project unit --project components",
"test:db": "vitest run --project db --no-file-parallelism"
}
}tsconfigPathsis a Vite 8 option. The Next.js guide uses thevite-tsconfig-pathsplugin, which does the same and works with earlier versions.server-onlyis replaced with an empty module. This is the promise from 03-05: Next.js understands the marker, and outside it there's no installed package by that name. We don't lose any protection, becausenext buildstill checks the boundary.- Three projects with different environments. Server code is tested in Node, not in a simulated browser; with
jsdom,windowwould exist and could hide a bug. In Vitest 5, projects inherit the plugins and aliases from the root configuration. vitest runruns and exits. Withoutrun, it stays watching for changes.- Tests live next to the code (
lib/filters.test.ts), insideapp/too: onlypageandroutepublish routes. The ones that need the database go intests/db/. - Imports are explicit (
import { test } from 'vitest'), with no globals. That's why Testing Library's cleanup is declared by hand.
- Pure functions
lib/filters.ts receives whatever anyone types into the URL. It's the perfect candidate: lots of inputs, no dependencies.
// lib/filters.test.ts
import { describe, expect, test } from 'vitest'
import { createEventsUrl, normalizeFilters } from '@/lib/filters'
describe('normalizeFilters', () => {
test.each([
['missing', undefined, 1],
['valid', '3', 3],
['zero', '0', 1],
['negative', '-3', 1],
['decimal', '2.5', 1],
['text', 'two', 1],
['repeated: the first one wins', ['2', '9'], 2],
])('page %s', (_case, page, expected) => {
expect(normalizeFilters({ page }).page).toBe(expected)
})
test('ignores an unknown category', () => {
expect(normalizeFilters({ category: 'dogs' }).category).toBeUndefined()
})
test('trims the text and discards whitespace', () => {
expect(normalizeFilters({ q: ` ${'a'.repeat(200)}` }).q).toHaveLength(80)
expect(normalizeFilters({ q: ' ' }).q).toBeUndefined()
})
})
test('createEventsUrl is the inverse of normalizeFilters', () => {
const filters = { category: 'theater', district: 'Riverside', q: 'café & jazz', page: 2 } as const
const { searchParams } = new URL(createEventsUrl(filters), 'https://agendaviva.example')
expect(normalizeFilters(Object.fromEntries(searchParams))).toEqual(filters)
})test.eachturns a table of cases into one test per row, each with its name. When one fails, you can see which.- The last test checks a property, not a value: writing and reading gives back the same thing. It covers the encoding of accents, spaces and
&without writing the expected string by hand. - The name says what's expected, in a sentence you can understand without reading the body.
3.1. Dates
Dates are the source of tests that fail "sometimes": on someone else's machine, in another time zone, on the last Sunday in March. The table from 06-03 becomes tests as is:
// lib/dates.test.ts
import { expect, test } from 'vitest'
import { formatLocalDateTime, parseLocalDateTime } from '@/lib/dates'
test.each([
['winter', '2028-01-12T00:00', '2028-01-11T23:00:00.000Z'],
['summer', '2028-05-12T20:30', '2028-05-12T18:30:00.000Z'],
['repeated hour: the second one', '2028-10-29T02:30', '2028-10-29T01:30:00.000Z'],
])('parseLocalDateTime, %s', (_case, text, instant) => {
expect(parseLocalDateTime(text)?.toISOString()).toBe(instant)
})
test.each([
['nonexistent day', '2028-02-31T10:00'],
['hour that doesn\'t exist', '2028-03-26T02:30'],
['with seconds', '2028-05-12T20:30:00'],
['empty', ''],
])('parseLocalDateTime rejects: %s', (_case, text) => {
expect(parseLocalDateTime(text)).toBeNull()
})
test('formatting and parsing return the same instant', () => {
const instant = new Date('2028-07-01T18:00:00Z')
expect(parseLocalDateTime(formatLocalDateTime(instant))).toEqual(instant)
})For anything that depends on now there are two paths. Ours is to receive it as an argument: createCalendar(details, now) and verifySignature(header, body, secrets, now) are tested with a fixed date. The other, for code that calls new Date() internally, is to freeze the clock: vi.useFakeTimers() and vi.setSystemTime(…), with vi.useRealTimers() at the end. With async code, fake timers bring surprises; if you can choose, pass the time in.
When testing formatDateTime, remember that the text is produced by ICU, which ships with Node, and that an update can change a comma or the kind of space. Check what matters (toContain('08:30')), not the whole sentence.
3.2. Security in a table
Security functions are the ones that benefit most from a list of hostile cases. Every attack you know is a row:
// lib/destination.test.ts
import { expect, test } from 'vitest'
import { safeDestination } from '@/lib/destination'
test.each([
['/events/jazz-night?x=1', '/events/jazz-night?x=1'],
['https://lookalike.example', '/'],
['//lookalike.example', '/'],
['/\\lookalike.example', '/'],
['/.//lookalike.example', '/'],
['javascript:alert(1)', '/'],
[['/a', '/b'], '/'],
[undefined, '/'],
[`/${'a'.repeat(600)}`, '/'],
])('safeDestination(%j) → %s', (value, expected) => {
expect(safeDestination(value)).toBe(expected)
})In the same style you test serializeJsonLd (that a </script> in the title doesn't appear in the output), isPossibleSlug, detectImageType with the first bytes of each format, the schemas in lib/schemas/, createGuideMetadata (which combinations aren't indexed) and routePattern. And there's one that pays off especially well: that toPublicEvent returns exactly these keys.
// lib/api/events.test.ts (excerpt; testEvent() creates an EventWithVenue)
test('does not publish internal fields', () => {
expect(Object.keys(toPublicEvent(testEvent())).toSorted()).toEqual([
'canceled', 'category', 'endsAt', 'hasSpots', 'image', 'slug',
'startsAt', 'summary', 'title', 'url', 'venue',
])
})If someone adds ...event, the test fails before the event's owner leaks out through the API.
- Client components
Testing Library renders the component and offers ways to search that resemble a person's: by role, by label or by text. If a test can't find a button by its name, neither can someone using a screen reader.
// components/favorite-button.test.tsx
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, expect, test } from 'vitest'
import { FavoriteButton } from '@/components/favorite-button'
beforeEach(() => localStorage.clear())
test('marks and unmarks', async () => {
const user = userEvent.setup()
render(<FavoriteButton eventId="evt-01" title="Riverside Quartet" />)
const button = screen.getByRole('button', { name: 'Favorite: Riverside Quartet' })
expect(button).toHaveAttribute('aria-pressed', 'false')
await user.click(button)
expect(button).toHaveAttribute('aria-pressed', 'true')
await user.click(button)
expect(button).toHaveAttribute('aria-pressed', 'false')
})
test('stays in sync with another button for the same event', async () => {
const user = userEvent.setup()
render(
<>
<FavoriteButton eventId="evt-01" title="Top" />
<FavoriteButton eventId="evt-01" title="Bottom" />
</>,
)
await user.click(screen.getByRole('button', { name: 'Favorite: Top' }))
expect(screen.getByRole('button', { name: 'Favorite: Bottom' })).toHaveAttribute('aria-pressed', 'true')
})We don't know whether it uses useSyncExternalStore or a context internally, and the test doesn't look. If it's rewritten, for example with useIsFavorite from 10-01, it will still hold. A test that checks internal state gets in the way precisely when you need it most, when the code changes.
4.1. A form with its action
Client Components import Server Actions like ordinary functions. In a test, that module is replaced: there's no server to call.
// app/(public)/events/_components/booking-panel.test.tsx
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { expect, test, vi } from 'vitest'
import { bookSpots } from '@/actions/bookings'
import { BookingPanel } from './booking-panel'
vi.mock('@/actions/bookings', () => ({ bookSpots: vi.fn() }))
function renderPanel(bookedSpots: number | null = null) {
render(
<BookingPanel
eventId="evt-02" slug="pottery-workshop"
bookedSpots={bookedSpots} max={4}
/>,
)
}
test('shows the rejection and keeps what was typed', async () => {
vi.mocked(bookSpots).mockResolvedValue({
status: 'error', message: 'There are no spots left.', errors: {}, values: { spots: '3' },
})
const user = userEvent.setup()
renderPanel()
const spots = screen.getByLabelText('Spots')
await user.clear(spots)
await user.type(spots, '3')
await user.click(screen.getByRole('button', { name: 'Book' }))
expect(await screen.findByText('There are no spots left.')).toBeInTheDocument()
expect(screen.getByLabelText('Spots')).toHaveValue(3)
const [eventId, , formData] = vi.mocked(bookSpots).mock.calls[0]
expect(eventId).toBe('evt-02')
expect(formData.get('spots')).toBe('3')
})
test('with a booking, offers to manage it and not the form', () => {
renderPanel(2)
expect(screen.getByText(/You have 2 spots/)).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Book' })).not.toBeInTheDocument()
})vi.mockis hoisted to the top of the file, before the imports: that's why it works even though it appears afterwards. It must be at the top level.findBy…waits;getBy…requires it to be there already;queryBy…returnsnulland is for checking absence.user-eventsimulates the full interaction, with focus and keys.fireEventonly fires an event.- Navigation is replaced the same way. A component that uses
useRouterorusePathnameneedsvi.mock('next/navigation', …)with the functions it calls. If a component demands lots of mocks, that's a sign it's better tested whole in the browser.
In Vitest 5, call records are cleared automatically before each test (clearMocks is true), but implementations are kept. Set the value in each test, as above, and it won't depend on the order.
- Server Actions
An action is an async function: you import it and call it. The 'use server' directive does nothing outside Next.js. What's missing is its environment, and that has to be replaced: next/cache, cookies(), the session and the data. The goal is to test its decisions: what it rejects, in what order and what it notifies.
// actions/bookings.test.ts
import { beforeEach, expect, test, vi } from 'vitest'
import { refresh } from 'next/cache'
import { bookSpots } from '@/actions/bookings'
import { createBooking } from '@/lib/data/bookings'
import { INITIAL_STATE } from '@/lib/forms'
import { notifyIfAvailabilityChanges } from '@/lib/revalidation'
import { withinLimits } from '@/lib/security/rate-limits'
import { getCurrentUser } from '@/lib/session'
vi.mock('next/cache', () => ({ refresh: vi.fn() }))
vi.mock('@/lib/data/bookings', () => ({ createBooking: vi.fn(), cancelBooking: vi.fn() }))
vi.mock('@/lib/session', () => ({ getCurrentUser: vi.fn() }))
vi.mock('@/lib/env', () => ({ readEnv: () => ({ maxSpotsPerBooking: 4 }) }))
vi.mock('@/lib/revalidation', () => ({ notifyIfAvailabilityChanges: vi.fn() }))
vi.mock('@/lib/security/rate-limits', () => ({
withinLimits: vi.fn(),
writeLimits: () => [],
}))
vi.mock('@/lib/tasks/audit', () => ({ audit: vi.fn() }))
vi.mock('@/lib/tasks/confirm-booking', () => ({ confirmBooking: vi.fn() }))
vi.mock('@/lib/tasks/after-response', () => ({ afterResponse: vi.fn() }))
function request(spots: string, eventId: unknown = 'evt-02') {
const formData = new FormData()
formData.set('spots', spots)
return bookSpots(eventId as string, INITIAL_STATE, formData)
}
beforeEach(() => {
vi.mocked(getCurrentUser).mockResolvedValue({ id: 'usr-01', name: 'Visitor', role: 'visitor' })
vi.mocked(withinLimits).mockResolvedValue(true)
vi.mocked(createBooking).mockResolvedValue({
status: 'booked', bookingId: 'bkg-01', spotsBefore: 4, spotsAfter: 2,
})
})
test('books and notifies after writing', async () => {
expect(await request('2')).toEqual({ status: 'success', message: 'You\'ve booked 2 spots.' })
expect(createBooking).toHaveBeenCalledWith('evt-02', 2)
expect(notifyIfAvailabilityChanges).toHaveBeenCalledWith(4, 2)
expect(refresh).toHaveBeenCalledOnce()
})
test('without a session it never reaches the data', async () => {
vi.mocked(getCurrentUser).mockResolvedValue(null)
expect(await request('2')).toMatchObject({ status: 'error', message: 'Sign in to book.' })
expect(createBooking).not.toHaveBeenCalled()
})
test.each(['', '0', '5', '1.5', '-1', 'two'])('rejects "%s" spots', async (spots) => {
expect(await request(spots)).toMatchObject({ status: 'error' })
expect(createBooking).not.toHaveBeenCalled()
})
test.each([null, 42, {}, 'x'.repeat(100)])('rejects a tampered identifier', async (id) => {
expect(await request('1', id)).toMatchObject({ status: 'error' })
expect(createBooking).not.toHaveBeenCalled()
})
test('if there are no spots left, it explains and refreshes', async () => {
vi.mocked(createBooking).mockResolvedValue({ status: 'not-enough-spots', spotsLeft: 0 })
expect(await request('1')).toMatchObject({ message: 'There are no spots left.' })
expect(refresh).toHaveBeenCalledOnce()
})Almost every test checks a rejection, and that nothing was touched after it. The two hostile-input tests are a reminder that an action is an endpoint (08-06).
The list of mocks is long, and that says something: this action coordinates many pieces. We put up with it because each one is a function with a clear name. If the list grew further, the answer wouldn't be another mock, but pulling the decisions out into a pure function and testing that.
For an action that ends in redirect, replace next/navigation with a version that throws, like the real one; otherwise the code would keep running afterwards:
// For testing signIn(…) or createEvent(…)
vi.mock('next/navigation', () => ({
redirect: vi.fn((destination: string) => {
throw new Error(`redirects to ${destination}`)
}),
}))
await expect(signIn('//lookalike.example', INITIAL_STATE, formData)).rejects.toThrow('redirects to /')5.1. Permission checks
lib/authorization.ts is the place where a mistake costs the most. With the session replaced, the test is the permissions table: with each role, and with no session, what checkRole('organizer') answers; that checkRole() with no arguments always denies; and that ensureRole throws AccessError with its reason. What it does not prove is that every data function uses it. That's what the next section is for.
- Against a database
Mocking Drizzle to test createBooking wouldn't prove anything: what's interesting is the row lock, the unique constraint and the where with the owner, and all of that happens in PostgreSQL. These tests use a real one, in a separate database.
// tests/db/url.ts
export const TEST_DB_URL =
process.env.TEST_DATABASE_URL ??
'postgresql://agendaviva:agendaviva_local@localhost:5432/agendaviva_test'
// These tests delete tables: make sure it can't be any other one
if (!new URL(TEST_DB_URL).pathname.endsWith('_test')) {
throw new Error('The test database name must end in _test')
}
// tests/db/migrate.ts — once, before everything
import { drizzle } from 'drizzle-orm/node-postgres'
import { migrate } from 'drizzle-orm/node-postgres/migrator'
import { Pool } from 'pg'
import { TEST_DB_URL } from './url'
export async function setup(): Promise<void> {
const pool = new Pool({ connectionString: TEST_DB_URL })
await migrate(drizzle({ client: pool }), { migrationsFolder: './drizzle' })
await pool.end()
}
// tests/db/mocks.ts — what doesn't exist outside Next.js
import { vi } from 'vitest'
vi.mock('next/cache', () => ({
io: async () => {},
cacheLife: () => {},
cacheTag: () => {},
}))'use cache' is a string with no effect outside Next.js, so the queries always run. That's what we want: we're testing the query, not the cache. The migrations are the same ones as in production and, along the way, they get checked too.
// tests/db/bookings.test.ts
import { eq } from 'drizzle-orm'
import { afterAll, beforeEach, expect, test, vi } from 'vitest'
import { getDb } from '@/lib/db/client'
import { bookings, events, users, venues } from '@/lib/db/schema'
import { cancelBooking, createBooking } from '@/lib/data/bookings'
const session = vi.hoisted(() => ({ id: '' }))
vi.mock('@/lib/authorization', () => ({
ensureUser: async () => ({ id: session.id, name: 'Test', role: 'visitor' }),
}))
function actingAs<T>(id: string, operation: () => Promise<T>): Promise<T> {
session.id = id
return operation()
}
const DAY = 24 * 60 * 60 * 1000
beforeEach(async () => {
const db = await getDb()
await db.delete(bookings)
await db.delete(events)
await db.delete(users)
await db.delete(venues)
await db.insert(venues).values({
id: 'v', slug: 'v', name: 'V', district: 'Downtown', address: '1 Main Street', capacity: 10, outdoor: false,
})
await db.insert(users).values([
{ id: 'ana', name: 'Ana', email: '[email protected]' },
{ id: 'bruno', name: 'Bruno', email: '[email protected]' },
])
await db.insert(events).values({
id: 'e', slug: 'e', title: 'E', summary: '-', description: '-', category: 'workshop',
startsAt: new Date(Date.now() + DAY), endsAt: new Date(Date.now() + 2 * DAY),
venueId: 'v', organizerId: 'ana', capacity: 10, spotsLeft: 1, status: 'published',
})
})
afterAll(async () => {
const db = await getDb()
await db.$client.end() // Closes the pool
})
async function spotsLeft(): Promise<number> {
const db = await getDb()
const [row] = await db.select({ spotsLeft: events.spotsLeft }).from(events).where(eq(events.id, 'e'))
return row.spotsLeft
}
test('the last spot goes to one person only', async () => {
const results = await Promise.all([
actingAs('ana', () => createBooking('e', 1)),
actingAs('bruno', () => createBooking('e', 1)),
])
expect(results.map(({ status }) => status).toSorted()).toEqual(['booked', 'not-enough-spots'])
expect(await spotsLeft()).toBe(0)
})
test('you can\'t cancel someone else\'s booking', async () => {
const booking = await actingAs('ana', () => createBooking('e', 1))
if (booking.status !== 'booked') throw new Error('The booking should have been made')
const othersBooking = await actingAs('bruno', () => cancelBooking(booking.bookingId))
expect(othersBooking).toEqual({ status: 'not-found' })
expect(await spotsLeft()).toBe(0)
})- Concurrency is tested with concurrency. Remove
.for('update')fromcreateBookingand run the first test: it will fail, with a PostgreSQL constraint error. That's how you check that the test works. vi.hoistedcreates the value before the mock that uses it.actingAssets the identity just before the call; it works withPromise.allbecause the function reads the session in its first step.- The second one is the IDOR test that 08-06 asked for. There should be one for every data function with an owner:
updateEvent,getEditableEvent,changeImage. - Each test starts from its own data. Deleting at the start, and not at the end, leaves the data in plain sight when something fails.
--no-file-parallelismkeeps two files from stepping on each other. - There's one left as a bonus: canceling twice at the same time must return the spot only once. Write it.
- Where the line is
| I want to test… | With Vitest? | Alternative |
|---|---|---|
A synchronous Server Component (StatusBadge, EventCard) |
Yes, like any component | |
| An async Server Component | No | Extract the decision into a function; the rest, in 10-04 |
| That a page streams, and in what order | No | 10-04 |
'use cache', tags and invalidation |
No: they don't exist outside Next.js | 10-04 |
| Real redirects, cookies and headers | No | 10-04, or curl |
| A Route Handler | Yes: it's a function that receives a Request and returns a Response |
|
proxy.ts |
The extracted logic (isPossibleSlug) |
The whole thing, in 10-04 |
| The look | No | Review, or screenshots in 10-04 |
Route Handlers are rewarding: await POST(new Request('http://test/api/metrics', { method: 'POST', body: '{}' })) and you inspect the response. The metrics one is tested in exercise 1.
There's the shortcut of calling an async component as a function, await EventContent(props), and rendering what it returns. It works as long as it has no async children, and stops working as soon as someone adds one. I don't recommend it as a rule.
What about Jest? It's still an option: Next.js includes next/jest, which configures the transform, aliases, CSS and environment variables. If the project already uses it, there's no rush to switch; the tests are almost identical, with jest instead of vi, and the limitation with async components is the same. For a fresh start, Vitest is faster and needs less configuration.
Coverage (vitest run --coverage, with @vitest/coverage-v8) points out what no test has executed. It's useful for finding things you forgot and bad as a target: you can execute 100% of the lines without checking anything.
Common Mistakes and Tips
- Testing the implementation: internal state, class names, how many times it renders.
- Mocking everything until the test only checks the mocks.
- Searching by
data-testidfor something that has a role and an accessible name. - Huge snapshots that get updated without being read.
redirectreplaced with a function that doesn't throw.- Depending on the time, the time zone or the order.
- Using the development database. One day you'll wipe it.
- Trying to render async components with fragile tricks.
- Forgetting
awaitin an async assertion. Vitest 5 treats it as a failure. - Writing only the happy path. Bugs live on the others.
- Never seeing the test fail, not even once.
Exercises
Exercise 1: testing a Route Handler
Write tests for POST /api/metrics (10-01): it accepts a valid measurement with 204; it rejects a body without a JSON type with 415, broken JSON with 400, and an extra field or a route with strange characters with 422.
Solution
// app/api/metrics/route.test.ts
import { expect, test, vi } from 'vitest'
import { POST } from './route'
const MEASUREMENT = {
name: 'LCP', value: 1830.4, rating: 'good',
navigation: 'navigate', route: '/events/[slug]', device: 'touch',
}
function send(body: string, type = 'application/json') {
return POST(
new Request('http://test/api/metrics', {
method: 'POST', body, headers: { 'Content-Type': type },
}),
)
}
test('logs a valid measurement', async () => {
const log = vi.spyOn(console, 'info').mockImplementation(() => {})
expect((await send(JSON.stringify(MEASUREMENT))).status).toBe(204)
expect(log).toHaveBeenCalledOnce()
})
test.each([
[415, JSON.stringify(MEASUREMENT), 'text/plain'],
[400, '{"name":', undefined],
[422, JSON.stringify({ ...MEASUREMENT, user: 'ana' }), undefined],
[422, JSON.stringify({ ...MEASUREMENT, route: '/<script>' }), undefined],
])('responds %i', async (status, body, type) => {
expect((await send(body, type)).status).toBe(status)
})No mocks are needed: the Route Handler uses the platform's Request and Response, which exist in Node. In 10-05 the output will go through a logging function, which still writes with console.info, and the test won't change.
Exercise 2: a fake storage
In 06-05 you wrote an in-memory FileStorage as practice. Use it to test uploadImage: that a file with a .png extension and HTML content is rejected without saving anything, and that, if changeImage returns null (the event isn't yours), the file that was just saved is deleted. What do you replace?
Solution
You replace @/lib/storage (so that getStorage returns the in-memory one), @/lib/data/dashboard (changeImage), @/lib/authorization (checkRole grants), the rate limits and next/cache. You do not replace detectImageType: it's part of what's being tested.
With new File(['<html>'], 'poster.png', { type: 'image/png' }) the action must return an error and the storage must be empty: the declared type doesn't count, the bytes do. For the second case, a file that starts with the PNG signature (new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, …])) and changeImage returning null: at the end, the storage is empty again, because no orphans are left.
A substitute with behavior, like this one, is called a fake. It's preferable to checking that "remove was called": if tomorrow the deletion is done another way, the test still tells the truth.
Exercise 3: reviewing a test
What problems do you see?
vi.mock('@/lib/filters', () => ({ normalizeFilters: () => ({ page: 1 }) }))
test('works', () => {
const { container } = render(<Pagination page={1} totalPages={3} createHref={(p) => `/events?page=${p}`} />)
expect(container.querySelector('.mt-8 > a:last-child')).toBeTruthy()
expect(container).toMatchSnapshot()
expect(new Date().getFullYear()).toBe(2026)
waitFor(() => expect(screen.getByText('Next')).toBeVisible())
})Solution
test('on the first page it links to the second and not backwards', () => {
render(<Pagination page={1} totalPages={3} createHref={(p) => `/events?page=${p}`} />)
expect(screen.getByRole('link', { name: 'Next' })).toHaveAttribute('href', '/events?page=2')
expect(screen.queryByRole('link', { name: 'Previous' })).not.toBeInTheDocument()
})The mock is unnecessary: Pagination doesn't use that module. The name says nothing. The selector depends on a Tailwind class. The snapshot freezes the whole HTML and will break for any reason. The year will make the test fail in January. And waitFor without await doesn't check anything in time; besides, there's nothing to wait for.
Conclusion
Each level catches a type of failure. Pure functions are tested with tables of cases; client components, the way a person uses them; Server Actions, by what they reject and in what order, with their environment replaced; and queries, against a real PostgreSQL, where concurrency and ownership are proven. server-only is resolved with an alias, and async components are left out: that's where Vitest ends.
What remains is what no isolated piece can guarantee: that booking works with the session, the cache, the proxy, streaming and a real browser. The next lesson, End-to-End Testing with Playwright, goes through the whole of AgendaViva from the outside.
