Unverified Commit a9f0a668 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

test: compare cache-control directives as a set in deploy tests (#99892)

Imported https://github.com/vercel/next.js/pull/99872 by @pieh as a
local branch to be able to run CI
Closes https://github.com/vercel/next.js/pull/99872

---


<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

We encourage you to use AI to assist you in researching, creating, and
reviewing changes. However, you must review and deeply understand the
contributions you are making. For this reason, **pull request
descriptions from external contributors must be written by a human**.

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Signed commits

- This repository requires verified commit signatures on protected
branches.
- If this pull request is blocked for unsigned commits, re-sign the
commits and force-push the branch.
- A `Signed-off-by` line in the commit message is not enough.

## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

### What?

Adjust existing `cache-control` assertions in e2e tests running in
deploy mode to compare directives in a way that whitespace changes don't
fail a test, but still assert that exact set of expected directives is
received.

To minimize the change I avoided changing tests that do not run in
deploy mode.

### Why?

Tests asserting on exact string are failing like this when testing
Netlify deployments:
```
Error: expect(received).toBe(expected) // Object.is equality

Expected: "public, max-age=0, must-revalidate"
Received: "public,max-age=0,must-revalidate"
    at Object.toBe (/home/runner/work/opennextjs-netlify/opennextjs-netlify/nextjs/test/e2e/app-dir/metadata-dynamic-routes/index.test.ts:26:48)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
```

which still has same overall behavior, just not the same exact
formatting

### How?

Extract pre-existing local `expectDirectives` helper from one of the the
[tests](https://github.com/vercel/next.js/blob/ea119d2702ba9252233c678ca74b4a310b5eedd0/test/e2e/app-dir/ppr-full/ppr-full.test.ts#L70-L83)
to shared utils, generalize it to allow regex rules and adjust deploy
tests to use it instead of strict string comparisons.
Co-authored-by: 's avatarpieh <misiek.piechowiak@gmail.com>
parent 6469906e
import { RouteKind } from 'next/dist/server/route-kind' import { RouteKind } from 'next/dist/server/route-kind'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import imageSize from 'image-size' import imageSize from 'image-size'
import { check, getDistDir } from 'next-test-utils' import { check, expectDirectives, getDistDir } from 'next-test-utils'
const CACHE_HEADERS = { const CACHE_HEADERS = {
NONE: 'no-cache, no-store', NONE: ['no-cache', 'no-store'],
REVALIDATE: 'public, max-age=0, must-revalidate', REVALIDATE: ['public', 'max-age=0', 'must-revalidate'],
} }
const hashRegex = /\?\w+/ const hashRegex = /\?\w+/
...@@ -24,7 +24,10 @@ describe('app dir - metadata dynamic routes', () => { ...@@ -24,7 +24,10 @@ describe('app dir - metadata dynamic routes', () => {
const text = await res.text() const text = await res.text()
expect(res.headers.get('content-type')).toContain('text/plain') expect(res.headers.get('content-type')).toContain('text/plain')
expect(res.headers.get('cache-control')).toBe(CACHE_HEADERS.REVALIDATE) expectDirectives(
res.headers.get('cache-control'),
CACHE_HEADERS.REVALIDATE
)
expect(text).toMatchInlineSnapshot(` expect(text).toMatchInlineSnapshot(`
"User-Agent: Googlebot "User-Agent: Googlebot
...@@ -48,7 +51,10 @@ describe('app dir - metadata dynamic routes', () => { ...@@ -48,7 +51,10 @@ describe('app dir - metadata dynamic routes', () => {
const text = await res.text() const text = await res.text()
expect(res.headers.get('content-type')).toBe('application/xml') expect(res.headers.get('content-type')).toBe('application/xml')
expect(res.headers.get('cache-control')).toBe(CACHE_HEADERS.REVALIDATE) expectDirectives(
res.headers.get('cache-control'),
CACHE_HEADERS.REVALIDATE
)
expect(text).toMatchInlineSnapshot(` expect(text).toMatchInlineSnapshot(`
"<?xml version="1.0" encoding="UTF-8"?> "<?xml version="1.0" encoding="UTF-8"?>
...@@ -191,7 +197,10 @@ describe('app dir - metadata dynamic routes', () => { ...@@ -191,7 +197,10 @@ describe('app dir - metadata dynamic routes', () => {
expect(res.headers.get('content-type')).toContain( expect(res.headers.get('content-type')).toContain(
'application/manifest+json' 'application/manifest+json'
) )
expect(res.headers.get('cache-control')).toBe(CACHE_HEADERS.REVALIDATE) expectDirectives(
res.headers.get('cache-control'),
CACHE_HEADERS.REVALIDATE
)
expect(json).toMatchObject({ expect(json).toMatchObject({
name: 'Next.js App', name: 'Next.js App',
...@@ -215,7 +224,8 @@ describe('app dir - metadata dynamic routes', () => { ...@@ -215,7 +224,8 @@ describe('app dir - metadata dynamic routes', () => {
const res = await next.fetch('/opengraph-image') const res = await next.fetch('/opengraph-image')
expect(res.headers.get('content-type')).toBe('image/png') expect(res.headers.get('content-type')).toBe('image/png')
expect(res.headers.get('cache-control')).toBe( expectDirectives(
res.headers.get('cache-control'),
isNextDev ? CACHE_HEADERS.NONE : CACHE_HEADERS.REVALIDATE isNextDev ? CACHE_HEADERS.NONE : CACHE_HEADERS.REVALIDATE
) )
}) })
...@@ -225,7 +235,8 @@ describe('app dir - metadata dynamic routes', () => { ...@@ -225,7 +235,8 @@ describe('app dir - metadata dynamic routes', () => {
let res = await next.fetch('/twitter-image') let res = await next.fetch('/twitter-image')
expect(res.headers.get('content-type')).toBe('image/png') expect(res.headers.get('content-type')).toBe('image/png')
expect(res.headers.get('cache-control')).toBe( expectDirectives(
res.headers.get('cache-control'),
isNextDev ? CACHE_HEADERS.NONE : CACHE_HEADERS.REVALIDATE isNextDev ? CACHE_HEADERS.NONE : CACHE_HEADERS.REVALIDATE
) )
...@@ -247,7 +258,8 @@ describe('app dir - metadata dynamic routes', () => { ...@@ -247,7 +258,8 @@ describe('app dir - metadata dynamic routes', () => {
// edge runtime // edge runtime
res = await next.fetch('/twitter-image2') res = await next.fetch('/twitter-image2')
expect(res.headers.get('content-type')).toBe('image/png') expect(res.headers.get('content-type')).toBe('image/png')
expect(res.headers.get('cache-control')).toBe( expectDirectives(
res.headers.get('cache-control'),
isNextDev ? CACHE_HEADERS.NONE : CACHE_HEADERS.REVALIDATE isNextDev ? CACHE_HEADERS.NONE : CACHE_HEADERS.REVALIDATE
) )
}) })
...@@ -348,7 +360,8 @@ describe('app dir - metadata dynamic routes', () => { ...@@ -348,7 +360,8 @@ describe('app dir - metadata dynamic routes', () => {
const res = await next.fetch('/icon') const res = await next.fetch('/icon')
expect(res.headers.get('content-type')).toBe('image/png') expect(res.headers.get('content-type')).toBe('image/png')
expect(res.headers.get('cache-control')).toBe( expectDirectives(
res.headers.get('cache-control'),
isNextDev ? CACHE_HEADERS.NONE : CACHE_HEADERS.REVALIDATE isNextDev ? CACHE_HEADERS.NONE : CACHE_HEADERS.REVALIDATE
) )
}) })
...@@ -357,7 +370,8 @@ describe('app dir - metadata dynamic routes', () => { ...@@ -357,7 +370,8 @@ describe('app dir - metadata dynamic routes', () => {
const res = await next.fetch('/apple-icon') const res = await next.fetch('/apple-icon')
expect(res.headers.get('content-type')).toBe('image/png') expect(res.headers.get('content-type')).toBe('image/png')
expect(res.headers.get('cache-control')).toBe( expectDirectives(
res.headers.get('cache-control'),
isNextDev ? CACHE_HEADERS.NONE : CACHE_HEADERS.REVALIDATE isNextDev ? CACHE_HEADERS.NONE : CACHE_HEADERS.REVALIDATE
) )
}) })
......
import { isNextDeploy, isNextStart, nextTestSetup } from 'e2e-utils' import { isNextDeploy, isNextStart, nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next' import type { NextAdapter } from 'next'
import { expectDirectives } from 'next-test-utils'
describe('not-found-non-document-dynamic', () => { describe('not-found-non-document-dynamic', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -25,9 +26,13 @@ describe('not-found-non-document-dynamic', () => { ...@@ -25,9 +26,13 @@ describe('not-found-non-document-dynamic', () => {
expect(res.headers.get('content-type')).toContain('text/html') expect(res.headers.get('content-type')).toContain('text/html')
} else { } else {
expect(res.headers.get('content-type')).toContain('text/plain') expect(res.headers.get('content-type')).toContain('text/plain')
expect(res.headers.get('cache-control')).toBe( expectDirectives(res.headers.get('cache-control'), [
'private, no-cache, no-store, max-age=0, must-revalidate' 'private',
) 'no-cache',
'no-store',
'max-age=0',
'must-revalidate',
])
expect(await res.text()).toBe('Not Found') expect(await res.text()).toBe('Not Found')
} }
if (!isNextDeploy) { if (!isNextDeploy) {
......
import { randomUUID } from 'node:crypto' import { randomUUID } from 'node:crypto'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { gate, retry } from 'next-test-utils' import { expectDirectives, gate, retry } from 'next-test-utils'
import type { Page } from 'playwright' import type { Page } from 'playwright'
import { createRouterAct } from 'router-act' import { createRouterAct } from 'router-act'
...@@ -47,10 +47,17 @@ describe('on-demand-prerender-error-boundary', () => { ...@@ -47,10 +47,17 @@ describe('on-demand-prerender-error-boundary', () => {
}) })
try { try {
expect(response.status()).toBe(500) expect(response.status()).toBe(500)
expect(response.headers()['cache-control']).toBe( expectDirectives(
response.headers()['cache-control'],
usesGenericErrorPage usesGenericErrorPage
? 'public, max-age=0, must-revalidate' ? ['public', 'max-age=0', 'must-revalidate']
: 'private, no-cache, no-store, max-age=0, must-revalidate' : [
'private',
'no-cache',
'no-store',
'max-age=0',
'must-revalidate',
]
) )
if (!usesGenericErrorPage) { if (!usesGenericErrorPage) {
...@@ -120,9 +127,13 @@ describe('on-demand-prerender-error-boundary', () => { ...@@ -120,9 +127,13 @@ describe('on-demand-prerender-error-boundary', () => {
try { try {
expect(response.status()).toBe(status) expect(response.status()).toBe(status)
if (status === 500 && !usesGenericErrorPage) { if (status === 500 && !usesGenericErrorPage) {
expect(response.headers()['cache-control']).toBe( expectDirectives(response.headers()['cache-control'], [
'private, no-cache, no-store, max-age=0, must-revalidate' 'private',
) 'no-cache',
'no-store',
'max-age=0',
'must-revalidate',
])
} }
await retry(async () => { await retry(async () => {
if (status === 500) { if (status === 500) {
...@@ -265,9 +276,13 @@ describe('on-demand-prerender-error-boundary', () => { ...@@ -265,9 +276,13 @@ describe('on-demand-prerender-error-boundary', () => {
try { try {
expect(response.status()).toBe(status) expect(response.status()).toBe(status)
if (status === 500 && !usesGenericErrorPage) { if (status === 500 && !usesGenericErrorPage) {
expect(response.headers()['cache-control']).toBe( expectDirectives(response.headers()['cache-control'], [
'private, no-cache, no-store, max-age=0, must-revalidate' 'private',
) 'no-cache',
'no-store',
'max-age=0',
'must-revalidate',
])
} }
await retry(async () => { await retry(async () => {
...@@ -565,10 +580,11 @@ describe('on-demand-prerender-error-boundary', () => { ...@@ -565,10 +580,11 @@ describe('on-demand-prerender-error-boundary', () => {
(conditions) => conditions.deploy && !conditions.adapter (conditions) => conditions.deploy && !conditions.adapter
) )
expect(response.status()).toBe(500) expect(response.status()).toBe(500)
expect(response.headers()['cache-control']).toBe( expectDirectives(
response.headers()['cache-control'],
usesGenericErrorPage usesGenericErrorPage
? 'public, max-age=0, must-revalidate' ? ['public', 'max-age=0', 'must-revalidate']
: 'private, no-cache, no-store, max-age=0, must-revalidate' : ['private', 'no-cache', 'no-store', 'max-age=0', 'must-revalidate']
) )
const expectedText = usesGenericErrorPage const expectedText = usesGenericErrorPage
...@@ -602,10 +618,17 @@ describe('on-demand-prerender-error-boundary', () => { ...@@ -602,10 +618,17 @@ describe('on-demand-prerender-error-boundary', () => {
const { browser, response } = await next.browserWithResponse(pathname) const { browser, response } = await next.browserWithResponse(pathname)
try { try {
expect(response.status()).toBe(500) expect(response.status()).toBe(500)
expect(response.headers()['cache-control']).toBe( expectDirectives(
response.headers()['cache-control'],
usesGenericErrorPage usesGenericErrorPage
? 'public, max-age=0, must-revalidate' ? ['public', 'max-age=0', 'must-revalidate']
: 'private, no-cache, no-store, max-age=0, must-revalidate' : [
'private',
'no-cache',
'no-store',
'max-age=0',
'must-revalidate',
]
) )
await retry(async () => { await retry(async () => {
expect(await browser.elementByCss('body').text()).toContain( expect(await browser.elementByCss('body').text()).toContain(
......
...@@ -2,7 +2,7 @@ import { nextTestSetup, isNextStart } from 'e2e-utils' ...@@ -2,7 +2,7 @@ import { nextTestSetup, isNextStart } from 'e2e-utils'
import { splitResponseWithPPRSentinel } from 'e2e-utils/ppr' import { splitResponseWithPPRSentinel } from 'e2e-utils/ppr'
import { links } from './components/links' import { links } from './components/links'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import { getCacheHeader, retry } from 'next-test-utils' import { expectDirectives, getCacheHeader, retry } from 'next-test-utils'
import { computeCacheBustingSearchParam } from 'next/dist/shared/lib/router/utils/cache-busting-search-param' import { computeCacheBustingSearchParam } from 'next/dist/shared/lib/router/utils/cache-busting-search-param'
type Page = { type Page = {
...@@ -67,21 +67,6 @@ const addCacheBustingSearchParam = async ( ...@@ -67,21 +67,6 @@ const addCacheBustingSearchParam = async (
return url.pathname + url.search return url.pathname + url.search
} }
/**
* Expects that the cache-control header contains the given directives in any
* order.
*
* @param header The cache-control header to check.
* @param directives The directives to expect.
*/
const expectDirectives = (header: string, directives: string[]) => {
const split = header.split(',').map((directive) => directive.trim())
for (const directive of directives) {
expect(split).toContain(directive)
}
expect(split.length).toEqual(directives.length)
}
// TODO(NAR-423): Migrate to Cache Components. // TODO(NAR-423): Migrate to Cache Components.
describe.skip('ppr-full', () => { describe.skip('ppr-full', () => {
const { next, isNextDev, isNextDeploy } = nextTestSetup({ const { next, isNextDev, isNextDeploy } = nextTestSetup({
......
...@@ -7,6 +7,7 @@ import { ...@@ -7,6 +7,7 @@ import {
check, check,
retry, retry,
fetchViaHTTP, fetchViaHTTP,
expectDirectives,
getBrowserBodyText, getBrowserBodyText,
getRedboxHeader, getRedboxHeader,
normalizeRegEx, normalizeRegEx,
...@@ -821,28 +822,42 @@ const runTests = ( ...@@ -821,28 +822,42 @@ const runTests = (
it('should set default caching header', async () => { it('should set default caching header', async () => {
const resPage = await fetchViaHTTP(next.url, `/something`) const resPage = await fetchViaHTTP(next.url, `/something`)
expect(resPage.headers.get('cache-control')).toBe( expectDirectives(resPage.headers.get('cache-control'), [
'private, no-cache, no-store, max-age=0, must-revalidate' 'private',
) 'no-cache',
'no-store',
'max-age=0',
'must-revalidate',
])
const resData = await fetchViaHTTP( const resData = await fetchViaHTTP(
next.url, next.url,
`/_next/data/${buildId}/something.json` `/_next/data/${buildId}/something.json`
) )
expect(resData.headers.get('cache-control')).toBe( expectDirectives(resData.headers.get('cache-control'), [
'private, no-cache, no-store, max-age=0, must-revalidate' 'private',
) 'no-cache',
'no-store',
'max-age=0',
'must-revalidate',
])
}) })
it('should respect custom caching header', async () => { it('should respect custom caching header', async () => {
const resPage = await fetchViaHTTP(next.url, `/custom-cache`) const resPage = await fetchViaHTTP(next.url, `/custom-cache`)
expect(resPage.headers.get('cache-control')).toBe('public, max-age=3600') expectDirectives(resPage.headers.get('cache-control'), [
'public',
'max-age=3600',
])
const resData = await fetchViaHTTP( const resData = await fetchViaHTTP(
next.url, next.url,
`/_next/data/${buildId}/custom-cache.json` `/_next/data/${buildId}/custom-cache.json`
) )
expect(resData.headers.get('cache-control')).toBe('public, max-age=3600') expectDirectives(resData.headers.get('cache-control'), [
'public',
'max-age=3600',
])
}) })
it('should not show error for invalid JSON returned from getServerSideProps', async () => { it('should not show error for invalid JSON returned from getServerSideProps', async () => {
......
...@@ -15,6 +15,7 @@ import { ...@@ -15,6 +15,7 @@ import {
retry, retry,
waitFor, waitFor,
getCacheHeader, getCacheHeader,
expectDirectives,
} from 'next-test-utils' } from 'next-test-utils'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
import { RouteKind } from 'next/dist/server/route-kind' import { RouteKind } from 'next/dist/server/route-kind'
...@@ -691,20 +692,22 @@ describe('Prerender', () => { ...@@ -691,20 +692,22 @@ describe('Prerender', () => {
if (!isDev) { if (!isDev) {
it('should use correct caching headers for a revalidate page', async () => { it('should use correct caching headers for a revalidate page', async () => {
const initialRes = await fetchViaHTTP(next.url, '/') const initialRes = await fetchViaHTTP(next.url, '/')
expect(initialRes.headers.get('cache-control')).toBe( expectDirectives(
initialRes.headers.get('cache-control'),
isDeploy isDeploy
? 'public, max-age=0, must-revalidate' ? ['public', 'max-age=0', 'must-revalidate']
: 's-maxage=2, stale-while-revalidate=31535998' : ['s-maxage=2', 'stale-while-revalidate=31535998']
) )
}) })
it('should use correct caching headers for a fallback-true page (prerendered)', async () => { it('should use correct caching headers for a fallback-true page (prerendered)', async () => {
const initialRes = await fetchViaHTTP(next.url, '/fallback-true/first') const initialRes = await fetchViaHTTP(next.url, '/fallback-true/first')
expect(initialRes.status).toBe(200) expect(initialRes.status).toBe(200)
expect(initialRes.headers.get('cache-control')).toBe( expectDirectives(
initialRes.headers.get('cache-control'),
isDeploy isDeploy
? 'public, max-age=0, must-revalidate' ? ['public', 'max-age=0', 'must-revalidate']
: 's-maxage=2, stale-while-revalidate=31535998' : ['s-maxage=2', 'stale-while-revalidate=31535998']
) )
expect(await initialRes.text()).not.toContain('hi fallback') expect(await initialRes.text()).not.toContain('hi fallback')
...@@ -713,19 +716,21 @@ describe('Prerender', () => { ...@@ -713,19 +716,21 @@ describe('Prerender', () => {
`/_next/data/${next.buildId}/fallback-true/first.json` `/_next/data/${next.buildId}/fallback-true/first.json`
) )
expect(dataRes.status).toBe(200) expect(dataRes.status).toBe(200)
expect(dataRes.headers.get('cache-control')).toBe( expectDirectives(
dataRes.headers.get('cache-control'),
isDeploy isDeploy
? 'public, max-age=0, must-revalidate' ? ['public', 'max-age=0', 'must-revalidate']
: 's-maxage=2, stale-while-revalidate=31535998' : ['s-maxage=2', 'stale-while-revalidate=31535998']
) )
await retry(async () => { await retry(async () => {
const finalRes = await fetchViaHTTP(next.url, `/fallback-true/first`) const finalRes = await fetchViaHTTP(next.url, `/fallback-true/first`)
expect(finalRes.status).toBe(200) expect(finalRes.status).toBe(200)
expect(finalRes.headers.get('cache-control')).toBe( expectDirectives(
finalRes.headers.get('cache-control'),
isDeploy isDeploy
? 'public, max-age=0, must-revalidate' ? ['public', 'max-age=0', 'must-revalidate']
: 's-maxage=2, stale-while-revalidate=31535998' : ['s-maxage=2', 'stale-while-revalidate=31535998']
) )
expect(await finalRes.text()).not.toContain('hi fallback') expect(await finalRes.text()).not.toContain('hi fallback')
}) })
...@@ -734,10 +739,17 @@ describe('Prerender', () => { ...@@ -734,10 +739,17 @@ describe('Prerender', () => {
it('should use correct caching headers for a fallback-true page (lazy)', async () => { it('should use correct caching headers for a fallback-true page (lazy)', async () => {
const initialRes = await fetchViaHTTP(next.url, '/fallback-true/second') const initialRes = await fetchViaHTTP(next.url, '/fallback-true/second')
expect(initialRes.status).toBe(200) expect(initialRes.status).toBe(200)
expect(initialRes.headers.get('cache-control')).toBe( expectDirectives(
initialRes.headers.get('cache-control'),
isDeploy isDeploy
? 'public, max-age=0, must-revalidate' ? ['public', 'max-age=0', 'must-revalidate']
: 'private, no-cache, no-store, max-age=0, must-revalidate' : [
'private',
'no-cache',
'no-store',
'max-age=0',
'must-revalidate',
]
) )
expect(await initialRes.text()).toContain('hi fallback') expect(await initialRes.text()).toContain('hi fallback')
...@@ -746,19 +758,21 @@ describe('Prerender', () => { ...@@ -746,19 +758,21 @@ describe('Prerender', () => {
`/_next/data/${next.buildId}/fallback-true/second.json` `/_next/data/${next.buildId}/fallback-true/second.json`
) )
expect(dataRes.status).toBe(200) expect(dataRes.status).toBe(200)
expect(dataRes.headers.get('cache-control')).toBe( expectDirectives(
dataRes.headers.get('cache-control'),
isDeploy isDeploy
? 'public, max-age=0, must-revalidate' ? ['public', 'max-age=0', 'must-revalidate']
: 's-maxage=2, stale-while-revalidate=31535998' : ['s-maxage=2', 'stale-while-revalidate=31535998']
) )
await retry(async () => { await retry(async () => {
const finalRes = await fetchViaHTTP(next.url, `/fallback-true/second`) const finalRes = await fetchViaHTTP(next.url, `/fallback-true/second`)
expect(finalRes.status).toBe(200) expect(finalRes.status).toBe(200)
expect(finalRes.headers.get('cache-control')).toBe( expectDirectives(
finalRes.headers.get('cache-control'),
isDeploy isDeploy
? 'public, max-age=0, must-revalidate' ? ['public', 'max-age=0', 'must-revalidate']
: 's-maxage=2, stale-while-revalidate=31535998' : ['s-maxage=2', 'stale-while-revalidate=31535998']
) )
expect(await finalRes.text()).not.toContain('hi fallback') expect(await finalRes.text()).not.toContain('hi fallback')
}) })
...@@ -1392,8 +1406,11 @@ describe('Prerender', () => { ...@@ -1392,8 +1406,11 @@ describe('Prerender', () => {
} else { } else {
it('should use correct caching headers for a no-revalidate page', async () => { it('should use correct caching headers for a no-revalidate page', async () => {
const initialRes = await fetchViaHTTP(next.url, '/something') const initialRes = await fetchViaHTTP(next.url, '/something')
expect(initialRes.headers.get('cache-control')).toBe( expectDirectives(
isDeploy ? 'public, max-age=0, must-revalidate' : 's-maxage=31536000' initialRes.headers.get('cache-control'),
isDeploy
? ['public', 'max-age=0', 'must-revalidate']
: ['s-maxage=31536000']
) )
const initialHtml = await initialRes.text() const initialHtml = await initialRes.text()
expect(initialHtml).toMatch(/hello.*?world/) expect(initialHtml).toMatch(/hello.*?world/)
......
...@@ -2181,6 +2181,30 @@ export const getCacheHeader = (curRes: Response) => ...@@ -2181,6 +2181,30 @@ export const getCacheHeader = (curRes: Response) =>
// favor generic header // favor generic header
curRes.headers.get('x-nextjs-cache') || curRes.headers.get('x-vercel-cache') curRes.headers.get('x-nextjs-cache') || curRes.headers.get('x-vercel-cache')
/**
* Asserts that the cache-control header consists of exactly these directives,
* in any order.
*
* @param header The cache-control header to check.
* @param directives The directives to expect.
*/
export const expectDirectives = (
header: string | null,
directives: Array<string | RegExp>
) => {
const split = (header ?? '').split(',').map((directive) => directive.trim())
expect(split).toEqual(
expect.arrayContaining(
directives.map((directive) =>
directive instanceof RegExp
? expect.stringMatching(directive)
: directive
)
)
)
expect(split).toHaveLength(directives.length)
}
export function getDeploymentId(appDir: string, isDev: boolean) { export function getDeploymentId(appDir: string, isDev: boolean) {
let requiredServerFiles: RequiredServerFilesManifest | undefined let requiredServerFiles: RequiredServerFilesManifest | undefined
if (!isDev) { if (!isDev) {
......
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