(
page: PlaywrightPage,
fn: () => Promise<T>,
options?: { baseURL?: string }
)
| 53 | * as labeled steps in the Playwright UI. |
| 54 | */ |
| 55 | export async function instant<T>( |
| 56 | page: PlaywrightPage, |
| 57 | fn: () => Promise<T>, |
| 58 | options?: { baseURL?: string } |
| 59 | ): Promise<T> { |
| 60 | // Check for nested instant() calls. The cookie is scoped to the browser |
| 61 | // context, so we can detect nesting by checking if it's already set. |
| 62 | const existingCookies = await page.context().cookies() |
| 63 | if (existingCookies.some((c) => c.name === INSTANT_COOKIE)) { |
| 64 | throw new Error( |
| 65 | 'An instant() scope is already active. Nesting instant() ' + |
| 66 | 'calls is not supported. Did you forget to await the ' + |
| 67 | 'previous instant() call?' |
| 68 | ) |
| 69 | } |
| 70 | |
| 71 | // Acquire the lock by setting the cookie via the browser context. This |
| 72 | // ensures the cookie is present even on the very first navigation. |
| 73 | // The cookie triggers the CookieStore change event in |
| 74 | // navigation-testing-lock.ts, which acquires the in-memory navigation lock. |
| 75 | const { hostname } = new URL(resolveURL(page, options)) |
| 76 | await step('Acquire Instant Lock', () => |
| 77 | page.context().addCookies([ |
| 78 | { |
| 79 | name: INSTANT_COOKIE, |
| 80 | value: JSON.stringify([0, `p${Math.random()}`]), |
| 81 | domain: hostname, |
| 82 | path: '/', |
| 83 | }, |
| 84 | ]) |
| 85 | ) |
| 86 | try { |
| 87 | return await fn() |
| 88 | } finally { |
| 89 | // Release the lock by clearing the cookie. Next.js may have updated the |
| 90 | // cookie value (e.g. from [0] to [1,null]) during the lock scope. We |
| 91 | // clear by name to remove the cookie regardless of its current value or |
| 92 | // which domain variant it was stored under. |
| 93 | await step('Release Instant Lock', () => |
| 94 | page.context().clearCookies({ name: INSTANT_COOKIE }) |
| 95 | ) |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | /** |
| 100 | * Resolves the URL to scope the instant navigation cookie to. Prefers |
no test coverage detected
searching dependent graphs…