Unverified Commit af74b4a3 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Include `use-cache` test suite in the Cache Components tests (#81610)

We're splitting the test app routes between two root layouts, one for (partially) static pages that does not wrap its children in a Suspense boundary, and one for dynamic pages that adds a Suspense boundary above `body`, which opts those pages into fully dynamic rendering.

Two tests are expected to fail for now, because they revealed bugs related to revalidation, which will be fixed in follow-up PRs:
- https://github.com/vercel/next.js/pull/81611
- https://github.com/vercel/next.js/pull/81621

closes NAR-171
parent d8fdb6ff
...@@ -27,6 +27,12 @@ ...@@ -27,6 +27,12 @@
"searchparams-reuse-loading should re-use loading from \"full\" prefetch for param-less URL when navigating to param-full route" "searchparams-reuse-loading should re-use loading from \"full\" prefetch for param-less URL when navigating to param-full route"
] ]
}, },
"test/e2e/app-dir/use-cache/use-cache.test.ts": {
"failed": [
"use-cache should revalidate before redirecting in a route handler",
"use-cache should update after unstable_expireTag correctly"
]
},
"test/production/app-dir/browser-chunks/browser-chunks.test.ts": { "test/production/app-dir/browser-chunks/browser-chunks.test.ts": {
"failed": [ "failed": [
"browser-chunks must not bundle any server modules into browser chunks" "browser-chunks must not bundle any server modules into browser chunks"
...@@ -278,7 +284,6 @@ ...@@ -278,7 +284,6 @@
"test/e2e/app-dir/use-cache-segment-configs/use-cache-segment-configs.test.ts", "test/e2e/app-dir/use-cache-segment-configs/use-cache-segment-configs.test.ts",
"test/e2e/app-dir/use-cache-standalone-search-params/use-cache-standalone-search-params.test.ts", "test/e2e/app-dir/use-cache-standalone-search-params/use-cache-standalone-search-params.test.ts",
"test/e2e/app-dir/use-cache-without-experimental-flag/use-cache-without-experimental-flag.test.ts", "test/e2e/app-dir/use-cache-without-experimental-flag/use-cache-without-experimental-flag.test.ts",
"test/e2e/app-dir/use-cache/use-cache.test.ts",
"test/e2e/app-dir/use-params/use-params.test.ts", "test/e2e/app-dir/use-params/use-params.test.ts",
"test/e2e/app-dir/use-selected-layout-segment-s/use-selected-layout-segment-s.test.ts", "test/e2e/app-dir/use-selected-layout-segment-s/use-selected-layout-segment-s.test.ts",
"test/e2e/app-dir/use-server-inserted-html/use-server-inserted-html.test.ts", "test/e2e/app-dir/use-server-inserted-html/use-server-inserted-html.test.ts",
......
import { Suspense } from 'react'
export default function Root({ children }: { children: React.ReactNode }) {
return (
<Suspense>
<html>
<body>{children}</body>
</html>
</Suspense>
)
}
import { Foo } from './client' import { Foo } from '../client'
async function getCachedRandom(x: number, children: React.ReactNode) { async function getCachedRandom(x: number, children: React.ReactNode) {
'use cache' 'use cache'
......
...@@ -12,7 +12,7 @@ export default async function Page() { ...@@ -12,7 +12,7 @@ export default async function Page() {
return ( return (
<form action={refresh}> <form action={refresh}>
<button id="refresh">Refresh</button> <button id="refresh">Refresh</button>
<p id="t">{Date.now()}</p> <p id="t">{new Date().toISOString()}</p>
</form> </form>
) )
} }
'use client' 'use client'
import { foo, bar, baz } from './cached' import { foo, bar, baz } from './cached'
import { Form } from '../form' import { Form } from '../../form'
export default function Page() { export function ClientComponent() {
return <Form foo={foo} bar={bar} baz={baz} /> return <Form foo={foo} bar={bar} baz={baz} />
} }
import { ClientComponent } from './client-component'
export default function Page() {
return <ClientComponent />
}
import { Form } from '../form' import { Form } from '../../form'
function getRandomValue() { function getRandomValue() {
const v = Math.random() const v = Math.random()
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
import { useActionState } from 'react' import { useActionState } from 'react'
import { getRandomValue } from './cached' import { getRandomValue } from './cached'
export default function Page() { export function Form() {
const [result, formAction, isPending] = useActionState(getRandomValue, -1) const [result, formAction, isPending] = useActionState(getRandomValue, -1)
return ( return (
......
import { Form } from './form'
export default function Page() {
return <Form />
}
...@@ -8,7 +8,7 @@ const nextConfig = { ...@@ -8,7 +8,7 @@ const nextConfig = {
frequent: { frequent: {
stale: 19, stale: 19,
revalidate: 100, revalidate: 100,
expire: 250, expire: 300,
}, },
}, },
cacheHandlers: { cacheHandlers: {
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry, waitFor } from 'next-test-utils' import { retry } from 'next-test-utils'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
import { format } from 'util' import { format } from 'util'
import { Playwright } from 'next-webdriver' import { Playwright } from 'next-webdriver'
...@@ -172,7 +172,7 @@ describe('use-cache', () => { ...@@ -172,7 +172,7 @@ describe('use-cache', () => {
expect(rand1).toEqual(rand2) expect(rand1).toEqual(rand2)
}) })
it('should revalidate before redirecting in a route handlers', async () => { it('should revalidate before redirecting in a route handler', async () => {
const initialValues = await next.fetch('/api').then((res) => res.json()) const initialValues = await next.fetch('/api').then((res) => res.json())
const values = await next const values = await next
...@@ -473,14 +473,24 @@ describe('use-cache', () => { ...@@ -473,14 +473,24 @@ describe('use-cache', () => {
it('should prerender fully cacheable pages as static HTML', async () => { it('should prerender fully cacheable pages as static HTML', async () => {
const prerenderManifest = JSON.parse( const prerenderManifest = JSON.parse(
await next.readFile('.next/prerender-manifest.json') await next.readFile('.next/prerender-manifest.json')
) ) as PrerenderManifest
let prerenderedRoutes = Object.keys(prerenderManifest.routes).sort() const withPPR = process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
if (process.env.__NEXT_EXPERIMENTAL_PPR === 'true') { const withCacheComponents =
process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS === 'true'
let prerenderedRoutes = Object.entries(prerenderManifest.routes)
if (withPPR || withCacheComponents) {
// For the purpose of this test we don't consider an incomplete shell. // For the purpose of this test we don't consider an incomplete shell.
prerenderedRoutes = prerenderedRoutes.filter((route) => { prerenderedRoutes = prerenderedRoutes.filter(([pathname, route]) => {
const filename = route.replace(/^\//, '').replace(/^$/, 'index') const filename = pathname.replace(/^\//, '').replace(/^$/, 'index')
// A prerendered route handler does not have a dataRoute (i.e. RSC).
if (!route.dataRoute) {
return true
}
return next return next
.readFileSync(`.next/server/app/${filename}.html`) .readFileSync(`.next/server/app/${filename}.html`)
...@@ -488,34 +498,42 @@ describe('use-cache', () => { ...@@ -488,34 +498,42 @@ describe('use-cache', () => {
}) })
} }
expect(prerenderedRoutes).toEqual([ const prerenderedRouteKeys = prerenderedRoutes
// [id] route, first entry in generateStaticParams .map(([routeKey]) => routeKey)
expect.stringMatching(/\/a\d/), .sort()
// [id] route, second entry in generateStaticParams
expect.stringMatching(/\/b\d/), expect(prerenderedRouteKeys).toEqual(
'/cache-fetch', [
'/cache-fetch-no-store', // [id] route, first entry in generateStaticParams
'/cache-life', expect.stringMatching(/\/a\d/),
'/cache-tag', withCacheComponents && '/api',
'/directive-in-node-modules/with-handler', // [id] route, second entry in generateStaticParams
'/directive-in-node-modules/without-handler', expect.stringMatching(/\/b\d/),
'/draft-mode', '/cache-fetch',
'/form', '/cache-fetch-no-store',
'/imported-from-client', '/cache-life',
'/logs', '/cache-tag',
'/method-props', '/directive-in-node-modules/with-handler',
'/nested-in-unstable-cache', '/directive-in-node-modules/without-handler',
'/not-found', '/draft-mode',
'/on-demand-revalidate', '/form',
'/passed-to-client', '/imported-from-client',
'/react-cache', '/logs',
'/referential-equality', '/method-props',
'/revalidate-and-redirect/redirect', '/nested-in-unstable-cache',
'/rsc-payload', '/not-found',
'/static-class-method', '/on-demand-revalidate',
'/use-action-state', '/passed-to-client',
'/with-server-action', '/react-cache',
]) '/referential-equality',
'/revalidate-and-redirect/redirect',
'/rsc-payload',
'/static-class-method',
withCacheComponents && '/unhandled-promise-regression',
'/use-action-state',
'/with-server-action',
].filter(Boolean)
)
}) })
it('should match the expected revalidate and expire configs on the prerender manifest', async () => { it('should match the expected revalidate and expire configs on the prerender manifest', async () => {
...@@ -527,7 +545,7 @@ describe('use-cache', () => { ...@@ -527,7 +545,7 @@ describe('use-cache', () => {
// custom cache life profile "frequent" // custom cache life profile "frequent"
expect(routes['/cache-life'].initialRevalidateSeconds).toBe(100) expect(routes['/cache-life'].initialRevalidateSeconds).toBe(100)
expect(routes['/cache-life'].initialExpireSeconds).toBe(250) expect(routes['/cache-life'].initialExpireSeconds).toBe(300)
// default expireTime // default expireTime
expect(routes['/cache-fetch'].initialExpireSeconds).toBe(31536000) expect(routes['/cache-fetch'].initialExpireSeconds).toBe(31536000)
...@@ -554,8 +572,8 @@ describe('use-cache', () => { ...@@ -554,8 +572,8 @@ describe('use-cache', () => {
let response = await next.fetch('/cache-life') let response = await next.fetch('/cache-life')
expect(response.headers.get('cache-control')).toBe( expect(response.headers.get('cache-control')).toBe(
// revalidate is set to 100, expire is set to 250 => SWR 150 // revalidate is set to 100, expire is set to 300 => SWR 200
's-maxage=100, stale-while-revalidate=150' 's-maxage=100, stale-while-revalidate=200'
) )
response = await next.fetch('/cache-fetch') response = await next.fetch('/cache-fetch')
...@@ -597,11 +615,10 @@ describe('use-cache', () => { ...@@ -597,11 +615,10 @@ describe('use-cache', () => {
await browser.elementByCss('#refresh').click() await browser.elementByCss('#refresh').click()
await waitFor(500) await retry(async () => {
const time3 = await browser.waitForElementByCss('#t').text()
const time3 = await browser.waitForElementByCss('#t').text() expect(time3).not.toBe(time2)
})
expect(time3).not.toBe(time2)
// Reloading again should ideally be the same value but because the Action seeds // Reloading again should ideally be the same value but because the Action seeds
// the cache with real params as the argument it has a different cache key. // the cache with real params as the argument it has a different cache key.
...@@ -878,26 +895,33 @@ describe('use-cache', () => { ...@@ -878,26 +895,33 @@ describe('use-cache', () => {
}) })
if (isNextDev) { if (isNextDev) {
it('should not have unhandled rejection of Request data promises when use cache is enabled without dynamicIO', async () => { if (process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS !== 'true') {
await next.render('/unhandled-promise-regression') it('should not have unhandled rejection of Request data promises when use cache is enabled without dynamicIO', async () => {
// We assert both to better defend against changes in error messaging invalidating this test silently. await next.render('/unhandled-promise-regression')
// They are today asserting the same thing // We assert both to better defend against changes in error messaging invalidating this test silently.
expect(next.cliOutput).not.toContain( // They are today asserting the same thing
'During prerendering, `cookies()` rejects when the prerender is complete.' expect(next.cliOutput).not.toContain(
) 'During prerendering, `cookies()` rejects when the prerender is complete.'
expect(next.cliOutput).not.toContain( )
'During prerendering, `headers()` rejects when the prerender is complete.' expect(next.cliOutput).not.toContain(
) 'During prerendering, `headers()` rejects when the prerender is complete.'
expect(next.cliOutput).not.toContain( )
'During prerendering, `connection()` rejects when the prerender is complete.' expect(next.cliOutput).not.toContain(
) 'During prerendering, `connection()` rejects when the prerender is complete.'
expect(next.cliOutput).not.toContain('HANGING_PROMISE_REJECTION') )
}) expect(next.cliOutput).not.toContain('HANGING_PROMISE_REJECTION')
})
}
it('replays logs from "use cache" functions', async () => { it('replays logs from "use cache" functions', async () => {
const browser = await next.browser('/logs') const browser = await next.browser('/logs')
const initialLogs = await getSanitizedLogs(browser) const initialLogs = await getSanitizedLogs(browser)
const expectedOutsideBadge =
process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS === 'true'
? 'Prerender'
: 'Server'
// We ignore the logged time string at the end of this message: // We ignore the logged time string at the end of this message:
const logMessageWithDateRegexp = /^ Cache {2}deep inside / const logMessageWithDateRegexp = /^ Cache {2}deep inside /
...@@ -906,7 +930,7 @@ describe('use-cache', () => { ...@@ -906,7 +930,7 @@ describe('use-cache', () => {
await retry(async () => { await retry(async () => {
expect(initialLogs).toMatchObject( expect(initialLogs).toMatchObject(
expect.arrayContaining([ expect.arrayContaining([
' Server outside', ` ${expectedOutsideBadge} outside`,
' Cache inside', ' Cache inside',
expect.stringMatching(logMessageWithDateRegexp), expect.stringMatching(logMessageWithDateRegexp),
]) ])
...@@ -929,7 +953,7 @@ describe('use-cache', () => { ...@@ -929,7 +953,7 @@ describe('use-cache', () => {
expect(newLogs).toMatchObject( expect(newLogs).toMatchObject(
expect.arrayContaining([ expect.arrayContaining([
' Server outside', ` ${expectedOutsideBadge} outside`,
' Cache inside', ' Cache inside',
logMessageWithCachedDate, logMessageWithCachedDate,
]) ])
......
...@@ -6236,7 +6236,7 @@ ...@@ -6236,7 +6236,7 @@
"use-cache should prerender fully cacheable pages as static HTML", "use-cache should prerender fully cacheable pages as static HTML",
"use-cache should propagate unstable_cache tags correctly", "use-cache should propagate unstable_cache tags correctly",
"use-cache should return the same object reference for multiple invocations", "use-cache should return the same object reference for multiple invocations",
"use-cache should revalidate before redirecting in a route handlers", "use-cache should revalidate before redirecting in a route handler",
"use-cache should revalidate caches after redirect", "use-cache should revalidate caches after redirect",
"use-cache should revalidate caches during on-demand revalidation", "use-cache should revalidate caches during on-demand revalidation",
"use-cache should revalidate caches nested in unstable_cache", "use-cache should revalidate caches nested in unstable_cache",
...@@ -9927,7 +9927,7 @@ ...@@ -9927,7 +9927,7 @@
"use-cache should override fetch with cookies/auth in use cache properly", "use-cache should override fetch with cookies/auth in use cache properly",
"use-cache should override fetch with no-store in use cache properly", "use-cache should override fetch with no-store in use cache properly",
"use-cache should return the same object reference for multiple invocations", "use-cache should return the same object reference for multiple invocations",
"use-cache should revalidate before redirecting in a route handlers", "use-cache should revalidate before redirecting in a route handler",
"use-cache should revalidate caches after redirect", "use-cache should revalidate caches after redirect",
"use-cache should revalidate caches during on-demand revalidation", "use-cache should revalidate caches during on-demand revalidation",
"use-cache should revalidate caches nested in unstable_cache", "use-cache should revalidate caches nested in unstable_cache",
...@@ -6096,7 +6096,7 @@ ...@@ -6096,7 +6096,7 @@
"use-cache should prerender fully cacheable pages as static HTML", "use-cache should prerender fully cacheable pages as static HTML",
"use-cache should propagate unstable_cache tags correctly", "use-cache should propagate unstable_cache tags correctly",
"use-cache should return the same object reference for multiple invocations", "use-cache should return the same object reference for multiple invocations",
"use-cache should revalidate before redirecting in a route handlers", "use-cache should revalidate before redirecting in a route handler",
"use-cache should revalidate caches after redirect", "use-cache should revalidate caches after redirect",
"use-cache should revalidate caches during on-demand revalidation", "use-cache should revalidate caches during on-demand revalidation",
"use-cache should revalidate caches nested in unstable_cache", "use-cache should revalidate caches nested in unstable_cache",
...@@ -9673,7 +9673,7 @@ ...@@ -9673,7 +9673,7 @@
"use-cache should override fetch with cookies/auth in use cache properly", "use-cache should override fetch with cookies/auth in use cache properly",
"use-cache should override fetch with no-store in use cache properly", "use-cache should override fetch with no-store in use cache properly",
"use-cache should return the same object reference for multiple invocations", "use-cache should return the same object reference for multiple invocations",
"use-cache should revalidate before redirecting in a route handlers", "use-cache should revalidate before redirecting in a route handler",
"use-cache should revalidate caches after redirect", "use-cache should revalidate caches after redirect",
"use-cache should revalidate caches during on-demand revalidation", "use-cache should revalidate caches during on-demand revalidation",
"use-cache should revalidate caches nested in unstable_cache", "use-cache should revalidate caches nested in unstable_cache",
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