Commit 50cbb16b authored by Janka Uryga's avatar Janka Uryga

tests

parent b2614f26
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { retry } from 'next-test-utils'
import * as nodePath from 'node:path'
import type { Playwright } from '../../../lib/next-webdriver' import type { Playwright } from '../../../lib/next-webdriver'
describe('cache-components-dev-warmup', () => { describe.each([
{
description: 'without runtime prefetch configs',
hasRuntimePrefetch: false,
fixturePath: 'fixtures/without-prefetch-config',
},
{
description: 'with runtime prefetch configs',
hasRuntimePrefetch: true,
fixturePath: 'fixtures/with-prefetch-config',
},
])(
'cache-components-dev-warmup - $description',
({ fixturePath, hasRuntimePrefetch }) => {
const { next, isTurbopack } = nextTestSetup({ const { next, isTurbopack } = nextTestSetup({
files: __dirname, files: nodePath.join(__dirname, fixturePath),
}) })
// Restart the dev server for each test to clear the in-memory cache. // Restart the dev server for each test to clear the in-memory cache.
...@@ -64,10 +78,19 @@ describe('cache-components-dev-warmup', () => { ...@@ -64,10 +78,19 @@ describe('cache-components-dev-warmup', () => {
// Initial load. // Initial load.
await retry(() => assertLogs(browser)) await retry(() => assertLogs(browser))
// We should not see any errors related to the aborted render.
expect(next.cliOutput).not.toContain(
'AbortError: This operation was aborted'
)
// After another load (with warm caches) the logs should be the same. // After another load (with warm caches) the logs should be the same.
await browser.loadPage(next.url + path) // clears old logs await browser.loadPage(next.url + path) // clears old logs
await retry(() => assertLogs(browser)) await retry(() => assertLogs(browser))
expect(next.cliOutput).not.toContain(
'AbortError: This operation was aborted'
)
if (isTurbopack) { if (isTurbopack) {
// FIXME: // FIXME:
// In Turbopack, requests to the /revalidate route seem to occasionally crash // In Turbopack, requests to the /revalidate route seem to occasionally crash
...@@ -88,6 +111,11 @@ describe('cache-components-dev-warmup', () => { ...@@ -88,6 +111,11 @@ describe('cache-components-dev-warmup', () => {
await browser.loadPage(next.url + path) // clears old logs await browser.loadPage(next.url + path) // clears old logs
await retry(() => assertLogs(browser)) await retry(() => assertLogs(browser))
// We should not see any errors related to the aborted render.
expect(next.cliOutput).not.toContain(
'AbortError: This operation was aborted'
)
} }
async function testNavigation( async function testNavigation(
...@@ -100,11 +128,20 @@ describe('cache-components-dev-warmup', () => { ...@@ -100,11 +128,20 @@ describe('cache-components-dev-warmup', () => {
await browser.elementByCss(`a[href="${path}"]`).click() await browser.elementByCss(`a[href="${path}"]`).click()
await retry(() => assertLogs(browser)) await retry(() => assertLogs(browser))
// We should not see any errors related to the aborted render.
expect(next.cliOutput).not.toContain(
'AbortError: This operation was aborted'
)
// Reload, and perform another nav (with warm caches). the logs should be the same. // Reload, and perform another nav (with warm caches). the logs should be the same.
await browser.loadPage(next.url + '/') // clears old logs await browser.loadPage(next.url + '/') // clears old logs
await browser.elementByCss(`a[href="${path}"]`).click() await browser.elementByCss(`a[href="${path}"]`).click()
await retry(() => assertLogs(browser)) await retry(() => assertLogs(browser))
expect(next.cliOutput).not.toContain(
'AbortError: This operation was aborted'
)
if (isTurbopack) { if (isTurbopack) {
// FIXME: // FIXME:
// In Turbopack, requests to the /revalidate route seem to occasionally crash // In Turbopack, requests to the /revalidate route seem to occasionally crash
...@@ -126,6 +163,10 @@ describe('cache-components-dev-warmup', () => { ...@@ -126,6 +163,10 @@ describe('cache-components-dev-warmup', () => {
await browser.loadPage(next.url + '/') // clears old logs await browser.loadPage(next.url + '/') // clears old logs
await browser.elementByCss(`a[href="${path}"]`).click() await browser.elementByCss(`a[href="${path}"]`).click()
await retry(() => assertLogs(browser)) await retry(() => assertLogs(browser))
expect(next.cliOutput).not.toContain(
'AbortError: This operation was aborted'
)
} }
async function revalidatePath(path: string) { async function revalidatePath(path: string) {
...@@ -139,6 +180,8 @@ describe('cache-components-dev-warmup', () => { ...@@ -139,6 +180,8 @@ describe('cache-components-dev-warmup', () => {
} }
} }
const RUNTIME_ENV = hasRuntimePrefetch ? 'Prefetch' : 'Prefetchable'
describe.each([ describe.each([
{ description: 'initial load', isInitialLoad: true }, { description: 'initial load', isInitialLoad: true },
{ description: 'navigation', isInitialLoad: false }, { description: 'navigation', isInitialLoad: false },
...@@ -175,12 +218,12 @@ describe('cache-components-dev-warmup', () => { ...@@ -175,12 +218,12 @@ describe('cache-components-dev-warmup', () => {
// Private caches are dynamic holes in static prerenders, // Private caches are dynamic holes in static prerenders,
// so they shouldn't resolve in the static stage. // so they shouldn't resolve in the static stage.
assertLog(logs, 'after private cache read - page', 'Prefetchable') assertLog(logs, 'after private cache read - page', RUNTIME_ENV)
assertLog(logs, 'after private cache read - layout', 'Prefetchable') assertLog(logs, 'after private cache read - layout', RUNTIME_ENV)
assertLog( assertLog(
logs, logs,
'after successive private cache reads - page', 'after successive private cache reads - page',
'Prefetchable' RUNTIME_ENV
) )
assertLog(logs, 'after uncached fetch - layout', 'Server') assertLog(logs, 'after uncached fetch - layout', 'Server')
...@@ -204,11 +247,11 @@ describe('cache-components-dev-warmup', () => { ...@@ -204,11 +247,11 @@ describe('cache-components-dev-warmup', () => {
// Short lived caches are dynamic holes in static prerenders, // Short lived caches are dynamic holes in static prerenders,
// so they shouldn't resolve in the static stage. // so they shouldn't resolve in the static stage.
assertLog(logs, 'after short-lived cache read - page', 'Prefetchable') assertLog(logs, 'after short-lived cache read - page', RUNTIME_ENV)
assertLog( assertLog(
logs, logs,
'after short-lived cache read - layout', 'after short-lived cache read - layout',
'Prefetchable' RUNTIME_ENV
) )
assertLog(logs, 'after uncached fetch - layout', 'Server') assertLog(logs, 'after uncached fetch - layout', 'Server')
...@@ -251,10 +294,10 @@ describe('cache-components-dev-warmup', () => { ...@@ -251,10 +294,10 @@ describe('cache-components-dev-warmup', () => {
assertLog(logs, 'after cache read - page', 'Prerender') assertLog(logs, 'after cache read - page', 'Prerender')
// TODO: we should only label this as "Prefetch" if there's a prefetch config. // TODO: we should only label this as "Prefetch" if there's a prefetch config.
assertLog(logs, `after cookies`, 'Prefetchable') assertLog(logs, `after cookies`, RUNTIME_ENV)
assertLog(logs, `after headers`, 'Prefetchable') assertLog(logs, `after headers`, RUNTIME_ENV)
assertLog(logs, `after params`, 'Prefetchable') assertLog(logs, `after params`, RUNTIME_ENV)
assertLog(logs, `after searchParams`, 'Prefetchable') assertLog(logs, `after searchParams`, RUNTIME_ENV)
assertLog(logs, 'after connection', 'Server') assertLog(logs, 'after connection', 'Server')
} }
...@@ -266,4 +309,5 @@ describe('cache-components-dev-warmup', () => { ...@@ -266,4 +309,5 @@ describe('cache-components-dev-warmup', () => {
} }
}) })
}) })
}) }
)
import { cookies, headers } from 'next/headers'
import { CachedData } from '../../data-fetching'
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_prefetch = { mode: 'runtime', samples: [{}] }
const CACHE_KEY = __dirname + '/__PAGE__'
export default function Page({ params, searchParams }) {
return (
<main>
<p>
This page checks whether runtime/dynamic APIs resolve in the correct
stage (regardless of whether we had a cache miss or not)
</p>
<CachedData cacheKey={CACHE_KEY} label="page" />
<LogAfter label="--- dynamic stage ---" api={() => connection()} />
{/* Runtime */}
<LogAfter label="cookies" api={() => cookies()} />
<LogAfter label="headers" api={() => headers()} />
<LogAfter label="params" api={() => params} />
<LogAfter label="searchParams" api={() => searchParams} />
{/* Dynamic */}
<LogAfter label="connection" api={() => connection()} />
</main>
)
}
function LogAfter({ label, api }: { label: string; api: () => Promise<any> }) {
return (
<Suspense fallback={<div>Waiting for {label}...</div>}>
<LogAfterInner label={label} api={api} />
</Suspense>
)
}
async function LogAfterInner({
label,
api,
}: {
label: string
api: () => Promise<any>
}) {
await api()
console.log(`after ${label}`)
return <div>Finished {label}</div>
}
import { Suspense } from 'react'
import { UncachedFetch, CachedData } from '../data-fetching'
import { PrivateCachedData } from './data-fetching'
export const unstable_prefetch = { mode: 'runtime', samples: [{}] }
const CACHE_KEY = '/private-cache/__LAYOUT__'
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<>
{children}
<section>
<h1>Layout</h1>
<p>This data is from a layout</p>
<CachedData label="layout" cacheKey={CACHE_KEY} />
<Suspense fallback="Loading private cache...">
<PrivateCachedData label="layout" cacheKey={CACHE_KEY} />
</Suspense>
<Suspense fallback="Loading uncached fetch...">
<UncachedFetch label="layout" cacheKey={CACHE_KEY} />
</Suspense>
</section>
</>
)
}
import { Suspense } from 'react'
import { UncachedFetch, CachedData } from '../data-fetching'
import { ShortLivedCache } from './data-fetching'
export const unstable_prefetch = { mode: 'runtime', samples: [{}] }
const CACHE_KEY = __dirname + '/__LAYOUT__'
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<>
{children}
<section>
<h1>Layout</h1>
<p>This data is from a layout</p>
<CachedData label="layout" cacheKey={CACHE_KEY} />
<Suspense fallback="Loading short-lived cache...">
<ShortLivedCache label="layout" cacheKey={CACHE_KEY} />
</Suspense>
<Suspense fallback="Loading uncached fetch...">
<UncachedFetch label="layout" cacheKey={CACHE_KEY} />
</Suspense>
</section>
</>
)
}
import { Suspense } from 'react'
import { UncachedFetch, CachedFetch, CachedData } from '../data-fetching'
export const unstable_prefetch = { mode: 'runtime', samples: [{}] }
const CACHE_KEY = __dirname + '/__LAYOUT__'
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<>
{children}
<section>
<h1>Layout</h1>
<p>This data is from a layout</p>
<CachedData label="layout" cacheKey={CACHE_KEY} />
<CachedFetch label="layout" cacheKey={CACHE_KEY} />
<Suspense fallback="Loading uncached fetch...">
<UncachedFetch label="layout" cacheKey={CACHE_KEY} />
</Suspense>
</section>
</>
)
}
export const unstable_prefetch = { mode: 'runtime', samples: [{}] }
export default async function Page() {
return (
<main>
<h1>Warmup Dev Renders - deep successive cache reads</h1>
<One />
</main>
)
}
async function One() {
const cache1 = await fastCache()
console.log('after cache 1')
return <Two cache1={cache1} />
}
async function Two({ cache1 }) {
const cache2 = await slowCache(1)
console.log('after cache 2')
return <Three cache1={cache1} cache2={cache2} />
}
async function Three({ cache1, cache2 }) {
console.log('after caches 1 and 2')
const cache3 = await slowCache(2)
console.log('after cache 3')
return (
<div>
<div>Cache 1: {cache1}</div>
<div>Cache 2: {cache2}</div>
<div>Cache 3: {cache3}</div>
</div>
)
}
async function fastCache() {
'use cache'
return Math.random()
}
async function slowCache(_key: number) {
'use cache'
await new Promise((resolve) => setTimeout(resolve))
return Math.random()
}
export async function fetchCachedRandom(cacheKey: string) {
return fetchCached(
`https://next-data-api-endpoint.vercel.app/api/random?key=${encodeURIComponent('cached-' + cacheKey)}`
)
}
export async function fetchCached(url: string) {
const response = await fetch(url, { cache: 'force-cache' })
return response.text()
}
export async function getCachedData(_key: string) {
'use cache'
await new Promise((r) => setTimeout(r))
return Math.random()
}
export async function CachedData({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
const data = await getCachedData(cacheKey)
console.log(`after cache read - ${label}`)
return (
<dl>
<dt>Cached Data</dt>
<dd>{data}</dd>
</dl>
)
}
export async function SuccessiveCachedData({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
// This components tests if we correctly handle the case where resolving a cache
// reveals another cache in the children. When we're filling caches, we should fill both.
const data1 = await getCachedData(`${cacheKey}-successive-1`)
return (
<dl>
<dt>Cached Data (successive reads)</dt>
<dd>{data1}</dd>
<dd>
<SuccessiveCachedDataChild label={label} cacheKey={cacheKey} />
</dd>
</dl>
)
}
async function SuccessiveCachedDataChild({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
const data2 = await getCachedData(`${cacheKey}-successive-2`)
console.log(`after successive cache reads - ${label}`)
return <>{data2}</>
}
export async function CachedFetch({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
const data = await fetchCachedRandom(cacheKey)
console.log(`after cached fetch - ${label}`)
return (
<dl>
<dt>Cached Fetch</dt>
<dd>{data}</dd>
</dl>
)
}
export async function UncachedFetch({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
const response = await fetch(
`https://next-data-api-endpoint.vercel.app/api/random?key=${encodeURIComponent('uncached-' + cacheKey)}`
)
console.log(`after uncached fetch - ${label}`)
const data = await response.text()
return (
<dl>
<dt>Uncached Fetch</dt>
<dd>{data}</dd>
</dl>
)
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function Page() {
// NOTE: these links must be kept in sync with `path` variables used in the test
return (
<main>
<ul>
<li>
<Link href="/simple">/simple</Link>
</li>
<li>
<Link href="/private-cache">/private-cache</Link>
</li>
<li>
<Link href="/short-lived-cache">/short-lived-cache</Link>
</li>
<li>
<Link href="/successive-caches">/successive-caches</Link>
</li>
<li>
<Link href="/apis/123">/apis/123</Link>
</li>
</ul>
</main>
)
}
export async function PrivateCachedData({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
const data = await getPrivateCachedData(cacheKey)
console.log(`after private cache read - ${label}`)
return (
<dl>
<dt>Private Cached Data (Page)</dt>
<dd>{data}</dd>
</dl>
)
}
export async function SuccessivePrivateCachedData({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
// This components tests if we correctly handle the case where resolving a cache
// reveals another cache in the children. When we're filling caches, we should fill both.
const data1 = await getPrivateCachedData(`${cacheKey}-successive-1`)
return (
<dl>
<dt>Private Cached Data (successive reads)</dt>
<dd>{data1}</dd>
<dd>
<SuccessivePrivateCachedDataChild label={label} cacheKey={cacheKey} />
</dd>
</dl>
)
}
async function SuccessivePrivateCachedDataChild({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
const data2 = await getPrivateCachedData(`${cacheKey}-successive-2`)
console.log(`after successive private cache reads - ${label}`)
return <>{data2}</>
}
async function getPrivateCachedData(_key: string) {
'use cache: private'
await new Promise((r) => setTimeout(r))
return Math.random()
}
import { Suspense } from 'react'
import { CachedData, UncachedFetch } from '../data-fetching'
import { PrivateCachedData, SuccessivePrivateCachedData } from './data-fetching'
const CACHE_KEY = '/private-cache/__PAGE__'
export default async function Page() {
return (
<main>
<h1>Warmup Dev Renders - private cache</h1>
<CachedData label="page" cacheKey={CACHE_KEY} />
<Suspense fallback="Loading private cache...">
<PrivateCachedData label="page" cacheKey={CACHE_KEY} />
</Suspense>
<Suspense fallback="Loading two successive private caches...">
<SuccessivePrivateCachedData label="page" cacheKey={CACHE_KEY} />
</Suspense>
<Suspense fallback="Loading uncached fetch...">
<UncachedFetch label="page" cacheKey={CACHE_KEY} />
</Suspense>
</main>
)
}
import { revalidatePath } from 'next/cache'
export async function GET(request: Request) {
const path = new URL(request.url).searchParams.get('path')!
revalidatePath(path)
return Response.json({ revalidated: true })
}
import { cacheLife } from 'next/cache'
export async function ShortLivedCache({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
const data = await getShortLivedCachedData(cacheKey)
console.log(`after short-lived cache read - ${label}`)
return (
<dl>
<dt>Short-lived Cached Data (Page)</dt>
<dd>{data}</dd>
</dl>
)
}
async function getShortLivedCachedData(_key: string) {
'use cache'
cacheLife('seconds')
await new Promise((r) => setTimeout(r))
return Math.random()
}
import { Suspense } from 'react'
import { CachedData, UncachedFetch } from '../data-fetching'
import { ShortLivedCache } from './data-fetching'
const CACHE_KEY = __dirname + '/__PAGE__'
export default async function Page() {
return (
<main>
<h1>Warmup Dev Renders - short lived cache</h1>
<CachedData label="page" cacheKey={CACHE_KEY} />
<Suspense fallback="Loading short-lived cache...">
<ShortLivedCache label="page" cacheKey={CACHE_KEY} />
</Suspense>
<Suspense fallback="Loading uncached fetch...">
<UncachedFetch label="page" cacheKey={CACHE_KEY} />
</Suspense>
</main>
)
}
import { fetchCachedRandom, getCachedData } from '../data-fetching'
// Deliberately using the same cache keys as the page.
const CACHE_KEY = __dirname + '/__PAGE__'
export default async function Loading() {
await fetchCachedRandom(CACHE_KEY) // Mirrors `CachedFetchingComponent`
await getCachedData(CACHE_KEY) // Mirrors `CachedDataComponent`
return <main>loading...</main>
}
import { Suspense } from 'react'
import {
CachedData,
CachedFetch,
SuccessiveCachedData,
UncachedFetch,
} from '../data-fetching'
const CACHE_KEY = __dirname + '/__PAGE__'
export default async function Page() {
return (
<main>
<h1>Warmup Dev Renders</h1>
<CachedData label="page" cacheKey={CACHE_KEY} />
<SuccessiveCachedData label="page" cacheKey={CACHE_KEY} />
<CachedFetch label="page" cacheKey={CACHE_KEY} />
<Suspense fallback="Loading uncached fetch...">
<UncachedFetch label="page" cacheKey={CACHE_KEY} />
</Suspense>
</main>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
cacheComponents: true,
},
}
export default 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