Unverified Commit 562d3e7f authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

test: add PPF coverage to use-cache and RDC tests (#99417)

We weren't running the use-cache/resume-data-cache test suites in PPF.
some of the tests fail due to the bug that is fixed in #98005 (although
interestingly the fetch-cache tests only fail in deploy mode, because in
`next start` we heal a bad RDC using outputs from
`.next/cache/fetch-cache`). a bunch of refactoring was needed (some
tests were producing false negatives, flakily), so i split this into a
separate PR to confirm behavior before/after the fix.

### `use-cache.test.ts`

- I've refactored the tests to use timestamps and be a bit more
debuggable. previously, they'd fail with a hydration error, and it was
hard to pinpoint the cause. including a name lets us know which cache
was mismatched, and assert that the values of the cache are consistent
across the HTML shell / resume.
- the tests for exluded caches now include more complete assertions on
what content is and isn't included in the HTML shell

### `resume-data-cache.test.ts`

This one needed quite a bit of work:

- The `use cache` and `fetch cache` tests were not independent. they
both used the same page and revalidated the same tag, which means that a
revalidation from the first test affected the outcome of the second
test. i've split them into two separate pages with two separate tags to
make the behavior consistent.
- Multiple tests fetched the same URL (with `fetch(..., { cache:
'force-cache' }`), which made them interfere with each other's fetch
caches. the URLs are now different so the tests are actually independent
- Some cache values are now tagged with a name and timestamp. The name
is used for asserting consistency, the timestamp is for improved
debuggability (provides ordering)
- The action revalidation tests weren't checking what the value from the
build-time prerender was actually supposed to be, so they were passing
even if the build-time RDC was not used at all
- The tests that use `browser()` now assert that there should be no
hydration warning, which can happen due to the PPF bug (due to
inconsistent cache values across HTML shell/resume)
- **the revalidation assertions are very flaky in deploy**, and i've had
to disable them to avoid introducing a test that fails often. i'm not
sure how they were passing before.
parent 8f4e4b64
import { Suspense } from 'react'
import { connection } from 'next/server'
import { fetchRandomWithForceCache } from '../../../utils'
async function DynamicComponent() {
await connection()
return null
}
const KEY = 'test-fetch-cache-initial'
async function getRandomNumber() {
const res = await fetchRandomWithForceCache({
key: KEY,
// no tag - this entry is not meant to be revalidated
tag: undefined,
})
const dateHeader = res.headers.get('date')
const timestamp = dateHeader ? new Date(dateHeader).getTime() : 'time_unknown'
const text = await res.text()
return `fetch-random-${timestamp}-${text}`
}
export default async function Page() {
const randomNumber = await getRandomNumber()
return (
<main>
<p id="random-number">{randomNumber}</p>
<Suspense>
<DynamicComponent />
</Suspense>
</main>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
import { fetchRandomWithForceCache } from '../../../utils'
async function DynamicComponent() {
await connection()
return null
}
const CACHE_TAG = 'test-fetch-cache-revalidation'
async function getRandomNumber() {
const res = await fetchRandomWithForceCache({ tag: CACHE_TAG })
const dateHeader = res.headers.get('date')
const timestamp = dateHeader ? new Date(dateHeader).getTime() : 'time_unknown'
const text = await res.text()
return `fetch-random-${timestamp}-${text}`
}
export default async function Page() {
const randomNumber = await getRandomNumber()
return (
<main>
<p id="random-number">{randomNumber}</p>
<Suspense>
<DynamicComponent />
</Suspense>
</main>
)
}
const { PHASE_PRODUCTION_BUILD } = require('next/constants')
export function getPhase() {
return process.env.NEXT_PHASE === PHASE_PRODUCTION_BUILD
? 'buildtime'
: 'runtime'
}
......@@ -2,11 +2,13 @@ import { Suspense } from 'react'
import { connection } from 'next/server'
import { cacheTag } from 'next/cache'
import { RevalidateButton } from './revalidate-button'
import { tasky } from '../../utils'
async function getCachedRandom() {
'use cache'
cacheTag('revalidate-action-test')
return Math.random()
await tasky()
return `cache-random-${Math.random()}`
}
async function DynamicContent() {
......
import { Suspense } from 'react'
import { connection } from 'next/server'
import { RevalidateButton } from './revalidate-button'
import { fetchRandomWithForceCache } from '../../utils'
async function DynamicContent() {
// Make the page dynamic/PPR by accessing connection()
......@@ -12,10 +13,9 @@ async function DynamicContent() {
export default async function Page() {
// Use fetch with cache and tags
const cachedValue = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{ cache: 'force-cache', next: { tags: ['revalidate-fetch-action-test'] } }
).then((res) => res.text())
const cachedValue = await fetchRandomWithForceCache({
tag: 'revalidate-fetch-action-test',
}).then(async (res) => `fetch-random-${await res.text()}`)
return (
<div>
......
import { revalidateTag } from 'next/cache'
export function POST() {
revalidateTag('test', 'minutes')
export function POST(req: Request) {
const tag = new URL(req.url).searchParams.get('tag')
if (!tag) {
return new Response('Expected "tag" search param to be set', {
status: 400,
})
}
revalidateTag(tag, 'minutes')
return new Response(null, { status: 200 })
}
......@@ -8,7 +8,7 @@ async function getCachedRandomNumber() {
await new Promise((resolve) => setTimeout(resolve, 100))
return Math.random()
return `cache-random-${Math.random()}`
}
async function getUncachedRandomNumber() {
......
import React, { Suspense } from 'react'
import { connection } from 'next/server'
import { getPhase } from '../../next-phase'
import { tasky } from '../../../utils'
async function getRandomNumber() {
'use cache'
// no cacheTag - this cache is not meant to be revalidated
await tasky()
return `cache-random-${getPhase()}-${Date.now()}-${Math.random()}`
}
async function DynamicComponent() {
await connection()
return null
}
export default async function Page() {
const randomNumber = await getRandomNumber()
return (
<main>
<p id="random-number">{randomNumber}</p>
<Suspense>
<DynamicComponent />
</Suspense>
</main>
)
}
......@@ -2,11 +2,16 @@ import React, { Suspense } from 'react'
import { connection } from 'next/server'
import { cacheTag } from 'next/cache'
import { getPhase } from '../../next-phase'
import { tasky } from '../../../utils'
const CACHE_TAG = 'test-use-cache-revalidation'
async function getRandomNumber() {
'use cache'
cacheTag('test')
return Math.random()
cacheTag(CACHE_TAG)
await tasky()
return `cache-random-${getPhase()}-${Date.now()}-${Math.random()}`
}
async function DynamicComponent() {
......@@ -16,17 +21,12 @@ async function DynamicComponent() {
export default async function Page() {
const randomNumber = await getRandomNumber()
const anotherRandomNumber = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{ cache: 'force-cache', next: { tags: ['test'] } }
).then((res) => res.text())
return (
<>
<main>
<p id="random-number">{randomNumber}</p>
<p id="another-random-number">{anotherRandomNumber}</p>
<Suspense>
<DynamicComponent />
</Suspense>
</>
</main>
)
}
process.env.__NEXT_PARTIAL_PREFETCHING = 'true'
require('./resume-data-cache.test')
export async function tasky() {
// make cache-misses noticeable
await new Promise((resolve) => setTimeout(resolve))
}
/**
* A wrapper meant to ensure fetches with independent tags are cached separately
* so that tests don't interfere with each others' fetch caches.
* */
export async function fetchRandomWithForceCache(
opts: { tag: string } | { key: string; tag: undefined }
) {
let key: string
let tag: string | undefined
if ('key' in opts) {
key = opts.key
tag = undefined
} else {
key = tag = opts.tag
}
return fetch(
`https://next-data-api-endpoint.vercel.app/api/random?key=${encodeURIComponent(key)}`,
{ cache: 'force-cache', next: { tags: tag !== undefined ? [tag] : [] } }
)
}
import { cacheLife } from 'next/cache'
import { Suspense } from 'react'
import { tasky } from '../../../utils'
async function getCachedRandom() {
async function getCachedNow() {
'use cache'
// Long-lived (stale >= MIN_PREFETCHABLE_STALE, expire >=
// MIN_PRERENDERABLE_EXPIRE): stays in the static shell.
cacheLife({ stale: 60, revalidate: 100, expire: 1000 })
return Math.random()
await tasky()
return `prerenderable: ${Date.now()}`
}
async function ShortStaleCache() {
async function NonPrefetchableCache() {
'use cache'
// Long expire (>= MIN_PRERENDERABLE_EXPIRE, 5min) and a non-zero revalidate,
// but a stale time below MIN_PREFETCHABLE_STALE (30s). This isolates the
......@@ -17,18 +20,17 @@ async function ShortStaleCache() {
// because of its short stale time, not because of a short expire or
// revalidate: 0.
cacheLife({ stale: 18, revalidate: 100, expire: 1000 })
return <p id="y">{new Date().toISOString()}</p>
return <p id="non-prefetchable">{`non-prefetchable: ${Date.now()}`}</p>
}
export default async function Page() {
const x = await getCachedRandom()
const cachedNow = await getCachedNow()
return (
<>
<p id="x">{x}</p>
<Suspense fallback={<p id="y">Loading...</p>}>
<ShortStaleCache />
<main>
<p id="prerenderable">{cachedNow}</p>
<Suspense fallback={<p id="non-prefetchable">Loading...</p>}>
<NonPrefetchableCache />
</Suspense>
</>
</main>
)
}
import { cacheLife } from 'next/cache'
import { connection } from 'next/server'
import { Suspense } from 'react'
import { tasky } from '../../../utils'
async function getCachedRandom() {
async function getCachedNow() {
'use cache'
// prerenderable and prefetchable.
cacheLife('frequent')
return Math.random()
await tasky()
return `prerenderable: ${Date.now()}`
}
async function DynamicCache() {
async function NonPrerenderableCache() {
'use cache'
cacheLife({ revalidate: 99, expire: 299, stale: 18 })
return <p id="y">{new Date().toISOString()}</p>
// Not prerenderable and not prefetchable.
cacheLife({
revalidate: 99,
expire: 299, // < MIN_PRERENDERABLE_EXPIRE
stale: 18, // < MIN_PREFETCHABLE_STALE
})
return <p id="non-prerenderable">{`non-prerenderable: ${Date.now()}`}</p>
}
async function Dynamic() {
......@@ -20,17 +29,16 @@ async function Dynamic() {
}
export default async function Page() {
const x = await getCachedRandom()
const cachedNow = await getCachedNow()
return (
<>
<p id="x">{x}</p>
<Suspense fallback={<p id="y">Loading...</p>}>
<DynamicCache />
<main>
<p id="prerenderable">{cachedNow}</p>
<Suspense fallback={<p id="non-prerenderable">Loading...</p>}>
<NonPrerenderableCache />
</Suspense>
<Suspense>
<Dynamic />
</Suspense>
</>
</main>
)
}
import { connection } from 'next/server'
import { cacheLife } from 'next/cache'
import { Suspense } from 'react'
import { tasky } from '../../../utils'
async function revalidateZero() {
'use cache: remote'
cacheLife({ revalidate: 0 })
return new Date().toISOString()
await tasky()
return Date.now()
}
async function lowExpire() {
'use cache: remote'
cacheLife({ expire: 5 })
return new Date().toISOString()
await tasky()
return Date.now()
}
async function OuterCacheNoExplicit() {
'use cache: remote'
// No explicit cacheLife - this would error during prerendering, but is
// allowed at request time (after connection()).
await tasky()
return (
<>
<p>
<code>revalidate=0</code>:{' '}
<span id="revalidate-zero">{await revalidateZero()}</span>
<span id="revalidate-zero">{`bare-revalidate-zero: ${await revalidateZero()}`}</span>
</p>
<p>
<code>expire=5</code>: <span id="low-expire">{await lowExpire()}</span>
<code>expire=5</code>:{' '}
<span id="low-expire">{`bare-low-expire: ${await lowExpire()}`}</span>
</p>
</>
)
......@@ -38,16 +42,16 @@ async function OuterCacheExplicitShort() {
'use cache: remote'
// Explicit short cacheLife - excluded from prerender, becomes a dynamic hole.
cacheLife({ revalidate: 0, expire: 5 })
await tasky()
return (
<>
<p>
Explicit <code>revalidate=0</code>:{' '}
<span id="explicit-revalidate-zero">{await revalidateZero()}</span>
<span id="explicit-revalidate-zero">{`explicit-revalidate-zero: ${await revalidateZero()}`}</span>
</p>
<p>
Explicit <code>expire=5</code>:{' '}
<span id="explicit-low-expire">{await lowExpire()}</span>
<span id="explicit-low-expire">{`explicit-low-expire: ${await lowExpire()}`}</span>
</p>
</>
)
......@@ -58,16 +62,16 @@ async function OuterCacheExplicitLong() {
// Explicit long cacheLife - included in prerender despite short-lived inner
// caches.
cacheLife('default')
await tasky()
return (
<>
<p>
Explicit long (<code>revalidate=0</code> inner):{' '}
<span id="explicit-long-revalidate-zero">{await revalidateZero()}</span>
<span id="explicit-long-revalidate-zero">{`explicit-long-revalidate-zero: ${await revalidateZero()}`}</span>
</p>
<p>
Explicit long (<code>expire=5</code> inner):{' '}
<span id="explicit-long-low-expire">{await lowExpire()}</span>
<span id="explicit-long-low-expire">{`explicit-long-low-expire: ${await lowExpire()}`}</span>
</p>
</>
)
......@@ -81,7 +85,7 @@ async function Dynamic() {
export default async function Page() {
return (
<>
<main>
<p id="static">Static content</p>
<Suspense fallback={<p id="dynamic">Loading...</p>}>
<Dynamic />
......@@ -90,6 +94,6 @@ export default async function Page() {
<OuterCacheExplicitShort />
</Suspense>
<OuterCacheExplicitLong />
</>
</main>
)
}
process.env.__NEXT_CACHE_COMPONENTS = 'true'
process.env.__NEXT_PARTIAL_PREFETCHING = 'true'
require('./use-cache.test')
export async function tasky() {
// make cache-misses noticeable
await new Promise((resolve) => setTimeout(resolve))
}
......@@ -176,6 +176,10 @@ export const conditions: Record<string, Condition> = {
'Cache Components are enabled for the fixture',
(config) => config.cacheComponents
),
partialPrefetchingGlobal: lazyCondition(
'Partial Prefetching is enabled globally for the fixture (does not check `export const prefetch = "partial"`)',
(config) => config.partialPrefetching
),
ppr: lazyCondition(
'partial prerendering is enabled (implied by `cacheComponents`)',
(config) => config.experimental?.ppr
......
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