router-act
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRouter Act Testing
Router Act 测试
Use this skill when writing or modifying tests that involve prefetch requests, client router navigations, or the segment cache. The utility from 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.
createRouterActtest/lib/router-act.ts当你编写或修改涉及预取请求、客户端路由导航或分段缓存的测试时,可以使用此方法。中的工具允许你以端到端的方式验证预取和导航响应,无需耦合到请求的具体数量或协议细节。这也是大多数客户端路由相关测试采用该模式的原因。
test/lib/router-act.tscreateRouterActWhen NOT to Use act
act何时不使用act
actDon't bother with 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 , , and are sufficient.
actbrowser.elementById()browser.elementByCss()browser.waitForElementByCss()如果你不需要监控网络响应——无论是控制其时机还是验证其中包含的内容——那么无需使用。如果你只是在导航后等待UI的某些部分显示,使用常规的Playwright辅助方法(如、和)就足够了。
actbrowser.elementById()browser.elementByCss()browser.waitForElementByCss()Core Principles
核心原则
- Use to control when prefetches happen. Never let links be visible outside an
LinkAccordionscope.act - Prefer whenever the data should be served from cache. This is the strongest assertion — it proves the cache is working.
'no-requests' - Avoid retry/polling timers. The utility exists specifically to replace inherently flaky patterns like
actloops orretry()waits for network activity. If you find yourself wanting to poll, you're probably not usingsetTimeoutcorrectly.act - Avoid the feature. It's prone to false negatives. Prefer
blockandincludesassertions instead.'no-requests'
- 使用控制预取触发时机。绝不要让链接在
LinkAccordion作用域之外可见。act - 优先使用断言,当数据应从缓存获取时。这是最强的断言——它能证明缓存正在正常工作。
'no-requests' - 避免重试/轮询计时器。工具的存在正是为了替代像
act循环或retry()等待网络活动这类本质上不稳定的模式。如果你发现自己想要使用轮询,很可能是没有正确使用setTimeout。act - 避免使用功能。它容易产生假阴性结果。优先使用
block和includes断言。'no-requests'
Act API
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 () => { ... })typescript
// 断言没有路由请求发出(数据从缓存获取)。
// 尽可能优先使用此方式——这是最强的断言。
await act(async () => { ... }, 'no-requests')
// 期望至少一个响应包含此子字符串
await act(async () => { ... }, { includes: 'Page content' })
// 期望多个响应(按顺序检查)
await act(async () => { ... }, [
{ includes: 'First response' },
{ includes: 'Second response' },
])
// 断言相同内容出现在两个独立的响应中
await act(async () => { ... }, [
{ includes: 'Repeated content' },
{ includes: 'Repeated content' },
])
// 期望至少一个请求,不验证内容
await act(async () => { ... })How includes
Matching Works
includesincludes
匹配的工作原理
includes- The substring is matched against the HTTP response body. Use text content that appears literally in the rendered output (e.g.
includes).'Dynamic content (stale time 60s)' - Extra responses that don't match any 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.
includes - Each expectation claims exactly one response. If the same substring appears in N separate responses, provide N separate
includesentries.{ includes: '...' }
- 子字符串会与HTTP响应体进行匹配。使用渲染输出中字面存在的文本内容(例如
includes)。'Dynamic content (stale time 60s)' - 任何与断言不匹配的额外响应都会被静默忽略——你只需要验证你关心的响应即可。这能让测试与路由发出的请求具体数量解耦。
includes - 每个断言对应恰好一个响应。如果相同的子字符串出现在N个独立响应中,请提供N个独立的
includes条目。{ includes: '...' }
What act
Does Internally
actact
内部工作机制
actact- Installs a Playwright route handler to intercept router requests
- Runs your scope function
- Waits for a (captures IntersectionObserver-triggered prefetches)
requestIdleCallback - Fulfills buffered responses to the browser
- Repeats steps 3-4 until no more requests arrive
- 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 handle the rest. Read destination page content after returns:
actacttypescript
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')act- 安装Playwright路由处理器以拦截路由请求
- 运行你的作用域函数
- 等待(捕获由IntersectionObserver触发的预取)
requestIdleCallback - 向浏览器转发缓冲的响应
- 重复步骤3-4直到没有更多请求到达
- 根据配置验证响应
响应会被缓冲,直到作用域函数返回后才会转发给浏览器。这意味着你不能在同一个作用域内导航到新页面并等待其渲染——这会导致死锁。触发导航(点击链接)后,让处理其余操作。在返回后再读取目标页面的内容:
actacttypescript
await act(
async () => {
/* 切换折叠面板,点击链接 */
},
{ includes: 'Page content' }
)
// 在act返回后读取内容,不要在作用域内读取
expect(await browser.elementById('my-content').text()).toBe('Page content')LinkAccordion Pattern
LinkAccordion模式
Why LinkAccordion Exists
LinkAccordion的存在意义
LinkAccordion<Link><Link>acttsx
// 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 (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}LinkAccordion<Link><Link>acttsx
// 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 (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}Standard Navigation Pattern
标准导航模式
Always toggle the accordion and click the link inside the same scope:
acttypescript
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' }
)始终在同一个作用域内切换折叠面板并点击链接:
acttypescript
await act(
async () => {
// 1. 切换折叠面板——Link进入DOM,触发预取
const toggle = await browser.elementByCss(
'input[data-link-accordion="/target-page"]'
)
await toggle.click()
// 2. 点击现在可见的链接——触发导航
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
browser.back()配合展开的折叠面板使用browser.back()
browser.back()Do not use to return to a page where accordions were previously opened. BFCache restores the full React state including values, so previously-opened Links are immediately visible. This triggers IntersectionObserver callbacks outside any scope — if the cached data is stale, uncontrolled re-prefetches fire and break subsequent assertions.
browser.back()useStateactno-requestsThe only safe use of / is when testing BFCache behavior specifically.
browser.back()browser.forward()Fix: navigate forward to a fresh hub page instead. See Hub Pages.
不要使用返回之前打开过折叠面板的页面。BFCache会恢复完整的React状态,包括的值,因此之前打开的链接会立即可见。这会在作用域之外触发IntersectionObserver回调——如果缓存数据已过期,不受控制的重新预取会触发并破坏后续的断言。
browser.back()useStateactno-requests只有在专门测试BFCache行为时,才可以安全使用/。
browser.back()browser.forward()修复方案: 改为导航到全新的中心页面。请参阅中心页面。
Using visible <Link>
components outside act
scopes
<Link>act在act
作用域之外使用可见的<Link>
组件
act<Link>Any visible in the viewport can trigger a prefetch at any time via IntersectionObserver. If this happens outside an scope, the request is uncontrolled and can interfere with subsequent assertions. Always hide links behind and only toggle them inside .
<Link>actLinkAccordionact任何在视口中可见的组件都可能随时通过IntersectionObserver触发预取。如果这发生在作用域之外,请求将不受控制,并可能干扰后续的断言。始终将链接隐藏在后面,并且只在作用域内切换它们。
<Link>actLinkAccordionactUsing retry/polling timers to wait for network activity
使用重试/轮询计时器等待网络活动
retry()setTimeoutactretry()setTimeoutactNavigating and waiting for render in the same act
scope
act在同一个act
作用域内导航并等待渲染
actResponses are buffered until the scope exits. Clicking a link then reading destination content in the same scope deadlocks. Read page content after returns instead.
act响应会被缓冲直到作用域退出。在同一个作用域内点击链接然后读取目标内容会导致死锁。请在返回后再读取页面内容。
actHub Pages
中心页面
When you need to navigate away from a page and come back to test staleness, use "hub" pages instead of . Each hub is a fresh page with its own components that start closed.
browser.back()LinkAccordionHub pages use to ensure they are dynamically rendered. This guarantees that navigating to a hub always produces a router request, which lets properly manage the navigation and wait for the page to fully render before continuing.
connection()actHub 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 <div id="hub-a-content">Hub a</div>
}
export default function Page() {
return (
<>
<Suspense fallback="Loading...">
<Content />
</Suspense>
<ul>
<li>
<LinkAccordion href="/my-test/target-page">Target page</LinkAccordion>
</li>
</ul>
</>
)
}Target pages link to hubs via LinkAccordion too:
tsx
// On target pages, add LinkAccordion links to hub pages
<LinkAccordion href="/my-test/hub-a">Hub A</LinkAccordion>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当你需要从一个页面导航离开并返回以测试过期情况时,请使用“中心”页面替代。每个中心页面都是全新的页面,其所有折叠面板默认都是关闭的。
browser.back()中心页面使用确保它们是动态渲染的。这能保证导航到中心页面始终会产生一个路由请求,从而让可以正确管理导航,并在继续之前等待页面完全渲染。
connection()act中心页面模式:
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 <div id="hub-a-content">Hub a</div>
}
export default function Page() {
return (
<>
<Suspense fallback="Loading...">
<Content />
</Suspense>
<ul>
<li>
<LinkAccordion href="/my-test/target-page">Target page</LinkAccordion>
</li>
</ul>
</>
)
}目标页面也通过LinkAccordion链接到中心页面:
tsx
// 在目标页面上,添加指向中心页面的LinkAccordion链接
<LinkAccordion href="/my-test/hub-a">Hub A</LinkAccordion>测试流程:
typescript
// 1. 导航到目标页面(首次访问)
await act(
async () => {
/* 切换折叠面板,点击链接 */
},
{ includes: 'Target content' }
)
// 2. 导航到hub-a(全新页面,所有折叠面板关闭)
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. 推进时间
await page.clock.setFixedTime(startDate + 60 * 1000)
// 4. 从中心页面导航回目标页面(受控预取)
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') // 如果数据已过期则使用{ includes: '...' }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 }
}- changes
setFixedTimereturn value but timers still run in real timeDate.now() - The segment cache uses for staleness checks
Date.now() - Advancing the clock doesn't trigger IntersectionObserver — only viewport changes do
- does NOT fire pending
setFixedTime/setTimeoutcallbackssetInterval
分段缓存过期测试使用Playwright的时钟API来控制:
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的返回值,但计时器仍会实时运行Date.now() - 分段缓存使用进行过期检查
Date.now() - 推进时钟不会触发IntersectionObserver——只有视口变化才会
- 不会触发挂起的
setFixedTime/setTimeout回调setInterval
Reference
参考
- :
createRouterActtest/lib/router-act.ts - :
LinkAccordiontest/e2e/app-dir/segment-cache/staleness/components/link-accordion.tsx - Example tests:
test/e2e/app-dir/segment-cache/staleness/
- :
createRouterActtest/lib/router-act.ts - :
LinkAccordiontest/e2e/app-dir/segment-cache/staleness/components/link-accordion.tsx - 示例测试:
test/e2e/app-dir/segment-cache/staleness/