# Router Act > Cómo escribir tests end-to-end con createRouterAct y LinkAccordion. Úsalo al escribir tests que controlan el momento de las peticiones internas de Next.js, como los prefetches. Fuente: https://skillsagentes.com/skills/vercel/next.js/router-act Markdown: https://skillsagentes.com/skills/vercel/next.js/router-act.md Repositorio: https://github.com/vercel/next.js Autor: vercel Licencia: MIT Actualizado: hace 2 meses Coste de contexto: 85 tok instalada, 3.1k tok al activarse, 3.1k tok con todos los archivos del bundle Bundle: 1 archivo, 12 KB Permisos que pide: ninguno declarado ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add vercel/next.js --skill router-act --agent claude-code # Cursor npx -y skills add vercel/next.js --skill router-act --agent cursor # Codex npx -y skills add vercel/next.js --skill router-act --agent codex # Gemini CLI npx -y skills add vercel/next.js --skill router-act --agent gemini # Windsurf npx -y skills add vercel/next.js --skill router-act --agent windsurf # Cline npx -y skills add vercel/next.js --skill router-act --agent cline ``` ## Qué hace - Explica cómo escribir tests end-to-end con `createRouterAct` y `LinkAccordion` - Permite controlar el momento en que se lanzan las peticiones internas de Next.js, como los prefetches, y afirmar sobre sus respuestas - Cubre la API de `act`, los patrones de fixture y el control de prefetch con `LinkAccordion` - Explica el reloj falso y las fuentes habituales de tests inestables - Aclara también cuándo no usar `act` ## Cuándo usarla - Escribir o modificar tests que necesitan controlar el momento de las peticiones internas de Next.js - Afirmar sobre las respuestas de un prefetch ## Cuándo no - Los casos que el propio skill recoge en su sección de cuándo no usar `act` ## Qué la activa - "Escribe un test que controle el prefetch" - "¿Cómo evito que este test sea flaky?" - "Usa LinkAccordion en esta prueba" ## Antes de instalar - Es un skill interno del repositorio de Next.js. ## Archivos - SKILL.md — 12 KB ## SKILL.md Reproducido tal cual desde vercel/next.js bajo MIT. Esta sección es el documento original y está en inglés. # Router Act Testing Use this skill when writing or modifying tests that involve prefetch requests, client router navigations, or the segment cache. The `createRouterAct` utility from `test/lib/router-act.ts` lets you assert on prefetch and navigation responses in an end-to-end way without coupling to the exact number of requests or the protocol details. This is why most client router-related tests use this pattern. ## When NOT to Use `act` Don't bother with `act` if you don't need to instrument the network responses — either to control their timing or to assert on what's included in them. If all you're doing is waiting for some part of the UI to appear after a navigation, regular Playwright helpers like `browser.elementById()`, `browser.elementByCss()`, and `browser.waitForElementByCss()` are sufficient. ## Core Principles 1. **Use `LinkAccordion` to control when prefetches happen.** Never let links be visible outside an `act` scope. 2. **Prefer `'no-requests'`** whenever the data should be served from cache. This is the strongest assertion — it proves the cache is working. 3. **Avoid retry/polling timers.** The `act` utility exists specifically to replace inherently flaky patterns like `retry()` loops or `setTimeout` waits for network activity. If you find yourself wanting to poll, you're probably not using `act` correctly. 4. **Avoid the `block` feature.** It's prone to false negatives. Prefer `includes` and `'no-requests'` assertions instead. ## Act API ### Config Options ```typescript // Assert NO router requests are made (data served from cache). // Prefer this whenever possible — it's the strongest assertion. await act(async () => { ... }, 'no-requests') // Expect at least one response containing this substring await act(async () => { ... }, { includes: 'Page content' }) // Expect multiple responses (checked in order) await act(async () => { ... }, [ { includes: 'First response' }, { includes: 'Second response' }, ]) // Assert the same content appears in two separate responses await act(async () => { ... }, [ { includes: 'Repeated content' }, { includes: 'Repeated content' }, ]) // Expect at least one request, don't assert on content await act(async () => { ... }) ``` ### How `includes` Matching Works - The `includes` substring is matched against the HTTP response body. Use text content that appears literally in the rendered output (e.g. `'Dynamic content (stale time 60s)'`). - Extra responses that don't match any `includes` assertion are silently ignored — you only need to assert on the responses you care about. This keeps tests decoupled from the exact number of requests the router makes. - Each `includes` expectation claims exactly one response. If the same substring appears in N separate responses, provide N separate `{ includes: '...' }` entries. ### App Shell requests are ignored by default When App Shells are enabled (the default when Cache Components is on), a `prefetch` is split into two phases: an **App Shell** prefetch — the param/searchParam-independent chrome of the route (layouts, loading boundaries, static shell) — and a separate per-link/per-page data prefetch. The App Shell is conceptually part of the route, not prefetch data, so **`act` ignores App Shell requests for all assertion purposes** (they carry a `next-router-prefetch: '3'` header). This means you generally do **not** need to account for the extra App Shell response in your assertions. If a `Loading...` fallback now arrives in both the App Shell prefetch and the per-link prefetch, you still write a single `{ includes: 'Loading...' }` — the App Shell copy is invisible to matching. Likewise, `'no-requests'` still passes even if an App Shell prefetch fires, and `block: 'reject'` won't match content that appears only in the App Shell. App Shell requests are still intercepted, fulfilled, and awaited (so the shell is cached and no requests are left in flight) — they just don't participate in `includes` matching, `no-requests`, `block: 'reject'`, or the "at least one request" check. An App Shell response that returns an error status (4xx/5xx) still fails the test. To assert on App Shell responses directly — for tests specifically about App Shell behavior — opt in at the `act` instance level: ```typescript const act = createRouterAct(page, { includeAppShellRequests: true }) ``` With this option, App Shell requests are treated like any other router request. Prefer expressing App Shell behavior through observable outcomes (e.g. an instant navigation rendering the cached shell before the data response arrives) rather than asserting on prefetch content where practical. See `test/e2e/app-dir/segment-cache/prefetch-app-shell/prefetch-app-shell.test.ts` for the canonical example. ### What `act` Does Internally `act` intercepts all router requests — prefetches, navigations, and Server Actions — made during the scope: 1. Installs a Playwright route handler to intercept router requests 2. Runs your scope function 3. Waits for a `requestIdleCallback` (captures IntersectionObserver-triggered prefetches) 4. Fulfills buffered responses to the browser 5. Repeats steps 3-4 until no more requests arrive 6. Asserts on the responses based on the config Responses are buffered and only forwarded to the browser after the scope function returns. This means you cannot navigate to a new page and wait for it to render within the same scope — that would deadlock. Trigger the navigation (click the link) and let `act` handle the rest. Read destination page content _after_ `act` returns: ```typescript await act( async () => { /* toggle accordion, click link */ }, { includes: 'Page content' } ) // Read content after act returns, not inside the scope expect(await browser.elementById('my-content').text()).toBe('Page content') ``` ## LinkAccordion Pattern ### Why LinkAccordion Exists `LinkAccordion` controls when `` components enter the DOM. A Next.js `` triggers a prefetch when it enters the viewport (via IntersectionObserver). By hiding the Link behind a checkbox toggle, you control exactly when prefetches happen — only when you explicitly toggle the accordion inside an `act` scope. ```tsx // components/link-accordion.tsx 'use client' import Link from 'next/link' import { useState } from 'react' export function LinkAccordion({ href, children, prefetch }) { const [isVisible, setIsVisible] = useState(false) return ( <> setIsVisible(!isVisible)} data-link-accordion={href} /> {isVisible ? ( {children} ) : ( `${children} (link is hidden)` )} ) } ``` ### Standard Navigation Pattern Always toggle the accordion and click the link inside the same `act` scope: ```typescript await act( async () => { // 1. Toggle accordion — Link enters DOM, triggers prefetch const toggle = await browser.elementByCss( 'input[data-link-accordion="/target-page"]' ) await toggle.click() // 2. Click the now-visible link — triggers navigation const link = await browser.elementByCss('a[href="/target-page"]') await link.click() }, { includes: 'Expected page content' } ) ``` ## Common Sources of Flakiness ### Using `browser.back()` with open accordions Do not use `browser.back()` to return to a page where accordions were previously opened. BFCache restores the full React state including `useState` values, so previously-opened Links are immediately visible. This triggers IntersectionObserver callbacks outside any `act` scope — if the cached data is stale, uncontrolled re-prefetches fire and break subsequent `no-requests` assertions. The only safe use of `browser.back()`/`browser.forward()` is when testing BFCache behavior specifically. **Fix:** navigate forward to a fresh hub page instead. See [Hub Pages](#hub-pages). ### Using visible `` components outside `act` scopes Any `` visible in the viewport can trigger a prefetch at any time via IntersectionObserver. If this happens outside an `act` scope, the request is uncontrolled and can interfere with subsequent assertions. Always hide links behind `LinkAccordion` and only toggle them inside `act`. ### Using retry/polling timers to wait for network activity `retry()`, `setTimeout`, or any polling pattern to wait for prefetches or navigations to settle is inherently flaky. `act` deterministically waits for all router requests to complete before returning. ### Navigating and waiting for render in the same `act` scope Responses are buffered until the scope exits. Clicking a link then reading destination content in the same scope deadlocks. Read page content after `act` returns instead. ## Hub Pages When you need to navigate away from a page and come back to test staleness, use "hub" pages instead of `browser.back()`. Each hub is a fresh page with its own `LinkAccordion` components that start closed. Hub pages use `connection()` to ensure they are dynamically rendered. This guarantees that navigating to a hub always produces a router request, which lets `act` properly manage the navigation and wait for the page to fully render before continuing. **Hub page pattern:** ```tsx // app/my-test/hub-a/page.tsx import { Suspense } from 'react' import { connection } from 'next/server' import { LinkAccordion } from '../../components/link-accordion' async function Content() { await connection() return
Hub a
} export default function Page() { return ( <> ) } ``` **Target pages link to hubs via LinkAccordion too:** ```tsx // On target pages, add LinkAccordion links to hub pages Hub A ``` **Test flow:** ```typescript // 1. Navigate to target (first visit) await act( async () => { /* toggle accordion, click link */ }, { includes: 'Target content' } ) // 2. Navigate to hub-a (fresh page, all accordions closed) await act( async () => { const toggle = await browser.elementByCss( 'input[data-link-accordion="/my-test/hub-a"]' ) await toggle.click() const link = await browser.elementByCss('a[href="/my-test/hub-a"]') await link.click() }, { includes: 'Hub a' } ) // 3. Advance time await page.clock.setFixedTime(startDate + 60 * 1000) // 4. Navigate back to target from hub (controlled prefetch) await act(async () => { const toggle = await browser.elementByCss( 'input[data-link-accordion="/my-test/target-page"]' ) await toggle.click() const link = await browser.elementByCss('a[href="/my-test/target-page"]') await link.click() }, 'no-requests') // or { includes: '...' } if data is stale ``` ## Fake Clock Setup Segment cache staleness tests use Playwright's clock API to control `Date.now()`: ```typescript async function startBrowserWithFakeClock(url: string) { let page!: Playwright.Page const startDate = Date.now() const browser = await next.browser(url, { async beforePageLoad(p: Playwright.Page) { page = p await page.clock.install() await page.clock.setFixedTime(startDate) }, }) const act = createRouterAct(page) return { browser, page, act, startDate } } ``` - `setFixedTime` changes `Date.now()` return value but timers still run in real time - The segment cache uses `Date.now()` for staleness checks - Advancing the clock doesn't trigger IntersectionObserver — only viewport changes do - `setFixedTime` does NOT fire pending `setTimeout`/`setInterval` callbacks ## Reference - `createRouterAct`: `test/lib/router-act.ts` - `LinkAccordion`: `test/e2e/app-dir/segment-cache/staleness/components/link-accordion.tsx` - Example tests: `test/e2e/app-dir/segment-cache/staleness/` ## Dónde encaja - Categoría: [Testing y QA](https://skillsagentes.com/categorias/testing-qa.md) — Flujos de testing unitario, de integración y end-to-end. - Creador: [vercel](https://skillsagentes.com/creators/vercel.md) — 36 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [Next Cache Components Adoption](https://skillsagentes.com/skills/vercel/next.js/next-cache-components-adoption.md): Activa Cache Components en una app de Next.js y resuelve las rutas bloqueantes que aparecen. Úsalo para adoptar o migrar, activar el flag cacheComponents o decidir entre excluir rutas y arreglarlas. - [Next Cache Components Optimizer](https://skillsagentes.com/skills/vercel/next.js/next-cache-components-optimizer.md): Lleva una ruta de Next.js a navegación instantánea bajo Cache Components o PPR mediante un bucle agéntico: codifica el objetivo como un e2e instant() en rojo y lo trabaja hasta verde, ruta a ruta. - [Next Partial Prefetching Adoption](https://skillsagentes.com/skills/vercel/next.js/next-partial-prefetching-adoption.md): Activa Partial Prefetching en una app de Next.js y resuelve las insights que surgen: audita los Link con prefetch, activa partialPrefetching y opta por rutas con prefetch = 'partial'. - [Next Dev Loop](https://skillsagentes.com/skills/vercel/next.js/next-dev-loop.md): Verifica el comportamiento en runtime de Next.js tras editar código de la aplicación. Combina /_next/mcp, la visión de Next.js, con agent-browser, la del navegador. Requiere un next dev en marcha. - [Gh Stack](https://skillsagentes.com/skills/vercel/next.js/gh-stack.md): Gestiona PRs apilados y parte el trabajo en ramas revisables con gh-stack: creación, visualización, edición, push, envío, sincronización, rebase, merge y checkout. ## Skills relacionadas - [Next Dev Loop](https://skillsagentes.com/skills/vercel/next.js/next-dev-loop.md): Verifica el comportamiento en runtime de Next.js tras editar código de la aplicación. Combina /_next/mcp, la visión de Next.js, con agent-browser, la del navegador. Requiere un next dev en marcha. - [Pr Status Triage](https://skillsagentes.com/skills/vercel/next.js/pr-status-triage.md): Tría fallos de CI y comentarios de revisión de PR con scripts/pr-status.js: prioriza por bloqueo (build, lint, tipos, tests), empareja variables de CI para reproducir en local y distingue flakies. - [Sandbox Bench](https://skillsagentes.com/skills/vercel/next.js/sandbox-bench.md): Compara el rendimiento de cambios de React o Next.js en VMs de Vercel Sandbox con estadística A/B pareada: rps, latencia, p95, TTFB, RSS y bytes de documento y Flight. - [Authoring Skills](https://skillsagentes.com/skills/vercel/next.js/authoring-skills.md): Cómo crear y mantener skills de agente en .agents/skills/. Úsalo al crear un SKILL.md, escribir descripciones, elegir campos de frontmatter o decidir qué va en un skill y qué en AGENTS.md. - [Backport Pr](https://skillsagentes.com/skills/vercel/next.js/backport-pr.md): Lleva un pull request fusionado de Next.js desde canary a una rama de release anterior como next-16-2: localiza el commit, crea la rama, hace cherry-pick, valida y abre el PR. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)