router-act
预览截图
安装方式
先用 Prompt 核对来源与依赖。也可下载安装包。
用 AI 助手安装
复制提示词,让助手先核对固定版本和依赖。
查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "router-act":https://skillpi.com/zh/skills/deepskill-00a50cbafc3335d7be1d086a714197985de0d8ef32fa8918c5bea64785299e8d。安装前核对上游来源和版本:https://github.com/vercel/next.js。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。
来源与配置
github.com
配置方式待核实
请查看原始来源中的适用工具、依赖和权限要求。
安装实测待补充
说明如何使用 createRouterAct 和 LinkAccordion 编写端到端测试。适用于编写或修改需要控制 Next.js 内部请求(如预取)时机或断言其响应的测试。涵盖 act API、fixture 模式、通过 LinkAccordion 控制预取、模拟时钟以及避免不稳定的测试模式。用户不可调用:false 元数据:内部:true
介绍来源: third_party · vercel · 1.0.0 参考来源
SkillPi 解读
- 能完成的任务
- 在写入或修改涉及预切请求,客户端路由器导航,或段缓存的测试时使用此技能. 这个 `createRouterAct` 工具从 `test/lib/router-act.ts` 允许您在不与请求的确切数量或协议细节相配合的情况下,以端到端的方式断言预和导航响应。 这就是为什么大多数客户端路由器相关的测试都使用这种模式.
- 适合谁
- 来源文档未说明。
- 输入和输出
- 来源文档未说明。
- 软件、账号及付费要求
- 翻译待完成,请参阅来源文档。
- 限制与区别
- 来源文档未说明。
- 实测状态
- 未测试
文件浏览
Frontmatter
name: router-act
description: >
How to write end-to-end tests using createRouterAct and LinkAccordion.
Use when writing or modifying tests that need to control the timing of
internal Next.js requests (like prefetches) or assert on their responses.
Covers the act API, fixture patterns, prefetch control via LinkAccordion,
fake clocks, and avoiding flaky testing patterns.
user-invocable: false
metadata:
internal: trueRouter 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
- Use
LinkAccordionto control when prefetches happen. Never let links be visible outside anactscope. - Prefer
'no-requests'whenever the data should be served from cache. This is the strongest assertion — it proves the cache is working. - Avoid retry/polling timers. The
actutility exists specifically to replace inherently flaky patterns likeretry()loops orsetTimeoutwaits for network activity. If you find yourself wanting to poll, you're probably not usingactcorrectly. - Avoid the
blockfeature. It's prone to false negatives. Preferincludesand'no-requests'assertions instead.
Act API
Config Options
// 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
includessubstring 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
includesassertion 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
includesexpectation 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:
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:
- Installs a Playwright route handler to intercept router requests
- Runs your scope function
- Waits for a
requestIdleCallback(captures IntersectionObserver-triggered prefetches) - 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 act handle the rest. Read destination page content after act returns:
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 <Link> components enter the DOM. A Next.js <Link> 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.
// 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 act scope:
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.
Using visible <Link> components outside act scopes
Any <Link> 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:
// 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:
// On target pages, add LinkAccordion links to hub pages
<LinkAccordion href="/my-test/hub-a">Hub A</LinkAccordion>
Test flow:
// 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():
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 }
}
setFixedTimechangesDate.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
setFixedTimedoes NOT fire pendingsetTimeout/setIntervalcallbacks
Reference
createRouterAct:test/lib/router-act.tsLinkAccordion:test/e2e/app-dir/segment-cache/staleness/components/link-accordion.tsx- Example tests:
test/e2e/app-dir/segment-cache/staleness/
当前收录版本
1.0.0
安全与评测信息
质量评测
满分100 · 来自 SkillPi LAB 实验室的评测报告。
亮点
- 提供 Next.js 路由测试的完整解决方案
- 涵盖 act API、LinkAccordion 模式、时钟控制等核心功能
- 包含详细的最佳实践和常见陷阱说明
亮点
- 触发描述清晰明确,覆盖多种测试场景
- 明确界定适用边界(When NOT to Use)
- 针对特定技术栈(Next.js 测试)精准定位
待提升项
-
缺少明确的 When to Use 章节标题 原报告严重程度:轻微
文档开头有使用场景说明,但未使用标准章节标题
改进建议:建议添加明确的 "When to Use" 章节标题以提升规范性
亮点
- 结构完整,章节划分清晰
- 包含丰富的代码示例和实际用例
- frontmatter 元数据完整规范
亮点
- 工具来源路径明确(test/lib/router-act.ts)
- API 参数说明详尽,覆盖各种使用场景
- 提供完整的异常处理和最佳实践指南
取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。
正文静态检测
100 / 100 · skillpi-20261123-no-r3-v1
正文未命中当前规则。
分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。
权限与使用前检查
根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。
未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。
安全评级与访问范围
safe · 静态证据核验,不代表运行安全保证。
翻译待完成,请参阅来源文档。
使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。
用户讨论
还没有已核实的点评。