Unverified Commit 5fbb9aa9 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Add Instant Navigation Testing API (#89465)

## Summary

Adds a dev-mode primitive for writing e2e tests that assert on the
prefetched/cached portion of a navigation. The API blocks dynamic data
from streaming in until assertions complete, allowing deterministic
testing of loading states without race conditions.

This gives developers a way to verify that specific UI elements render
instantly from cache, rather than relying on network timing. It also
reinforces the mental model that navigation performance should be
thought of primarily in terms of cached vs. dynamic.

This PR implements the primitive that Next.js exposes on the window
object. In practice, it's meant to be used via a testing framework
integration, like a Playwright helper:

```typescript
await instant(page, async () => {
  await page.click('a[href="/products/123"]');
  await expect(page.locator('[data-testid="skeleton"]')).toBeVisible();
});
```

The implementation forces a prefetch before navigation when inside an
`instant` scope (since prefetching is normally disabled in dev), then
holds dynamic data until the scope ends. All code is wrapped in dev
checks and gets dead code eliminated in production.

Current scope is client-side navigations only. SSR/MPA support is
planned as a follow-up.

## Test plan

- `test/e2e/app-dir/instant-navigation-testing-api`
parent 178a4c71
......@@ -36,6 +36,7 @@ import { getIsPossibleServerAction } from '../../server/lib/server-action-reques
import {
RSC_HEADER,
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_INSTANT_PREFETCH_HEADER,
NEXT_IS_PRERENDER_HEADER,
NEXT_DID_POSTPONE_HEADER,
RSC_CONTENT_TYPE_HEADER,
......@@ -346,6 +347,14 @@ export async function handler(
const hasDebugFallbackShellQuery =
hasDebugStaticShellQuery && query.__nextppronly === 'fallback'
// Dev-only: Enable the Instant Navigation Testing API. Renders only the
// prefetched portion of the page, excluding dynamic content. This allows
// tests to assert on the prefetched UI state deterministically.
const hasInstantPrefetchHeader =
routeModule.isDev === true &&
req.headers[NEXT_INSTANT_PREFETCH_HEADER] === '1' &&
couldSupportPPR
// This page supports PPR if it is marked as being `PARTIALLY_STATIC` in the
// prerender manifest and this is an app page.
const isRoutePPREnabled: boolean =
......@@ -358,12 +367,12 @@ export async function handler(
// enabled or not, but that would require plumbing the appConfig through
// to the server during development. We assume that the page supports it
// but only during development.
(hasDebugStaticShellQuery &&
((hasDebugStaticShellQuery || hasInstantPrefetchHeader) &&
(routeModule.isDev === true ||
routerServerContext?.experimentalTestProxy === true)))
const isDebugStaticShell: boolean =
hasDebugStaticShellQuery && isRoutePPREnabled
(hasDebugStaticShellQuery || hasInstantPrefetchHeader) && isRoutePPREnabled
// We should enable debugging dynamic accesses when the static shell
// debugging has been enabled and we're also in development mode.
......
......@@ -5,3 +5,17 @@ import '../build/polyfills/polyfill-module'
if (process.env.NODE_ENV !== 'production') {
require('../next-devtools/userspace/app/app-dev-overlay-setup') as typeof import('../next-devtools/userspace/app/app-dev-overlay-setup')
}
// Expose a testing API that allows e2e tests to assert on the prefetched UI
// state before dynamic data streams in. Dev-only, browser-only.
if (process.env.NODE_ENV !== 'production' && typeof window !== 'undefined') {
const { acquireNavigationLock, releaseNavigationLock } =
require('./components/segment-cache/dev-navigation-lock') as typeof import('./components/segment-cache/dev-navigation-lock')
window.__EXPERIMENTAL_NEXT_TESTING__ = {
navigation: {
lock: acquireNavigationLock,
unlock: releaseNavigationLock,
},
}
}
......@@ -65,6 +65,16 @@ declare global {
*/
__next_r?: string
__next_f: NextFlight
/**
* Testing API that allows e2e tests to assert on the prefetched UI state
* before dynamic data streams in. Dev-only.
*/
__EXPERIMENTAL_NEXT_TESTING__?: {
navigation: {
lock: () => void
unlock: () => void
}
}
}
}
......
......@@ -16,6 +16,12 @@ export const NEXT_HMR_REFRESH_HASH_COOKIE = '__next_hmr_refresh_hash__' as const
export const NEXT_URL = 'next-url' as const
export const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const
// Dev-only header for the Instant Navigation Testing API. In dev mode, static
// pre-renders normally don't happen. This header tells the server to perform
// a static pre-render anyway, allowing tests to assert on the prefetched UI.
export const NEXT_INSTANT_PREFETCH_HEADER =
'next-dev-only-instant-prefetch' as const
export const FLIGHT_HEADERS = [
RSC_HEADER,
NEXT_ROUTER_STATE_TREE_HEADER,
......
......@@ -83,6 +83,17 @@ export function unmountLinkForCurrentNavigation(link: LinkInstance) {
}
}
/**
* Returns the link instance that initiated the most recent navigation.
* Returns null if the navigation was not initiated by a link click.
*
* Used by the Instant Navigation Testing API in dev mode to match the
* fetch strategy of the link during cache-miss navigations.
*/
export function getLinkForCurrentNavigation(): LinkInstance | null {
return linkForMostRecentNavigation
}
// Use a WeakMap to associate a Link instance with its DOM element. This is
// used by the IntersectionObserver to track the link's visibility.
const prefetchable:
......
......@@ -15,6 +15,7 @@ import type {
import {
type NEXT_ROUTER_PREFETCH_HEADER,
type NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
type NEXT_INSTANT_PREFETCH_HEADER,
NEXT_ROUTER_STATE_TREE_HEADER,
NEXT_RSC_UNION_QUERY,
NEXT_URL,
......@@ -93,6 +94,7 @@ export type RequestHeaders = {
'Next-Test-Fetch-Priority'?: RequestInit['priority']
[NEXT_HTML_REQUEST_ID_HEADER]?: string // dev-only
[NEXT_REQUEST_ID_HEADER]?: string // dev-only
[NEXT_INSTANT_PREFETCH_HEADER]?: '1' // dev-only
}
function doMpaNavigation(url: string): FetchServerResponseResult {
......
......@@ -1531,6 +1531,14 @@ async function fetchMissingDynamicData(
result.flightData,
result.renderedSearch
)
// Dev-only: If the navigation lock is active, wait for it to be released
// before writing the dynamic data. This allows tests to assert on the
// prefetched UI state.
if (process.env.NODE_ENV !== 'production') {
await waitForNavigationLock()
}
const didReceiveUnknownParallelRoute = writeDynamicDataIntoNavigationTask(
task,
seed.routeTree,
......@@ -1870,3 +1878,17 @@ function createDeferredRsc<
return pendingRsc
}
/**
* Dev-only helper for the Instant Navigation Testing API. Waits for the
* navigation lock to be released before returning. The network request has
* already completed by the time this is called, so this only delays writing
* the dynamic data.
*/
async function waitForNavigationLock(): Promise<void> {
if (process.env.NODE_ENV !== 'production') {
const { waitForNavigationLockIfActive } =
require('../segment-cache/dev-navigation-lock') as typeof import('../segment-cache/dev-navigation-lock')
await waitForNavigationLockIfActive()
}
}
......@@ -14,6 +14,7 @@ import {
import { HasLoadingBoundary } from '../../../shared/lib/app-router-types'
import {
NEXT_DID_POSTPONE_HEADER,
NEXT_INSTANT_PREFETCH_HEADER,
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_ROUTER_STALE_TIME_HEADER,
......@@ -1554,6 +1555,9 @@ export async function fetchRouteOnCacheMiss(
if (nextUrl !== null) {
headers[NEXT_URL] = nextUrl
}
// Dev-only: Tell the server to perform a static pre-render for the Instant
// Navigation Testing API. In dev mode, static pre-renders don't normally happen.
addInstantPrefetchHeaderIfLocked(headers)
try {
const url = new URL(pathname + search, location.origin)
......@@ -1860,6 +1864,9 @@ export async function fetchSegmentOnCacheMiss(
if (nextUrl !== null) {
headers[NEXT_URL] = nextUrl
}
// Dev-only: Tell the server to perform a static pre-render for the Instant
// Navigation Testing API. In dev mode, static pre-renders don't normally happen.
addInstantPrefetchHeaderIfLocked(headers)
const requestUrl = isOutputExportMode
? // In output: "export" mode, we need to add the segment path to the URL.
......@@ -2607,3 +2614,19 @@ export function canNewFetchStrategyProvideMoreContent(
): boolean {
return currentStrategy < newStrategy
}
/**
* Dev-only: Adds the instant prefetch header if the navigation lock is active.
* Uses a lazy require to ensure dead code elimination in production.
*/
function addInstantPrefetchHeaderIfLocked(
headers: Record<string, string>
): void {
if (process.env.NODE_ENV !== 'production') {
const { isNavigationLocked } =
require('./dev-navigation-lock') as typeof import('./dev-navigation-lock')
if (isNavigationLocked()) {
headers[NEXT_INSTANT_PREFETCH_HEADER] = '1'
}
}
}
/**
* Dev-only navigation lock for the Instant Navigation Testing API.
*
* This module is not meant to be used directly. It's exposed on the window
* object and intended to be called via a wrapper API integrated into an
* e2e testing framework like Playwright:
*
* async function instant(page, fn) {
* await page.evaluate(() => window.__EXPERIMENTAL_NEXT_TESTING__.navigation.lock())
* try {
* return await fn()
* } finally {
* await page.evaluate(() => window.__EXPERIMENTAL_NEXT_TESTING__.navigation.unlock())
* }
* }
*
* // Usage in a test:
* await instant(page, async () => {
* await page.click('a[href="/product"]')
* await expect(page.locator('[data-testid="loading"]')).toBeVisible()
* })
*
* When the lock is acquired:
* - Routes without a prefetch cache hit will wait for prefetch to complete
* before navigating.
* - Routes with a prefetch cache hit will wait before writing dynamic data
* into the UI.
*
* This allows tests to assert on the prefetched UI state before dynamic
* content streams in. Network requests are not blocked - they proceed in
* parallel while the lock is held.
*
* All functions in this module are wrapped in dev-mode checks so they get
* dead code eliminated in production builds.
*/
type NavigationLockState = {
promise: Promise<void>
resolve: () => void
}
let lockState: NavigationLockState | null = null
/**
* Acquires the navigation lock. While locked, navigations will wait for
* prefetch tasks to complete before proceeding.
*
* Logs an error if the lock is already acquired (concurrent locks are not
* allowed).
*
* Dev mode only.
*/
export function acquireNavigationLock(): void {
if (process.env.NODE_ENV !== 'production') {
if (lockState !== null) {
console.error(
'Navigation lock already acquired. Concurrent locks are not allowed. ' +
'Did you forget to release the previous lock?'
)
return
}
let resolve: () => void
const promise = new Promise<void>((r) => {
resolve = r
})
lockState = { promise, resolve: resolve! }
}
}
/**
* Releases the navigation lock. Any navigations that were waiting for
* prefetch completion will now proceed with dynamic data fetching.
*
* No-op if the lock is not currently acquired.
*
* Dev mode only.
*/
export function releaseNavigationLock(): void {
if (process.env.NODE_ENV !== 'production') {
if (lockState !== null) {
lockState.resolve()
lockState = null
}
}
}
/**
* Returns true if the navigation lock is currently acquired.
*
* Dev mode only. Always returns false in production.
*/
export function isNavigationLocked(): boolean {
if (process.env.NODE_ENV !== 'production') {
return lockState !== null
}
return false
}
/**
* Waits for the navigation lock to be released, if it's currently held.
* No-op if the lock is not acquired.
*
* Dev mode only.
*/
export async function waitForNavigationLockIfActive(): Promise<void> {
if (process.env.NODE_ENV !== 'production') {
if (lockState !== null) {
await lockState.promise
}
}
}
......@@ -24,6 +24,9 @@ import {
} from './cache'
import { discoverKnownRoute } from './optimistic-routes'
import { createCacheKey, type NormalizedSearch } from './cache-key'
import { schedulePrefetchTask } from './scheduler'
import { PrefetchPriority, FetchStrategy } from './types'
import { getLinkForCurrentNavigation } from '../links'
import type { PageVaryPath } from './vary-path'
import type { AppRouterState } from '../router-reducer/router-reducer-types'
import { computeChangedPath } from '../router-reducer/compute-changed-path'
......@@ -112,7 +115,8 @@ export function navigate(
// There's no matching prefetch for this route in the cache. We must lazily
// fetch it from the server before we can perform the navigation.
// TODO: If this is an gesture navigation, instead of performing a
//
// TODO: If this is a gesture navigation, instead of performing a
// dynamic request, we should do a runtime prefetch.
return navigateToUnknownRoute(
now,
......@@ -296,6 +300,27 @@ async function navigateToUnknownRoute(
shouldScroll: boolean,
navigateType: 'push' | 'replace'
): Promise<AppRouterState> {
// Dev-only: If the Instant Navigation Testing API lock is active, try to
// prefetch the route first. If the prefetch succeeds, navigate using the
// prefetched route tree. If it fails, fall through to the normal path.
if (process.env.NODE_ENV !== 'production') {
const prefetchResult = await tryNavigateUsingTestingAPIPrefetch(
state,
url,
currentUrl,
currentRenderedSearch,
nextUrl,
currentCacheNode,
currentFlightRouterState,
freshnessPolicy,
shouldScroll,
navigateType
)
if (prefetchResult !== null) {
return prefetchResult
}
}
// Runs when a navigation happens but there's no cached prefetch we can use.
// Don't bother to wait for a prefetch response; go straight to a full
// navigation that contains both static and dynamic data in a single stream.
......@@ -748,3 +773,79 @@ function convertServerPatchToFullTreeImpl(
data: clonedSeedData,
}
}
/**
* Dev-only helper for the Instant Navigation Testing API. If the navigation
* lock is active, schedules a prefetch task, waits for it to complete, and
* navigates using the prefetched route tree.
*
* Returns the new router state if navigation succeeded via prefetch, or null
* if the lock isn't active or the prefetch failed (caller should fall through
* to the normal unknown route path).
*/
async function tryNavigateUsingTestingAPIPrefetch(
state: AppRouterState,
url: URL,
currentUrl: URL,
currentRenderedSearch: string,
nextUrl: string | null,
currentCacheNode: CacheNode | null,
currentFlightRouterState: FlightRouterState,
freshnessPolicy: FreshnessPolicy,
shouldScroll: boolean,
navigateType: 'push' | 'replace'
): Promise<AppRouterState | null> {
if (process.env.NODE_ENV !== 'production') {
// Lazy require to ensure dead code elimination in production
const { isNavigationLocked } =
require('./dev-navigation-lock') as typeof import('./dev-navigation-lock')
if (!isNavigationLocked()) {
return null
}
// Use the link's fetch strategy so the test behavior matches what would
// happen if the route had been prefetched before navigation
const link = getLinkForCurrentNavigation()
const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR
const cacheKey = createCacheKey(url.href, nextUrl)
const { promise, resolve } = Promise.withResolvers<void>()
schedulePrefetchTask(
cacheKey,
currentFlightRouterState,
fetchStrategy,
PrefetchPriority.Default,
null, // onInvalidate
resolve // _onComplete callback
)
await promise
// Re-read from cache (should now be populated)
const now = Date.now()
const route = readRouteCacheEntry(now, cacheKey)
if (route !== null && route.status === EntryStatus.Fulfilled) {
return navigateUsingPrefetchedRouteTree(
now,
state,
url,
currentUrl,
currentRenderedSearch,
nextUrl,
currentCacheNode,
currentFlightRouterState,
freshnessPolicy,
shouldScroll,
navigateType,
route
)
}
// Prefetch failed - fall through to normal unknown route path. This is fine
// because the lock will still be held, and waitForNavigationLockIfActive()
// in the dynamic data path will block until the lock is released.
return null
}
return null
}
......@@ -150,6 +150,17 @@ export type PrefetchTask = {
* We also use this field to check whether a task is currently in the queue.
*/
_heapIndex: number
/**
* Dev-only. Called when the prefetch task finishes (either completed or
* canceled). Used by the Instant Navigation Testing API to await prefetch
* completion.
*
* Note: "Complete" means the scheduler has no more work to do for this task
* — all network requests have been spawned. It does not mean all data has
* been retrieved; responses may still be in flight.
*/
_onComplete?: () => void
}
const enum PrefetchTaskExitStatus {
......@@ -243,13 +254,15 @@ export type IncludeDynamicData = null | 'full' | 'dynamic'
* @param treeAtTimeOfPrefetch The app's current FlightRouterState
* @param fetchStrategy Whether to prefetch dynamic data, in addition to
* static data. This is used by `<Link prefetch={true}>`.
* @param _onComplete Dev-only. Called when the prefetch task finishes.
*/
export function schedulePrefetchTask(
key: RouteCacheKey,
treeAtTimeOfPrefetch: FlightRouterState,
fetchStrategy: PrefetchTaskFetchStrategy,
priority: PrefetchPriority,
onInvalidate: null | (() => void)
onInvalidate: null | (() => void),
_onComplete?: () => void
): PrefetchTask {
// Spawn a new prefetch task
const task: PrefetchTask = {
......@@ -267,6 +280,9 @@ export function schedulePrefetchTask(
onInvalidate,
_heapIndex: -1,
}
if (process.env.NODE_ENV !== 'production') {
task._onComplete = _onComplete
}
trackMostRecentlyHoveredLink(task)
......@@ -292,6 +308,14 @@ export function cancelPrefetchTask(task: PrefetchTask): void {
// does not get added back to the queue when it's pinged by the network.
task.isCanceled = true
heapDelete(taskHeap, task)
if (process.env.NODE_ENV !== 'production') {
// Call completion callback. In practice this shouldn't be reached for
// test-initiated prefetches since cancellation is only used by the Link
// component when elements scroll out of viewport.
const onComplete = task._onComplete
task._onComplete = undefined
onComplete?.()
}
}
export function reschedulePrefetchTask(
......@@ -306,6 +330,10 @@ export function reschedulePrefetchTask(
//
// The primary use case is to increase the priority of a Link-initated
// prefetch on hover.
//
// Note: _onComplete is not reset here because it's preserved on the same
// task object. When the rescheduled task completes, the original callback
// will still be invoked.
// Un-cancel the task, in case it was previously canceled.
task.isCanceled = false
......@@ -520,6 +548,13 @@ function processQueueInMicrotask() {
heapResift(taskHeap, task)
} else {
// The prefetch is complete. Continue to the next task.
if (process.env.NODE_ENV !== 'production') {
// Notify the Instant Navigation Testing API that the prefetch has
// completed, so it can proceed with navigation.
const onComplete = task._onComplete
task._onComplete = undefined
onComplete?.()
}
heapPop(taskHeap)
}
task = heapPeek(taskHeap)
......
export default function Loading() {
return (
<div data-testid="full-prefetch-loading">
Loading full prefetch target...
</div>
)
}
import { connection } from 'next/server'
export default async function FullPrefetchTargetPage() {
await connection()
return (
<div>
<h1>Full Prefetch Target</h1>
<div data-testid="full-prefetch-content">
Full prefetch content loaded
</div>
</div>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function HomePage() {
return (
<div>
<h1>Instant Navigation API Test</h1>
<Link href="/target-page" id="link-to-target">
Go to target page
</Link>
<Link
href="/runtime-prefetch-target?myParam=testValue"
id="link-to-runtime-prefetch"
>
Go to runtime prefetch target
</Link>
<Link
href="/full-prefetch-target"
prefetch={true}
id="link-to-full-prefetch"
>
Go to full prefetch target
</Link>
</div>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
export const unstable_prefetch = {
mode: 'runtime',
samples: [{ searchParams: { myParam: 'testValue' } }],
}
type SearchParams = { [key: string]: string | string[] | undefined }
export default async function RuntimePrefetchTargetPage({
searchParams,
}: {
searchParams: Promise<SearchParams>
}) {
return (
<div>
<h1>Runtime Prefetch Target</h1>
<Suspense fallback={<div data-testid="outer-loading">Loading...</div>}>
<RuntimePrefetchableContent searchParams={searchParams} />
</Suspense>
<Suspense
fallback={
<div data-testid="inner-loading">Loading dynamic content...</div>
}
>
<DynamicContent />
</Suspense>
</div>
)
}
async function RuntimePrefetchableContent({
searchParams,
}: {
searchParams: Promise<SearchParams>
}) {
const params = await searchParams
const myParam = params.myParam
return <p data-testid="search-param-value">{`myParam: ${myParam}`}</p>
}
async function DynamicContent() {
await connection()
return <div data-testid="dynamic-content">Dynamic content loaded</div>
}
export default function Loading() {
return <div data-testid="loading-shell">Loading target page...</div>
}
import { connection } from 'next/server'
export default async function TargetPage() {
await connection()
return (
<div>
<h1>Target Page</h1>
<div data-testid="dynamic-content">Dynamic content loaded</div>
</div>
)
}
/**
* Tests for the Instant Navigation Testing API.
*
* The `instant` helper allows tests to assert on the prefetched UI state
* before dynamic data streams in. This enables deterministic testing of
* loading states without race conditions.
*
* Usage example:
*
* await instant(page, async () => {
* await page.click('a[href="/products/123"]')
* // Assert on the prefetched loading UI
* await expect(page.locator('[data-testid="loading-shell"]')).toBeVisible()
* // Dynamic content hasn't streamed in yet
* expect(await page.locator('[data-testid="price"]').count()).toBe(0)
* })
* // After exiting instant(), dynamic content streams in
* await expect(page.locator('[data-testid="price"]')).toBeVisible()
*
* NOTE: This API is dev-mode only. The tests bail out in production mode.
*
* TODO: Add tests for initial page loads (SSR) and MPA navigations. These
* require a cookie-based approach since we can't set request headers for
* browser-native navigations like page.goto() or refresh.
*/
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
describe('instant-navigation-testing-api', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (!isNextDev) {
it('should not expose __EXPERIMENTAL_NEXT_TESTING__ API in production mode', async () => {
const browser = await next.browser('/')
const hasTestingAPI = await browser.eval(
'typeof window.__EXPERIMENTAL_NEXT_TESTING__ !== "undefined"'
)
expect(hasTestingAPI).toBe(false)
})
return
}
/**
* Opens a browser and returns the underlying Playwright Page instance.
*
* We use this pattern so our test assertions look as close as possible to
* what users would write with the actual Playwright helper package. The
* Next.js test infra wraps Playwright with its own BrowserInterface, but
* the Instant Navigation Testing API is designed to work with native Playwright.
*/
async function openPage(url: string): Promise<Playwright.Page> {
let page: Playwright.Page
await next.browser(url, {
beforePageLoad(p) {
page = p
},
})
return page!
}
/**
* Runs a function with instant navigation enabled. Within this scope,
* navigations render the prefetched UI immediately and wait for the
* callback to complete before streaming in dynamic data.
*
* This is the inline implementation of what will eventually be extracted
* to a Playwright helper package.
*/
async function instant<T>(
page: Playwright.Page,
fn: () => Promise<T>
): Promise<T> {
await page.evaluate(() =>
(window as any).__EXPERIMENTAL_NEXT_TESTING__?.navigation.lock()
)
try {
return await fn()
} finally {
await page.evaluate(() =>
(window as any).__EXPERIMENTAL_NEXT_TESTING__?.navigation.unlock()
)
}
}
it('renders prefetched loading shell instantly during navigation', async () => {
const page = await openPage('/')
await instant(page, async () => {
await page.click('#link-to-target')
// The loading shell appears immediately, without waiting for dynamic data
const loadingShell = page.locator('[data-testid="loading-shell"]')
await loadingShell.waitFor({ state: 'visible' })
expect(await loadingShell.textContent()).toContain(
'Loading target page...'
)
// Dynamic content has not streamed in yet
const dynamicContent = page.locator('[data-testid="dynamic-content"]')
expect(await dynamicContent.count()).toBe(0)
})
// After exiting the instant scope, dynamic content streams in
const dynamicContent = page.locator('[data-testid="dynamic-content"]')
await dynamicContent.waitFor({ state: 'visible' })
expect(await dynamicContent.textContent()).toContain(
'Dynamic content loaded'
)
})
it('renders runtime-prefetched content instantly during navigation', async () => {
const page = await openPage('/')
await instant(page, async () => {
await page.click('#link-to-runtime-prefetch')
// Content that depends on search params appears immediately because
// it was included in the runtime prefetch
const searchParamValue = page.locator(
'[data-testid="search-param-value"]'
)
await searchParamValue.waitFor({ state: 'visible' })
expect(await searchParamValue.textContent()).toContain(
'myParam: testValue'
)
// The loading state for dynamic content is visible
const innerLoading = page.locator('[data-testid="inner-loading"]')
await innerLoading.waitFor({ state: 'visible' })
expect(await innerLoading.textContent()).toContain(
'Loading dynamic content...'
)
// Dynamic content has not streamed in yet
const dynamicContent = page.locator('[data-testid="dynamic-content"]')
expect(await dynamicContent.count()).toBe(0)
})
// After exiting the instant scope, dynamic content streams in
const dynamicContent = page.locator('[data-testid="dynamic-content"]')
await dynamicContent.waitFor({ state: 'visible' })
expect(await dynamicContent.textContent()).toContain(
'Dynamic content loaded'
)
// Search param content remains visible
const searchParamValue = page.locator('[data-testid="search-param-value"]')
expect(await searchParamValue.textContent()).toContain('myParam: testValue')
})
it('renders full prefetch content instantly when prefetch={true}', async () => {
const page = await openPage('/')
await instant(page, async () => {
await page.click('#link-to-full-prefetch')
// With prefetch={true}, the dynamic content is included in the prefetch
// response, so it appears immediately without a loading state
const content = page.locator('[data-testid="full-prefetch-content"]')
await content.waitFor({ state: 'visible' })
expect(await content.textContent()).toContain(
'Full prefetch content loaded'
)
})
})
it('logs an error when attempting to nest instant scopes', async () => {
const page = await openPage('/')
const errors: string[] = []
page.on('console', (msg) => {
if (msg.type() === 'error') {
errors.push(msg.text())
}
})
await instant(page, async () => {
// Attempt to nest another instant scope - should log an error
await instant(page, async () => {})
})
expect(errors.some((e) => e.includes('already acquired'))).toBe(true)
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment