Unverified Commit 44ab1be4 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Support MPA navigations in `instant()` (#89469)

Based on:

- https://github.com/vercel/next.js/pull/89465

---

The `instant()` testing API allows e2e tests to assert on prefetched UI
before dynamic data streams in. This extends it to handle full page
navigations: page reloads, plain anchor clicks, and browser
back/forward.

For client-side navigations, the API uses request headers to trigger
static shell rendering. For MPA navigations, headers aren't available,
so this uses a cookie-based approach instead. When `instant()` acquires
a lock, it sets a cookie that tells the server to render the static
shell. When the lock is released, the cookie is cleared and the page
reloads to fetch dynamic content.

On pages loaded with the test cookie, hydration is skipped entirely and
a minimal testing API is set up in the bootstrap script. This is similar
to how the `__nextppronly` debug parameter works (an internal experiment
that was never shipped). This feature is the productionized version of
that approach, designed for actual use in e2e tests.

New test cases:
- Static shell on page reload
- Static shell on plain anchor navigation
- Multiple MPA navigations within a single `instant()` scope
- Verifies navigations work normally after exiting `instant()` scope
parent 5fbb9aa9
...@@ -37,6 +37,7 @@ import { ...@@ -37,6 +37,7 @@ import {
RSC_HEADER, RSC_HEADER,
NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_PREFETCH_HEADER,
NEXT_INSTANT_PREFETCH_HEADER, NEXT_INSTANT_PREFETCH_HEADER,
NEXT_INSTANT_TEST_COOKIE,
NEXT_IS_PRERENDER_HEADER, NEXT_IS_PRERENDER_HEADER,
NEXT_DID_POSTPONE_HEADER, NEXT_DID_POSTPONE_HEADER,
RSC_CONTENT_TYPE_HEADER, RSC_CONTENT_TYPE_HEADER,
...@@ -350,10 +351,18 @@ export async function handler( ...@@ -350,10 +351,18 @@ export async function handler(
// Dev-only: Enable the Instant Navigation Testing API. Renders only the // Dev-only: Enable the Instant Navigation Testing API. Renders only the
// prefetched portion of the page, excluding dynamic content. This allows // prefetched portion of the page, excluding dynamic content. This allows
// tests to assert on the prefetched UI state deterministically. // tests to assert on the prefetched UI state deterministically.
const hasInstantPrefetchHeader = // - Header: Used for client-side navigations where we can set request headers
// - Cookie: Used for MPA navigations (page reload, full page load) where we
// can't set request headers. Only applies to document requests (no RSC
// header) - RSC requests should proceed normally even during a locked scope,
// with blocking happening on the client side.
const isInstantNavigationTest =
routeModule.isDev === true && routeModule.isDev === true &&
req.headers[NEXT_INSTANT_PREFETCH_HEADER] === '1' && couldSupportPPR &&
couldSupportPPR (req.headers[NEXT_INSTANT_PREFETCH_HEADER] === '1' ||
(req.headers[RSC_HEADER] === undefined &&
typeof req.headers.cookie === 'string' &&
req.headers.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=')))
// This page supports PPR if it is marked as being `PARTIALLY_STATIC` in the // This page supports PPR if it is marked as being `PARTIALLY_STATIC` in the
// prerender manifest and this is an app page. // prerender manifest and this is an app page.
...@@ -367,12 +376,12 @@ export async function handler( ...@@ -367,12 +376,12 @@ export async function handler(
// enabled or not, but that would require plumbing the appConfig through // enabled or not, but that would require plumbing the appConfig through
// to the server during development. We assume that the page supports it // to the server during development. We assume that the page supports it
// but only during development. // but only during development.
((hasDebugStaticShellQuery || hasInstantPrefetchHeader) && ((hasDebugStaticShellQuery || isInstantNavigationTest) &&
(routeModule.isDev === true || (routeModule.isDev === true ||
routerServerContext?.experimentalTestProxy === true))) routerServerContext?.experimentalTestProxy === true)))
const isDebugStaticShell: boolean = const isDebugStaticShell: boolean =
(hasDebugStaticShellQuery || hasInstantPrefetchHeader) && isRoutePPREnabled (hasDebugStaticShellQuery || isInstantNavigationTest) && isRoutePPREnabled
// We should enable debugging dynamic accesses when the static shell // We should enable debugging dynamic accesses when the static shell
// debugging has been enabled and we're also in development mode. // debugging has been enabled and we're also in development mode.
......
...@@ -76,6 +76,34 @@ export function appBootstrap(hydrate: (assetPrefix: string) => void) { ...@@ -76,6 +76,34 @@ export function appBootstrap(hydrate: (assetPrefix: string) => void) {
} }
} }
// Instant Navigation Testing API: If the page was loaded with the instant
// test cookie set (from an MPA navigation while locked), skip hydration
// and set up a minimal testing API. Hydration would fail because the
// static shell response doesn't include the full Flight data stream.
// When unlock() is called, we clear the cookie and reload the page.
if (process.env.NODE_ENV !== 'production') {
const NEXT_INSTANT_TEST_COOKIE = 'next-dev-only-instant-test'
if (document.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=')) {
// Set up minimal testing API for the static shell
window.__EXPERIMENTAL_NEXT_TESTING__ = {
navigation: {
lock: () => {
console.error(
'Navigation lock already acquired. Concurrent locks are not allowed. ' +
'Did you forget to release the previous lock?'
)
},
unlock: () => {
// Clear the cookie and reload to get the full page with dynamic data
document.cookie = `${NEXT_INSTANT_TEST_COOKIE}=;path=/;max-age=0`
window.location.reload()
},
},
}
return
}
}
hydrate(assetPrefix) hydrate(assetPrefix)
}) })
} }
...@@ -22,6 +22,11 @@ export const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const ...@@ -22,6 +22,11 @@ export const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const
export const NEXT_INSTANT_PREFETCH_HEADER = export const NEXT_INSTANT_PREFETCH_HEADER =
'next-dev-only-instant-prefetch' as const 'next-dev-only-instant-prefetch' as const
// Dev-only cookie for the Instant Navigation Testing API. Used for MPA
// navigations (page reload, full page load) where we can't set request headers.
// When set, the server renders only the static shell.
export const NEXT_INSTANT_TEST_COOKIE = 'next-dev-only-instant-test' as const
export const FLIGHT_HEADERS = [ export const FLIGHT_HEADERS = [
RSC_HEADER, RSC_HEADER,
NEXT_ROUTER_STATE_TREE_HEADER, NEXT_ROUTER_STATE_TREE_HEADER,
......
import type { import type {
ReadonlyReducerState, ReadonlyReducerState,
ReducerState, ReducerState,
RefreshAction,
} from '../router-reducer-types' } from '../router-reducer-types'
import { import {
convertServerPatchToFullTree, convertServerPatchToFullTree,
...@@ -11,14 +12,25 @@ import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-c ...@@ -11,14 +12,25 @@ import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-c
import { FreshnessPolicy } from '../ppr-navigations' import { FreshnessPolicy } from '../ppr-navigations'
import { invalidateBfCache } from '../../segment-cache/bfcache' import { invalidateBfCache } from '../../segment-cache/bfcache'
export function refreshReducer(state: ReadonlyReducerState): ReducerState { export function refreshReducer(
state: ReadonlyReducerState,
action: RefreshAction
): ReducerState {
// During a refresh, we invalidate the segment cache but not the route cache. // During a refresh, we invalidate the segment cache but not the route cache.
// The route cache contains the tree structure (which segments exist at a // The route cache contains the tree structure (which segments exist at a
// given URL) which doesn't change during a refresh. The segment cache // given URL) which doesn't change during a refresh. The segment cache
// contains the actual RSC data which needs to be re-fetched. // contains the actual RSC data which needs to be re-fetched.
const currentNextUrl = state.nextUrl //
const currentRouterState = state.tree // Dev-only: The Instant Navigation Testing API can bypass cache invalidation
invalidateSegmentCacheEntries(currentNextUrl, currentRouterState) // to preserve prefetched data when refreshing after an MPA navigation. This
// is only used for testing and is not exposed in production builds.
const bypassCacheInvalidation =
process.env.NODE_ENV !== 'production' && action.devBypassCacheInvalidation
if (!bypassCacheInvalidation) {
const currentNextUrl = state.nextUrl
const currentRouterState = state.tree
invalidateSegmentCacheEntries(currentNextUrl, currentRouterState)
}
return refreshDynamicData(state, FreshnessPolicy.RefreshAll) return refreshDynamicData(state, FreshnessPolicy.RefreshAll)
} }
......
import { createHrefFromUrl } from '../create-href-from-url' import { createHrefFromUrl } from '../create-href-from-url'
import type { import {
ServerPatchAction, ACTION_REFRESH,
ReducerState, type ServerPatchAction,
ReadonlyReducerState, type ReducerState,
type ReadonlyReducerState,
} from '../router-reducer-types' } from '../router-reducer-types'
import { import {
completeHardNavigation, completeHardNavigation,
...@@ -35,7 +36,7 @@ export function serverPatchReducer( ...@@ -35,7 +36,7 @@ export function serverPatchReducer(
// There was another, more recent navigation since the once that // There was another, more recent navigation since the once that
// mismatched. We can abort the retry, but we still need to refresh the // mismatched. We can abort the retry, but we still need to refresh the
// page to evict any stale dynamic data. // page to evict any stale dynamic data.
return refreshReducer(state) return refreshReducer(state, { type: ACTION_REFRESH })
} }
// There have been no new navigations since the mismatched one. Refresh, // There have been no new navigations since the mismatched one. Refresh,
// using the tree we just received from the server. // using the tree we just received from the server.
......
...@@ -30,6 +30,12 @@ export type RouterChangeByServerResponse = ({ ...@@ -30,6 +30,12 @@ export type RouterChangeByServerResponse = ({
*/ */
export interface RefreshAction { export interface RefreshAction {
type: typeof ACTION_REFRESH type: typeof ACTION_REFRESH
/**
* Dev-only. Bypass invalidating the segment cache. Used by the Instant
* Navigation Testing API to preserve prefetched data when refreshing after
* an MPA navigation.
*/
devBypassCacheInvalidation?: boolean
} }
export interface HmrRefreshAction { export interface HmrRefreshAction {
......
...@@ -36,7 +36,7 @@ function clientReducer( ...@@ -36,7 +36,7 @@ function clientReducer(
return restoreReducer(state, action) return restoreReducer(state, action)
} }
case ACTION_REFRESH: { case ACTION_REFRESH: {
return refreshReducer(state) return refreshReducer(state, action)
} }
case ACTION_HMR_REFRESH: { case ACTION_HMR_REFRESH: {
return hmrRefreshReducer(state) return hmrRefreshReducer(state)
......
...@@ -26,6 +26,11 @@ ...@@ -26,6 +26,11 @@
* - Routes with a prefetch cache hit will wait before writing dynamic data * - Routes with a prefetch cache hit will wait before writing dynamic data
* into the UI. * into the UI.
* *
* For MPA navigations (page reload, full page load):
* - A cookie is set that tells the server to render only the static shell.
* - When the lock is released, the cookie is cleared and a refresh is
* triggered to fetch dynamic data.
*
* This allows tests to assert on the prefetched UI state before dynamic * This allows tests to assert on the prefetched UI state before dynamic
* content streams in. Network requests are not blocked - they proceed in * content streams in. Network requests are not blocked - they proceed in
* parallel while the lock is held. * parallel while the lock is held.
...@@ -34,6 +39,8 @@ ...@@ -34,6 +39,8 @@
* dead code eliminated in production builds. * dead code eliminated in production builds.
*/ */
import { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers'
type NavigationLockState = { type NavigationLockState = {
promise: Promise<void> promise: Promise<void>
resolve: () => void resolve: () => void
...@@ -41,10 +48,17 @@ type NavigationLockState = { ...@@ -41,10 +48,17 @@ type NavigationLockState = {
let lockState: NavigationLockState | null = null let lockState: NavigationLockState | null = null
// Tracks whether the page was loaded while the instant test cookie was set.
// When true, releasing the lock will trigger a refresh to fetch dynamic data.
let mpaLockedStateNeedsRefresh = false
/** /**
* Acquires the navigation lock. While locked, navigations will wait for * Acquires the navigation lock. While locked, navigations will wait for
* prefetch tasks to complete before proceeding. * prefetch tasks to complete before proceeding.
* *
* Also sets a cookie so that MPA navigations (page reload, full page load)
* will render only the static shell.
*
* Logs an error if the lock is already acquired (concurrent locks are not * Logs an error if the lock is already acquired (concurrent locks are not
* allowed). * allowed).
* *
...@@ -65,6 +79,9 @@ export function acquireNavigationLock(): void { ...@@ -65,6 +79,9 @@ export function acquireNavigationLock(): void {
resolve = r resolve = r
}) })
lockState = { promise, resolve: resolve! } lockState = { promise, resolve: resolve! }
// Set cookie for MPA navigations
document.cookie = `${NEXT_INSTANT_TEST_COOKIE}=1;path=/`
} }
} }
...@@ -72,6 +89,10 @@ export function acquireNavigationLock(): void { ...@@ -72,6 +89,10 @@ export function acquireNavigationLock(): void {
* Releases the navigation lock. Any navigations that were waiting for * Releases the navigation lock. Any navigations that were waiting for
* prefetch completion will now proceed with dynamic data fetching. * prefetch completion will now proceed with dynamic data fetching.
* *
* If the page was loaded while locked (MPA navigation), this also triggers
* a refresh to fetch the dynamic data that was blocked during the initial
* page load.
*
* No-op if the lock is not currently acquired. * No-op if the lock is not currently acquired.
* *
* Dev mode only. * Dev mode only.
...@@ -82,6 +103,16 @@ export function releaseNavigationLock(): void { ...@@ -82,6 +103,16 @@ export function releaseNavigationLock(): void {
lockState.resolve() lockState.resolve()
lockState = null lockState = null
} }
// Clear the cookie
document.cookie = `${NEXT_INSTANT_TEST_COOKIE}=;path=/;max-age=0`
// If the page was loaded with the cookie set (MPA navigation), trigger a
// refresh to fetch the dynamic data that was blocked during SSR.
if (mpaLockedStateNeedsRefresh) {
mpaLockedStateNeedsRefresh = false
triggerRefresh()
}
} }
} }
...@@ -110,3 +141,46 @@ export async function waitForNavigationLockIfActive(): Promise<void> { ...@@ -110,3 +141,46 @@ export async function waitForNavigationLockIfActive(): Promise<void> {
} }
} }
} }
/**
* Called during page initialization when the instant test cookie is detected.
* Sets up the lock state so that:
* 1. Client-side navigations during the instant scope also block dynamic data
* 2. When the lock is released, a refresh is triggered to fetch dynamic data
*
* Dev mode only.
*/
export function initializeMpaLockedState(): void {
if (process.env.NODE_ENV !== 'production') {
// Set the MPA flag so we know to trigger a refresh when the lock is released
mpaLockedStateNeedsRefresh = true
// Also acquire the in-memory lock so client-side navigations during the
// instant scope also block dynamic data
if (lockState === null) {
let resolve: () => void
const promise = new Promise<void>((r) => {
resolve = r
})
lockState = { promise, resolve: resolve! }
}
}
}
/**
* Triggers a router refresh to fetch dynamic data. Used after releasing the
* navigation lock following an MPA navigation.
*/
function triggerRefresh(): void {
if (process.env.NODE_ENV !== 'production') {
const { dispatchAppRouterAction } =
require('../use-action-queue') as typeof import('../use-action-queue')
const { ACTION_REFRESH } =
require('../router-reducer/router-reducer-types') as typeof import('../router-reducer/router-reducer-types')
dispatchAppRouterAction({
type: ACTION_REFRESH,
devBypassCacheInvalidation: true,
})
}
}
...@@ -90,6 +90,7 @@ import { ...@@ -90,6 +90,7 @@ import {
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_URL, NEXT_URL,
NEXT_ROUTER_STATE_TREE_HEADER, NEXT_ROUTER_STATE_TREE_HEADER,
NEXT_INSTANT_TEST_COOKIE,
} from '../client/components/app-router-headers' } from '../client/components/app-router-headers'
import type { import type {
MatchOptions, MatchOptions,
...@@ -2196,6 +2197,18 @@ export default abstract class Server< ...@@ -2196,6 +2197,18 @@ export default abstract class Server<
typeof query.__nextppronly !== 'undefined' && typeof query.__nextppronly !== 'undefined' &&
couldSupportPPR couldSupportPPR
// Dev-only: Check for the instant test cookie for MPA navigations (page
// reload, full page load) in the Instant Navigation Testing API. Only
// applies to document requests (no RSC header) - RSC requests should
// proceed normally even during a locked scope, with blocking happening
// on the client side.
const hasInstantTestCookie =
this.renderOpts.dev === true &&
req.headers[RSC_HEADER] === undefined &&
typeof req.headers.cookie === 'string' &&
req.headers.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=') &&
couldSupportPPR
// This page supports PPR if it is marked as being `PARTIALLY_STATIC` in the // This page supports PPR if it is marked as being `PARTIALLY_STATIC` in the
// prerender manifest and this is an app page. // prerender manifest and this is an app page.
const isRoutePPREnabled: boolean = const isRoutePPREnabled: boolean =
...@@ -2208,7 +2221,7 @@ export default abstract class Server< ...@@ -2208,7 +2221,7 @@ export default abstract class Server<
// enabled or not, but that would require plumbing the appConfig through // enabled or not, but that would require plumbing the appConfig through
// to the server during development. We assume that the page supports it // to the server during development. We assume that the page supports it
// but only during development. // but only during development.
(hasDebugStaticShellQuery && ((hasDebugStaticShellQuery || hasInstantTestCookie) &&
(this.renderOpts.dev === true || (this.renderOpts.dev === true ||
this.experimentalTestProxy === true))) this.experimentalTestProxy === true)))
......
...@@ -3,7 +3,7 @@ import Link from 'next/link' ...@@ -3,7 +3,7 @@ import Link from 'next/link'
export default function HomePage() { export default function HomePage() {
return ( return (
<div> <div>
<h1>Instant Navigation API Test</h1> <h1 data-testid="home-title">Instant Navigation API Test</h1>
<Link href="/target-page" id="link-to-target"> <Link href="/target-page" id="link-to-target">
Go to target page Go to target page
</Link> </Link>
...@@ -20,6 +20,10 @@ export default function HomePage() { ...@@ -20,6 +20,10 @@ export default function HomePage() {
> >
Go to full prefetch target Go to full prefetch target
</Link> </Link>
{/* Plain anchor for MPA navigation testing (bypasses client-side routing) */}
<a href="/target-page" id="plain-link-to-target">
Go to target page (MPA)
</a>
</div> </div>
) )
} }
...@@ -18,10 +18,6 @@ ...@@ -18,10 +18,6 @@
* await expect(page.locator('[data-testid="price"]')).toBeVisible() * await expect(page.locator('[data-testid="price"]')).toBeVisible()
* *
* NOTE: This API is dev-mode only. The tests bail out in production mode. * 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 { nextTestSetup } from 'e2e-utils'
...@@ -79,6 +75,13 @@ describe('instant-navigation-testing-api', () => { ...@@ -79,6 +75,13 @@ describe('instant-navigation-testing-api', () => {
try { try {
return await fn() return await fn()
} finally { } finally {
// Wait for the page to be ready before unlocking. This is only necessary
// when fn() triggers a full page navigation (e.g. page.reload() or
// clicking a plain anchor), since the new page needs time to initialize.
await page.waitForFunction(
() =>
typeof (window as any).__EXPERIMENTAL_NEXT_TESTING__ !== 'undefined'
)
await page.evaluate(() => await page.evaluate(() =>
(window as any).__EXPERIMENTAL_NEXT_TESTING__?.navigation.unlock() (window as any).__EXPERIMENTAL_NEXT_TESTING__?.navigation.unlock()
) )
...@@ -184,4 +187,163 @@ describe('instant-navigation-testing-api', () => { ...@@ -184,4 +187,163 @@ describe('instant-navigation-testing-api', () => {
expect(errors.some((e) => e.includes('already acquired'))).toBe(true) expect(errors.some((e) => e.includes('already acquired'))).toBe(true)
}) })
it('renders static shell on page reload', async () => {
const page = await openPage('/target-page')
// Wait for the page to fully load with dynamic content
const dynamicContent = page.locator('[data-testid="dynamic-content"]')
await dynamicContent.waitFor({ state: 'visible' })
await instant(page, async () => {
// Reload the page while in instant mode
await page.reload()
// The loading shell appears, but dynamic content is blocked
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
expect(await dynamicContent.count()).toBe(0)
})
// After exiting the instant scope, dynamic content streams in
await dynamicContent.waitFor({ state: 'visible' })
expect(await dynamicContent.textContent()).toContain(
'Dynamic content loaded'
)
})
it('renders static shell on MPA navigation via plain anchor', async () => {
const page = await openPage('/')
await instant(page, async () => {
// Navigate using a plain anchor (triggers full page load)
await page.click('#plain-link-to-target')
// The loading shell appears, but dynamic content is blocked
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', timeout: 10000 })
expect(await dynamicContent.textContent()).toContain(
'Dynamic content loaded'
)
})
it('reload followed by MPA navigation, both block dynamic data', async () => {
const page = await openPage('/')
await instant(page, async () => {
// Reload the page while in instant mode
await page.reload()
// Home page should be visible (static content)
const homeTitle = page.locator('[data-testid="home-title"]')
await homeTitle.waitFor({ state: 'visible' })
// Navigate via plain anchor (MPA navigation)
await page.click('#plain-link-to-target')
// The loading shell appears, but dynamic content is blocked
const loadingShell = page.locator('[data-testid="loading-shell"]')
await loadingShell.waitFor({ state: 'visible' })
// 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('successive MPA navigations within instant scope', async () => {
const page = await openPage('/')
await instant(page, async () => {
// First MPA navigation: reload
await page.reload()
const homeTitle = page.locator('[data-testid="home-title"]')
await homeTitle.waitFor({ state: 'visible' })
// Second MPA navigation: go to target page
await page.click('#plain-link-to-target')
// Static shell is visible
const loadingShell = page.locator('[data-testid="loading-shell"]')
await loadingShell.waitFor({ state: 'visible' })
// Dynamic content is blocked
const dynamicContent = page.locator('[data-testid="dynamic-content"]')
expect(await dynamicContent.count()).toBe(0)
// Third MPA navigation: go back to home
await page.goBack()
await homeTitle.waitFor({ state: 'visible' })
// Fourth MPA navigation: go to target page again
await page.click('#plain-link-to-target')
// Still shows static shell, dynamic content still blocked
await loadingShell.waitFor({ state: 'visible' })
expect(await dynamicContent.count()).toBe(0)
})
// After exiting 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('subsequent navigations after instant scope are not locked', async () => {
const page = await openPage('/')
// First, do an MPA navigation within an instant scope
await instant(page, async () => {
await page.reload()
const homeTitle = page.locator('[data-testid="home-title"]')
await homeTitle.waitFor({ state: 'visible' })
})
// After exiting the instant scope, navigations work normally again
// Client-side navigation should load dynamic content
await page.click('#link-to-target')
const dynamicContent = page.locator('[data-testid="dynamic-content"]')
await dynamicContent.waitFor({ state: 'visible' })
expect(await dynamicContent.textContent()).toContain(
'Dynamic content loaded'
)
// Navigate back to home
await page.goBack()
const homeTitle = page.locator('[data-testid="home-title"]')
await homeTitle.waitFor({ state: 'visible' })
// Another MPA navigation (reload) should also work normally
await page.goto(page.url().replace(/\/$/, '') + '/target-page')
await dynamicContent.waitFor({ state: 'visible' })
expect(await dynamicContent.textContent()).toContain(
'Dynamic content loaded'
)
})
}) })
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