prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
force-static'
export default async function Page() {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?page',
{
cache: 'no-store',
}
).then((res) => res.text())
const data2 = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?page',
{
... | }
).then((res) => res.text())
return (
<>
<p id="page">/force-static-fetch-no-store</p>
<p id="page-data">{data}</p>
<p id="page-data2">{data2}</p>
<p id="page-data3">{data3}</p>
<p id="now">{Date.now()}</p>
</>
| no-cache',
| {
"filepath": "test/e2e/app-dir/app-static/app/force-static-fetch-no-store/page.js",
"language": "javascript",
"file_size": 812,
"cut_index": 536,
"middle_length": 14
} |
'default-cache'
export default async function Page() {
const dataNoCache = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?no-cache',
{
cache: 'no-cache',
}
).then((res) => res.text())
const dataForceCache = await fetch(
'https://next-data-api-endpoint.vercel.app/api/ra... | xt: {
revalidate: 3,
},
}
).then((res) => res.text())
const dataRevalidateAndFetchCache = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?revalidate-3-force-cache',
{
next: {
revalidate: 3,
| idate-0',
{
next: {
revalidate: 0,
},
}
).then((res) => res.text())
const dataRevalidateCache = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?revalidate-3',
{
ne | {
"filepath": "test/e2e/app-dir/app-static/app/default-cache/page.js",
"language": "javascript",
"file_size": 1773,
"cut_index": 537,
"middle_length": 229
} |
import { unstable_noStore as noStore } from 'next/cache'
export default async function Page() {
// this page is using unstable_noStore() to opt into dynamic rendering
// meaning the page will bail from ISR cache and hint to patch-fetch
// that it's in a dynamic scope and shouldn't cache the fetch.
noStore()
... | <p>/default-cache-fetch</p>
<p id="data-default-cache">"cache: default" {data1}</p>
<p id="data-request-cache">
"cache: default" (Request constructor) {data2}
</p>
<p id="data-cache-auto">"cache: auto" {data3}</p>
</>
| tps://next-data-api-endpoint.vercel.app/api/random?2')
).then((res) => res.text())
const data3 = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?3'
).then((res) => res.text())
return (
<>
| {
"filepath": "test/e2e/app-dir/app-static/app/default-cache-search-params/page.js",
"language": "javascript",
"file_size": 1003,
"cut_index": 512,
"middle_length": 229
} |
lt async function Page() {
const dataNoCache = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?a2',
{
cache: 'no-cache',
}
).then((res) => res.text())
const dataForceCache = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?b3',
{
cache: 'force-... | orce-cache',
}
).then((res) => res.text())
const dataAutoCache = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?d6'
).then((res) => res.text())
return (
<>
<p>/fetch-no-cache</p>
<p id="data-no-cache">" | ,
},
}
).then((res) => res.text())
const dataRevalidateAndFetchCache = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?d5',
{
next: {
revalidate: 3,
},
cache: 'f | {
"filepath": "test/e2e/app-dir/app-static/app/fetch-no-cache/page.js",
"language": "javascript",
"file_size": 1407,
"cut_index": 524,
"middle_length": 229
} |
rt default async function Page() {
const [urlDefaultCache, valueDefaultCache] = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?a1'
).then((res) => Promise.all([res.url, res.text()]))
const urlNoCache = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?b2',
{ cache... | url-default-cache">{urlDefaultCache}</p>
<p id="data-value-default-cache">{valueDefaultCache}</p>
<p id="data-url-no-cache">{urlNoCache}</p>
<p id="data-url-cached">{urlCached}</p>
<p id="data-value-cached">{valueCached}</p>
</> | res.text()]))
return (
<>
<p id="data- | {
"filepath": "test/e2e/app-dir/app-static/app/response-url/page.js",
"language": "javascript",
"file_size": 874,
"cut_index": 559,
"middle_length": 52
} |
{ updateTag, unstable_cache } from 'next/cache'
import { RevalidateButton } from '../revalidate-button'
export const dynamic = 'force-dynamic'
export default async function Page() {
async function revalidate() {
'use server'
await updateTag('random-value-data')
}
const cachedData = await unstable_cach... | >random: {Math.random()}</p>
<p id="cached-data">cachedData: {cachedData.random}</p>
<p id="draft-mode-enabled">
draft mode enabled: {cachedData.draftModeEnabled.toString()}
</p>
<RevalidateButton onClick={revalidate} />
| e-data'],
}
)()
return (
<div>
<p | {
"filepath": "test/e2e/app-dir/app-static/app/unstable-cache/dynamic/page.tsx",
"language": "tsx",
"file_size": 881,
"cut_index": 559,
"middle_length": 52
} |
lt async function Page() {
const traceparent1 = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{
headers: { traceparent: 'A' },
next: { revalidate: 50 },
}
).then((res) => res.text())
const traceparent2 = await fetch(
'https://next-data-api-endpoint.vercel.app/ap... | ',
{
headers: { tracestate: 'B' },
next: { revalidate: 50 },
}
).then((res) => res.text())
const echoedHeaders = await fetch(
'https://next-data-api-endpoint.vercel.app/api/echo-headers',
{
headers: { traceparent: 'A' | t.vercel.app/api/random',
{
headers: { tracestate: 'B' },
next: { revalidate: 50 },
}
).then((res) => res.text())
const tracestate2 = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random | {
"filepath": "test/e2e/app-dir/app-static/app/strip-w3c-trace-context-headers/page.tsx",
"language": "tsx",
"file_size": 1359,
"cut_index": 524,
"middle_length": 229
} |
test-utils'
describe('with babel', () => {
const { next, isNextStart, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should support babel in app dir', async () => {
const $ = await next.render$('/')
expect($('h1').text()).... | skip : it)(
'should contain og package files in middleware',
async () => {
await retry(async () => {
const middleware = await next.readFile('.next/server/middleware.js')
// @vercel/og default font should be bundled
| om/vercel/next.js/pull/51067
;(isTurbopack ? it. | {
"filepath": "test/e2e/app-dir/with-babel/with-babel.test.ts",
"language": "typescript",
"file_size": 985,
"cut_index": 582,
"middle_length": 52
} |
from 'e2e-utils'
describe('@next/third-parties basic usage', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
'@next/third-parties': 'canary',
},
})
it('renders YoutubeEmbed', async () => {
const $ = await next.render$('/youtube-embed')
const baseContainer = ... | y=XYZ"]'
)
expect(baseContainer.length).toBe(1)
expect(mapContainer.length).toBe(1)
})
it('renders GTM', async () => {
const browser = await next.browser('/gtm')
await browser.waitForElementByCss('script#_next-gtm')
await brow | psEmbed', async () => {
const $ = await next.render$('/google-maps-embed')
const baseContainer = $('[data-ntpc="GoogleMapsEmbed"]')
const mapContainer = $(
'[src^="https://www.google.com/maps/embed/v1/place?ke | {
"filepath": "test/e2e/app-dir/third-parties/basic.test.ts",
"language": "typescript",
"file_size": 1999,
"cut_index": 537,
"middle_length": 229
} |
Script = `document.querySelectorAll('body link[rel="icon"], body link[rel="apple-touch-icon"]').forEach(el => document.head.appendChild(el))`
describe('app-dir - metadata-icons', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should only have 1 favicon link in root page', async () => {
... | "shortcut icon"]').attr('href')).toBe(
'/shortcut-icon.png'
)
})
it('should render custom icons along with favicon in nested page', async () => {
const $ = await next.render$('/nested')
expect($('link[rel="shortcut icon"]').attr('hre | xt.render$('/nested')
expect($('link[href^="/favicon.ico"]').length).toBe(1)
})
it('should render custom icons along with favicon in root page', async () => {
const $ = await next.render$('/')
expect($('link[rel= | {
"filepath": "test/e2e/app-dir/metadata-icons/metadata-icons.test.ts",
"language": "typescript",
"file_size": 5059,
"cut_index": 614,
"middle_length": 229
} |
retry } from 'next-test-utils'
describe('parallel-routes-layouts', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should properly render layouts for multiple slots', async () => {
const browser = await next.browser('/nested')
let layouts = await getLayoutHeadings(browser)
exp... | ser.elementById('foo-children').text()).toBe('Foo Slot')
expect(await browser.elementById('bar-children').text()).toBe('Bar Slot')
// Navigate to a subroute that only has a match for the @foo slot
await browser.elementByCss('[href="/nested/sub | )
// ensure nested/page is showing its contents
expect(await browser.elementById('nested-children').text()).toBe(
'Hello from Nested'
)
// Ensure each slot is showing its contents
expect(await brow | {
"filepath": "test/e2e/app-dir/parallel-routes-layouts/parallel-routes-layouts.test.ts",
"language": "typescript",
"file_size": 2694,
"cut_index": 563,
"middle_length": 229
} |
'use client'
import { useInsertionEffect } from 'react'
export default function ClientPage() {
useInsertionEffect(() => {
// Logging in client component useInsertionEffect
// Test complex partial circular object
const circularObj: any = {
name: 'test',
data: {
nested: {
val... | g('Client: Complex circular object:', circularObj)
console.error('Client: This is an error message from client component')
console.warn('Client: This is a warning message from client component')
}, [])
return <p>client page with logging</p>
}
| circularObj.data.parent = circularObj
console.lo | {
"filepath": "test/e2e/app-dir/log-file/app/client/page.tsx",
"language": "tsx",
"file_size": 820,
"cut_index": 512,
"middle_length": 52
} |
) => {
const { next } = nextTestSetup({
files: new FileRef(__dirname),
dependencies: {
typescript: 'latest',
'@types/react': 'latest',
'@types/node': 'latest',
},
})
it('It should be able to navigate app -> pages', async () => {
const browser = await next.browser('/app')
exp... |
expect(await browser.elementById('pages-page').text()).toBe('Pages Page')
})
it('It should be able to navigate pages -> app', async () => {
const browser = await next.browser('/pages')
expect(await browser.elementById('pages-page').text() | an the default timeout.
await browser
.elementById('link-to-pages')
.click()
.waitForElementByCss('#pages-page', { timeout: 30000 })
expect(await browser.hasElementByCssSelector('#app-page')).toBeFalse() | {
"filepath": "test/e2e/app-dir/interoperability-with-pages/navigation.test.ts",
"language": "typescript",
"file_size": 3542,
"cut_index": 614,
"middle_length": 229
} |
irname,
})
it('should delay the metadata render to body', async () => {
const $ = await next.render$('/')
expect($('head title').length).toBe(0)
expect($('body title').length).toBe(1)
})
it('should still load viewport meta tags even if metadata is delayed', async () => {
const $ = await next.r... |
it('should load the initial html without slow metadata during navigation', async () => {
// navigate from / to /slow, the metadata should be empty first, e.g. no title.
// then the metadata should be loaded after few seconds.
const browser = | )
it('should render the metadata in the browser', async () => {
const browser = await next.browser('/')
await retry(async () => {
expect(await browser.elementByCss('title').text()).toBe('index page')
})
})
| {
"filepath": "test/e2e/app-dir/metadata-streaming/metadata-streaming.test.ts",
"language": "typescript",
"file_size": 6737,
"cut_index": 716,
"middle_length": 229
} |
('dynamic-href', () => {
const {
isNextDev: isDev,
next,
skipped,
} = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
if (isDev) {
it('should error when using dynamic href.pathname in app dir', async () => {
const browser = await next.br... | > 5 | <Link
| ^",
"stack": [
"HomePage app/object/page.js (5:5)",
],
}
`)
// Fix error
const pageContent = await next.readFile('app/object/page.js')
await next.patchFile( | p\` router, this is not supported. Read more: https://nextjs.org/docs/messages/app-dir-dynamic-href",
"environmentLabel": null,
"label": "Runtime Error",
"source": "app/object/page.js (5:5) @ HomePage
| {
"filepath": "test/e2e/app-dir/dynamic-href/dynamic-href.test.ts",
"language": "typescript",
"file_size": 2655,
"cut_index": 563,
"middle_length": 229
} |
act'
import { expensiveCalculation } from './actions'
export function Form({ randomNum }) {
const [isPending, setIsPending] = React.useState(false)
const [result, setResult] = React.useState(null)
async function handleSubmit(event) {
event.preventDefault()
setIsPending(true)
const result = await ex... | tton style={{ width: 'max-content' }} type="submit" id="submit">
Submit
</button>
{isPending && 'Loading...'}
</section>
<div>Server side rendered number: {randomNum}</div>
{result && <div id="result">RESULT FROM | mit={handleSubmit}
>
<section>
<bu | {
"filepath": "test/e2e/app-dir/actions-navigation/app/action-after-redirect/form.js",
"language": "javascript",
"file_size": 905,
"cut_index": 547,
"middle_length": 52
} |
from 'e2e-utils'
const isPPREnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true'
;(isPPREnabled ? describe.skip : describe)(
'app-dir - metadata-static-generation',
() => {
const { next, isNextDev, isNextStart } = nextTestSetup({
files: __dirname,
})
// In dev, it suspenses as dynamic rende... | c', async () => {
const prerenderManifest = JSON.parse(
await next.readFile('.next/prerender-manifest.json')
)
const staticRoutes = prerenderManifest.routes
expect(Object.keys(staticRoutes).sort()).toEqual([
| // Precondition for the following tests in build mode.
// This test is only useful for non-PPR mode as in PPR mode those routes
// are all listed in the prerender manifest.
it('should generate all pages stati | {
"filepath": "test/e2e/app-dir/metadata-static-generation/metadata-static-generation.test.ts",
"language": "typescript",
"file_size": 1983,
"cut_index": 537,
"middle_length": 229
} |
from 'e2e-utils'
import { retry } from 'next-test-utils'
import { join } from 'path'
describe('app-dir action allowed from opaque origins', () => {
const { next, skipped } = nextTestSetup({
files: join(__dirname, 'opaque-origin'),
skipDeployment: true,
env: {
NEXT_TEST_ALLOW_OPAQUE_ORIGIN: '1',
... | () => {
const { isNextDev, next, skipped } = nextTestSetup({
files: join(__dirname, 'opaque-origin'),
skipDeployment: true,
env: {
NEXT_TEST_ALLOW_OPAQUE_ORIGIN: '',
},
})
if (skipped) {
return
}
it('should fail on su | type="submit"]').click()
await retry(async () => {
expect(await browser.elementByCss('output').text()).toEqual(
'Action Invoked'
)
})
})
})
describe('app-dir action disallowed from opaque origins', | {
"filepath": "test/e2e/app-dir/actions-allowed-origins/app-action-opaque-origin.test.ts",
"language": "typescript",
"file_size": 1866,
"cut_index": 537,
"middle_length": 229
} |
ime root layout', () => {
const { next, isNextStart, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should not emit metadata files into bad paths', async () => {
await next.fetch('/favicon.ico')
// issue: If metadata files are not filte... | tedStaticFolder).toBe(false)
})
if (isNextStart) {
it('should mark static contain metadata routes as edge functions', async () => {
const middlewareManifest = await next.readFile(
'.next/server/middleware-manifest.json'
)
| it next.hasFile('static')
expect(incorrectGenera | {
"filepath": "test/e2e/app-dir/app-edge-root-layout/index.test.ts",
"language": "typescript",
"file_size": 958,
"cut_index": 582,
"middle_length": 52
} |
t'
import { cookies } from 'next/headers'
import { Delay, Login } from './state'
export async function Dynamic({ fallback }) {
const dynamic = fallback !== true
let signedIn
let active
if (dynamic) {
signedIn = (await cookies()).has('session')
active = (await cookies()).has('delay')
if (active) {
... | }
return (
<div id="dynamic">
<pre id="state" className={signedIn ? 'bg-green-600' : 'bg-red-600'}>
{signedIn ? 'Signed In' : 'Not Signed In'}
</pre>
<Login signedIn={signedIn} />
<Delay active={active} />
</div> | k />
<Delay fallback />
</div>
)
| {
"filepath": "test/e2e/app-dir/ppr/components/dynamic.jsx",
"language": "jsx",
"file_size": 850,
"cut_index": 535,
"middle_length": 52
} |
ref: '/no-suspense' },
{ href: '/suspense/node' },
{ href: '/suspense/edge' },
{ href: '/suspense/node/nested/1' },
{ href: '/loading/nested/1' },
{ href: '/loading/nested/2' },
{ href: '/loading/nested/3' },
]
export default function Root({ children }) {
return (
<html>
<head>
<script ... | links.map(({ href }) => (
<li key={href}>
{href} - <Link href={href}>link</Link> -{' '}
<a href={href}>anchor</a>
</li>
))}
</ul>
</main>
</body>
</html>
| <h2>Links</h2>
<ul>
{ | {
"filepath": "test/e2e/app-dir/ppr/app/layout.jsx",
"language": "jsx",
"file_size": 918,
"cut_index": 606,
"middle_length": 52
} |
h')
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
turbopack: {
resolveAlias: {
'alias-data': './alias-data.mjs',
'alias-dep': './esm-dep.mjs',
},
rules: {
'*.test-file.ts': {
loaders: [require.resolve('./test-file-loader.js')],
as: '*.js',
},
... | treated as external ESM packages by Next.js.
const aliasedModules = new Set(['alias-data', 'alias-dep'])
config.externals = config.externals.map((fn) => {
if (typeof fn !== 'function') return fn
return async function (ctx) {
if | ig.resolve.alias,
'alias-data': path.resolve(__dirname, 'alias-data.mjs'),
'alias-dep': path.resolve(__dirname, 'esm-dep.mjs'),
}
// Wrap externals handlers to prevent aliased bare specifiers from
// being | {
"filepath": "test/e2e/app-dir/webpack-loader-import-module/next.config.js",
"language": "javascript",
"file_size": 1758,
"cut_index": 537,
"middle_length": 229
} |
('webpack-loader-import-module', () => {
const { next, skipped, isTurbopack } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should support this.importModule() in a webpack loader', async () => {
const $ = await next.render$('/')
expect($('#title... | ct($('#mjs-title').text()).toBe('ESM Config Works')
expect($('#mjs-esm-label').text()).toBe('hello from esm')
// resolveAlias: importModule with alias as request
expect($('#alias-value').text()).toBe('resolved via alias')
// resolveAlias: | .toBe('hello from cjs')
expect($('#version').text()).toBe('1.0.0')
// ESM dependency imported from config-data.ts
expect($('#esm-label').text()).toBe('hello from esm')
// ESM .mjs module (config-data.mjs)
expe | {
"filepath": "test/e2e/app-dir/webpack-loader-import-module/webpack-loader-import-module.test.ts",
"language": "typescript",
"file_size": 2355,
"cut_index": 563,
"middle_length": 229
} |
si'
import { retry } from 'next-test-utils'
function normalizeCliOutput(output: string) {
return stripAnsi(output)
}
describe('app-dir - server source maps edge runtime', () => {
const { skipped, next, isNextDev } = nextTestSetup({
files: path.join(__dirname, 'fixtures/edge'),
// Deploy tests don't have a... | rsc-error-log'
)
})
expect(normalizeCliOutput(next.cliOutput.slice(outputIndex))).toContain(
'Error: rsc-error-log' +
'\n at logError (app/rsc-error-log/page.js:2:17)' +
'\n at Page (app/rsc-error-log/ | ', async () => {
const outputIndex = next.cliOutput.length
await next.render('/rsc-error-log')
if (isNextDev) {
await retry(() => {
expect(next.cliOutput.slice(outputIndex)).toContain(
'Error: | {
"filepath": "test/e2e/app-dir/server-source-maps/server-source-maps-edge.test.ts",
"language": "typescript",
"file_size": 3572,
"cut_index": 614,
"middle_length": 229
} |
t'
import { runInternal } from 'internal-pkg'
import { runInternalSourceMapped } from 'internal-pkg/sourcemapped'
import { runInternalIgnored } from 'internal-pkg/ignored'
import { runExternal } from 'external-pkg'
import { runExternalSourceMapped } from 'external-pkg/sourcemapped'
function logError() {
const error ... | ped() {
runExternal(function runWithExternal() {
runExternalSourceMapped(function runWithExternalSourceMapped() {
runInternalIgnored(function runWithInternalIgnored() {
logError()
})
})
})
})
| ernalSourceMap | {
"filepath": "test/e2e/app-dir/server-source-maps/fixtures/default/app/ssr-error-log-ignore-listed/page.js",
"language": "javascript",
"file_size": 813,
"cut_index": 522,
"middle_length": 14
} |
{ nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
async function expectContainOnce(next: any, search: string) {
// Ensure the search string is found once
await retry(() => {
const parts = next.cliOutput.split(search)
expect(parts.length).toBe(2)
})
}
describe('dedupe-rsc-error-... | rver/edge')
await expectContainOnce(next, 'Custom error:server-edge')
})
it('should only log SSR error once for nodejs runtime', async () => {
await next.fetch('/client')
await expectContainOnce(next, 'Custom error:client-node')
})
it | or nodejs runtime', async () => {
await next.fetch('/server')
await expectContainOnce(next, 'Custom error:server-node')
})
it('should only log RSC error once for edge runtime', async () => {
await next.fetch('/se | {
"filepath": "test/e2e/app-dir/dedupe-rsc-error-log/dedupe-rsc-error-log.test.ts",
"language": "typescript",
"file_size": 1176,
"cut_index": 518,
"middle_length": 229
} |
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
test('skipped in dev mode', () => {})
return
}
// Uses Playwright's built-in network emulation, which fires the browser's
// native offline/online events and blocks all requests at the network layer.
async fun... | e) {
page = p
act = createRouterAct(p)
},
})
// Verify we're on the home page and online
expect(await browser.elementById('home').text()).toContain('Home')
expect(await browser.elementById('offline-status').text()).to | 'retries navigation after connectivity is restored', async () => {
let act: ReturnType<typeof createRouterAct>
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Pag | {
"filepath": "test/e2e/app-dir/use-offline/use-offline.test.ts",
"language": "typescript",
"file_size": 5387,
"cut_index": 716,
"middle_length": 229
} |
{ nextTestSetup } from 'e2e-utils'
describe('app-dir - metadata-streaming-customized-rule', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
overrideFiles: {
'next.config.js': `
module.exports = {
htmlLimitedBots: /Minibot/i,
}
`,
},
})
it(... | ) => {
const $ = await next.render$(
'/',
undefined, // no query
{
headers: {
'user-agent': 'Weebot',
},
}
)
expect(await $('head title').length).toBe(0)
expect(await $('body title').length) | ent': 'Minibot',
},
}
)
expect(await $('head title').text()).toBe('index page')
expect(await $('body title').length).toBe(0)
})
it('should send streaming response for headless browser bots', async ( | {
"filepath": "test/e2e/app-dir/metadata-streaming/metadata-streaming-customized-rule.test.ts",
"language": "typescript",
"file_size": 1200,
"cut_index": 518,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import { check, waitFor, retry } from 'next-test-utils'
describe('app-dir action handling', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should handle actions correctly after navigation / redirection events', async () => {
const browser = await next.bro... | ct(await browser.elementByCss('#form').text()).not.toContain(
'Loading...'
)
expect(await browser.elementByCss('#result').text()).toContain(
'RESULT FROM SERVER ACTION'
)
})
it('should handle actions correctly after following | mentByCss('#submit').click()
await check(() => {
return browser.elementByCss('#form').text()
}, /Loading.../)
// wait for 2 seconds, since the action takes a second to resolve
await waitFor(2000)
expe | {
"filepath": "test/e2e/app-dir/actions-navigation/index.test.ts",
"language": "typescript",
"file_size": 1329,
"cut_index": 524,
"middle_length": 229
} |
t'
import { useState } from 'react'
import { log } from './action'
if (typeof window !== 'undefined') {
// hijack fetch
const originalFetch = window.fetch
window.fetch = function (url, init) {
if (init?.method === 'POST') {
console.log('fetch', url, init)
// override forwarded host
init.h... |
return (
<div>
<div id="res">{res}</div>
<button
onClick={async () => {
try {
setRes(await log())
} catch (err) {
setRes(err.message)
}
}}
>
fetch
| seState(null)
| {
"filepath": "test/e2e/app-dir/actions-allowed-origins/unsafe-origins/app/page.js",
"language": "javascript",
"file_size": 819,
"cut_index": 522,
"middle_length": 14
} |
t'
import { useState } from 'react'
import { log } from './action'
if (typeof window !== 'undefined') {
// hijack fetch
const originalFetch = window.fetch
window.fetch = function (url, init) {
if (init?.method === 'POST') {
console.log('fetch', url, init)
// override forwarded host
init.h... |
return (
<div>
<div id="res">{res}</div>
<button
onClick={async () => {
try {
setRes(await log())
} catch (err) {
setRes(err.message)
}
}}
>
fetch
| seState(null)
| {
"filepath": "test/e2e/app-dir/actions-allowed-origins/safe-origins/app/page.js",
"language": "javascript",
"file_size": 819,
"cut_index": 522,
"middle_length": 14
} |
ePathname } from 'next/navigation'
import React from 'react'
import { Suspense } from 'react'
import { useCallback } from 'react'
function Pathname() {
const pathname = usePathname()
return <pre id="pathname">{pathname}</pre>
}
export function Login({ signedIn = false, fallback }) {
const onClick = useCallback(... | ton
id="login"
className="bg-gray-400 hover:bg-gray-500 px-4 py-2 text-white rounded-md"
onClick={onClick}
>
{fallback ? 'Sign ..' : signedIn ? 'Sign Out' : 'Sign In'}
</button>
</>
)
}
export function Del | okie?name=session', {
method: 'POST',
credentials: 'same-origin',
})
}
window.location.reload()
}, [signedIn])
return (
<>
<Suspense>
<Pathname />
</Suspense>
<but | {
"filepath": "test/e2e/app-dir/ppr/components/state.jsx",
"language": "jsx",
"file_size": 1791,
"cut_index": 537,
"middle_length": 229
} |
ort {
title,
items,
cjsGreeting,
version,
esmLabel,
imageUrl,
wasmAddResult,
dynamicValue,
mjsTitle,
mjsEsmLabel,
mjsImageUrl,
mjsWasmAddResult,
mjsDynamicValue,
aliasValue,
aliasDepLabel,
customDataValue,
consumedValue,
} from './file.test-file'
export default function Page() {
ret... | <p id="mjs-image-url">{mjsImageUrl}</p>
<p id="mjs-wasm-add-result">{mjsWasmAddResult}</p>
<p id="mjs-dynamic-value">{mjsDynamicValue}</p>
<p id="alias-value">{aliasValue}</p>
<p id="alias-dep-label">{aliasDepLabel}</p>
| el}</p>
<p id="image-url">{imageUrl}</p>
<p id="wasm-add-result">{wasmAddResult}</p>
<p id="dynamic-value">{dynamicValue}</p>
<p id="mjs-title">{mjsTitle}</p>
<p id="mjs-esm-label">{mjsEsmLabel}</p>
| {
"filepath": "test/e2e/app-dir/webpack-loader-import-module/app/page.js",
"language": "javascript",
"file_size": 1114,
"cut_index": 515,
"middle_length": 229
} |
gation on not-found', async () => {
const browser = await next.browser('/trigger-404')
expect(await browser.elementByCss('#not-found-component').text()).toBe(
'Not Found!'
)
expect(
await browser
.elementByCss('#to-result')
.click()
.waitForElementByCss('#result-page... | Be('Result Page!')
})
it('should allow navigation to other routes on route that was initially not-found', async () => {
// Intentionally non-existent route.
const browser = await next.browser('/testabc')
expect(await browser.elementByCss(' | mentByCss('#error-component').text()).toBe(
'Error Happened!'
)
expect(
await browser
.elementByCss('#to-result')
.click()
.waitForElementByCss('#result-page')
.text()
).to | {
"filepath": "test/e2e/app-dir/error-boundary-navigation/index.test.ts",
"language": "typescript",
"file_size": 3609,
"cut_index": 614,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import { listClientChunks } from 'next-test-utils'
import fs from 'node:fs/promises'
import path from 'node:path'
describe('css-server-chunks', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('... | || f.endsWith('.css'))
expect(clientChunks).toEqual(
expect.arrayContaining([expect.stringMatching(/\.css$/)])
)
let serverChunks = (
await Promise.all(
[`${next.distDir}/server/app`, `${next.distDir}/server/pages`].map(
| ext.fetch('/server')).status).toBe(200)
expect((await next.fetch('/pages')).status).toBe(200)
let clientChunks = (
await listClientChunks(path.join(next.testDir, next.distDir))
).filter((f) => f.endsWith('.js') | {
"filepath": "test/e2e/app-dir/css-server-chunks/css-server-chunks.test.ts",
"language": "typescript",
"file_size": 1413,
"cut_index": 524,
"middle_length": 229
} |
ppr', () => {
const { next, isNextDev, isNextStart } = nextTestSetup({
files: __dirname,
env: {
NEXT_TELEMETRY_DEBUG: '1',
},
})
it('should indicate the feature is experimental', async () => {
await retry(() => {
expect(next.cliOutput).toContain('Experiments (use with caution)')
... | expect(next.cliOutput).toContain(' /suspense/node/nested/[slug]')
})
})
describe('telemetry', () => {
it('should send ppr feature usage event', async () => {
const events = findAllTelemetryEvents(
next.cliOutput, | e build output', () => {
expect(next.cliOutput).toContain('◐ /loading/nested/[slug]')
expect(next.cliOutput).toContain('◐ /suspense/node')
expect(next.cliOutput).toContain(' /suspense/node/gsp/[slug]')
| {
"filepath": "test/e2e/app-dir/ppr/ppr.test.ts",
"language": "typescript",
"file_size": 6528,
"cut_index": 716,
"middle_length": 229
} |
| ^' +
'\n 5 | console.error(error)' +
'\n 6 | }' +
'\n 7 |' +
'\n'
)
} else {
if (isTurbopack) {
// TODO(veil): Sourcemap names
// TODO(veil): relative paths in webpack
expect(normalizeCliOutput(next.cliOutput)).to... | if (isNextDev) {
const outputIndex = next.cliOutput.length
await next.render('/rsc-error-log-cause')
await retry(() => {
expect(next.cliOutput.slice(outputIndex)).toContain(
'Error: rsc-error-log-cause'
)
| -error-log')" +
'\n | ^'
)
} else {
// TODO(veil): line/column numbers are flaky in Webpack
}
}
})
it('logged errors have a sourcemapped `cause`', async () => {
| {
"filepath": "test/e2e/app-dir/server-source-maps/server-source-maps.test.ts",
"language": "typescript",
"file_size": 42798,
"cut_index": 2151,
"middle_length": 229
} |
('next-dynamic-css', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
it('should have correct order of styles between global and css modules', async () => {
const browser = await next.browser('/page')
expect(await browser.waitForElementByCss('#server').text()).toBe(
'Hel... | next/dynamic (TODO)'
)
} else {
it('should have correct order of styles on client component that is sharing styles with next/dynamic', async () => {
const browser = await next.browser('/page')
expect(await browser.waitForElementByCss | mputedCss('color')).toBe(
'rgb(0, 0, 0)'
)
})
if (isNextDev) {
// TODO Fix order of styling in development
it.todo(
'should have correct order of styles on client component that is sharing styles with | {
"filepath": "test/e2e/app-dir/next-dynamic-css/next-dynamic-css.test.ts",
"language": "typescript",
"file_size": 2452,
"cut_index": 563,
"middle_length": 229
} |
t has its own dependencies
// (cjs-dep.ts -> metadata.json, esm-dep.mjs)
const configPath = path.resolve(__dirname, 'config-data.ts')
const configModule = await this.importModule(configPath)
const config = configModule.default || configModule
// Import an ESM .mjs module that also imports esm-dep.mjs
// Us... | e
const mjsEsmLabel = mjsConfig.esmLabel
// --- resolveAlias tests ---
let aliasValue = 'unsupported'
let aliasDepLabel = 'unsupported'
try {
// importModule with alias as the request
const aliasModule = await this.importModule('alias-da | || mjsModule
const title = config.title
const items = config.items.join(', ')
const cjsGreeting = config.cjsGreeting
const version = config.version
const esmLabel = config.esmLabel
const mjsTitle = mjsConfig.mjsTitl | {
"filepath": "test/e2e/app-dir/webpack-loader-import-module/test-file-loader.js",
"language": "javascript",
"file_size": 4659,
"cut_index": 614,
"middle_length": 229
} |
utils'
import { check } from 'next-test-utils'
import { join } from 'path'
describe('app-dir action disallowed origins', () => {
const { next, skipped } = nextTestSetup({
files: join(__dirname, 'unsafe-origins'),
skipDeployment: true,
dependencies: {
'server-only': 'latest',
},
})
if (skip... | it check(async () => {
const t = await browser.elementByCss('#res').text()
return t.includes('Invalid Server Actions request.') ||
// In prod the message is hidden
t.includes('https://react.dev/errors/441')
? 'yes'
| wait browser.elementByCss('button').click()
awa | {
"filepath": "test/e2e/app-dir/actions-allowed-origins/app-action-disallowed-origins.test.ts",
"language": "typescript",
"file_size": 887,
"cut_index": 547,
"middle_length": 52
} |
notFound } from 'next/navigation'
export async function generateStaticParams() {
return [{ slug: ['about'] }]
}
async function validateSlug(slug: string[]) {
try {
const isValidPath =
slug.length === 1 && (slug[0] === 'about' || slug[0] === 'contact')
if (!isValidPath) {
return false
}
... | // Validate the slug
const isValid = await validateSlug(slugArray)
// If not valid, show 404
if (!isValid) {
notFound()
}
return (
<div>
<h1>Catch All</h1>
<p>This is a catch all page added to the APP router</p>
</div> | const slugArray = Array.isArray(slug) ? slug : []
| {
"filepath": "test/e2e/app-dir/not-found-with-pages-i18n/app/app-dir/[[...slug]]/page.tsx",
"language": "tsx",
"file_size": 835,
"cut_index": 520,
"middle_length": 52
} |
om 'e2e-utils'
import { waitForRedbox, retry } from 'next-test-utils'
describe('parallel-routes-leaf-segments-build-error', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'build-error'),
skipStart: true,
skipDeployment: true,
})
if (skipped) {
... | const browser = await next.browser('/with-children/child')
await waitForRedbox(browser)
await retry(async () => {
const logs = await browser.log()
expect(logs).toEqual(
expect.arrayContaining([
| h {
// Expect build error
}
})
}
describe('Non-leaf segment with child routes', () => {
it('should throw MissingDefaultParallelRouteError for @header slot', async () => {
if (isNextDev) {
| {
"filepath": "test/e2e/app-dir/parallel-routes-leaf-segments/parallel-routes-leaf-segments.build-error.test.ts",
"language": "typescript",
"file_size": 2328,
"cut_index": 563,
"middle_length": 229
} |
// @ts-check
import { NextResponse } from 'next/server'
import { NEXT_RSC_UNION_QUERY } from 'next/dist/client/components/app-router-headers'
if (NEXT_RSC_UNION_QUERY !== '_rsc') {
throw new Error(`NEXT_RSC_UNION_QUERY should be _rsc`)
}
/**
* @param {import('next/server').NextRequest} request
* @returns {NextRes... | est', request.url))
}
if (request.nextUrl.pathname === '/redirect-on-refresh/auth') {
const cookie = request.cookies.get('token')
if (cookie) {
return NextResponse.redirect(
new URL('/redirect-on-refresh/dashboard', request.url)
| eware
if (rscQuery) {
throw new Error('RSC query should not be present in the middleware')
}
if (request.nextUrl.pathname === '/redirect-middleware-to-dashboard') {
return NextResponse.redirect(new URL('/redirect-d | {
"filepath": "test/e2e/app-dir/navigation/middleware.js",
"language": "javascript",
"file_size": 1017,
"cut_index": 512,
"middle_length": 229
} |
})
})
},
})
expect(await browser.elementById('name').text()).toBe('名')
await browser.elementById('link').click()
await browser.waitForElementByCss('#set-query')
await retry(() =>
expect(requests).toContainEqual({
pathname: '/',
ok: true,
... | nst link = await browser.elementByCss('a')
await link.hover()
// Hovering a prefetch link should keep the URL intact
expect(await browser.url()).toMatch(/\?foo=bar$/)
})
describe('useParams identity between renders', () => {
| sync () => {
const browser = await next.browser('/search-params/shallow')
const button = await browser.elementByCss('button')
await button.click()
expect(await browser.url()).toMatch(/\?foo=bar$/)
co | {
"filepath": "test/e2e/app-dir/navigation/navigation.test.ts",
"language": "typescript",
"file_size": 36160,
"cut_index": 2151,
"middle_length": 229
} |
tate } from 'react'
export function NavigateAndTrackRouterIdentity({ href }) {
const router = useRouter()
const [prevRouter, setPrevRouter] = useState(router)
const [changedCount, setChangedCount] = useState(0)
if (prevRouter !== router) {
setPrevRouter(router)
setChangedCount((p) => p + 1)
}
con... | unmounting this component):{' '}
<span id="count-from-client-state">{navigationCount}</span>
</div>
<div>
router identity changes:{' '}
<span id="router-change-count">{changedCount}</span>
</div>
<button id=" | n (
<>
<div>
navigations (without | {
"filepath": "test/e2e/app-dir/navigation/app/use-router/navigate.js",
"language": "javascript",
"file_size": 971,
"cut_index": 582,
"middle_length": 52
} |
ect } from 'next/navigation'
function createSuspenseyComponent(Component, { timeout = 0, expire = 10 }) {
let result
let promise
return function Data() {
if (result) return result
if (!promise)
promise = new Promise((resolve) => {
setTimeout(() => {
result = <Component />
... | />
}
const SuspenseyRedirect = createSuspenseyComponent(Redirect, {
timeout: 300,
})
export default function () {
return (
<div className="suspense">
<Suspense fallback="fallback">
<SuspenseyRedirect />
</Suspense>
</div>
| rect() {
redirect('/redirect/result')
return <>< | {
"filepath": "test/e2e/app-dir/navigation/app/redirect/suspense/page.js",
"language": "javascript",
"file_size": 873,
"cut_index": 559,
"middle_length": 52
} |
igation*/
'use client'
import { use } from 'react'
import { redirect, useSearchParams } from 'next/navigation'
let listening = false
export default function Page({ params }) {
if (typeof window === 'undefined') {
throw new Error('Client render only')
}
const { storageKey } = use(params)
let searchParam... | nt number of navigations triggered (in browsers that support it)
sessionStorage.setItem(
`${storageKey}/navigation-supported`,
typeof navigation !== 'undefined'
)
if (!listening && typeof navigation !== 'undefined') {
listenin | value]) =>
key.startsWith(`${storageKey}/`)
? [[key.slice(storageKey.length + 1), value]]
: []
)
)
return <pre id="storage">{JSON.stringify(storage, null, 2)}</pre>
} else {
// Cou | {
"filepath": "test/e2e/app-dir/navigation/app/redirect/external-log/[storageKey]/page.js",
"language": "javascript",
"file_size": 1369,
"cut_index": 524,
"middle_length": 229
} |
port { permanentRedirect } from 'next/navigation'
function createSuspenseyComponent(Component, { timeout = 0, expire = 10 }) {
let result
let promise
return function Data() {
if (result) return result
if (!promise)
promise = new Promise((resolve) => {
setTimeout(() => {
result = <... | redirect/result')
return <></>
}
const SuspenseyRedirect = createSuspenseyComponent(Redirect, {
timeout: 300,
})
export default function () {
return (
<div className="suspense">
<Suspense fallback="fallback">
<SuspenseyRedirect /> |
}
}
function Redirect() {
permanentRedirect('/ | {
"filepath": "test/e2e/app-dir/navigation/app/redirect/suspense-2/page.js",
"language": "javascript",
"file_size": 891,
"cut_index": 547,
"middle_length": 52
} |
ort Link from 'next/link'
import './global.css'
export default function HashPage() {
// Create list of 5000 items that all have unique id
const items = Array.from({ length: 5000 }, (_, i) => ({ id: i }))
return (
<div style={{ fontFamily: 'sans-serif', fontSize: '16px' }}>
<p>Hash Page</p>
<Link... | id="link-to-top">
To Top
</Link>
<Link href="/hash#non-existent" id="link-to-non-existent">
To non-existent
</Link>
<div>
{items.map((item) => (
<div key={item.id}>
<div id={`hash-${item | >
To 160
</Link>
<Link href="/hash#hash-300" id="link-to-300">
To 300
</Link>
<Link href="#hash-500" id="link-to-500">
To 500 (hash only)
</Link>
<Link href="/hash#top" | {
"filepath": "test/e2e/app-dir/navigation/app/hash-with-scroll-offset/page.js",
"language": "javascript",
"file_size": 1082,
"cut_index": 515,
"middle_length": 229
} |
import Link from 'next/link'
import { useEffect, useRef } from 'react'
export default function Page() {
const prefetchRef = useRef()
const slowPageRef = useRef()
useEffect(() => {
function triggerPrefetch() {
const event = new MouseEvent('mouseover', {
view: window,
bubbles: true,
... | 1000)
}, [])
return (
<>
<Link id="link-to-slow-page" href="/slow-page" ref={slowPageRef}>
To /slow-page
</Link>
<Link id="prefetch-link" href="/hash" ref={prefetchRef}>
Prefetch link
</Link>
</>
)
}
| fetch()
}, | {
"filepath": "test/e2e/app-dir/navigation/app/mpa-nav-test/page.js",
"language": "javascript",
"file_size": 794,
"cut_index": 524,
"middle_length": 14
} |
Link from 'next/link'
import './global.css'
export default function HashPage() {
// Create list of 5000 items that all have unique id
const items = Array.from({ length: 5000 }, (_, i) => ({ id: i }))
return (
<div style={{ fontFamily: 'sans-serif', fontSize: '16px' }}>
<p>Hash Page</p>
<Link hr... | "link-to-top">
To Top
</Link>
<Link href="/hash#non-existent" id="link-to-non-existent">
To non-existent
</Link>
<div>
<Link href="?with-query-param#hash-160" id="link-to-query-param">
To 160 (with | To 160
</Link>
<Link href="/hash#hash-300" id="link-to-300">
To 300
</Link>
<Link href="#hash-500" id="link-to-500">
To 500 (hash only)
</Link>
<Link href="/hash#top" id= | {
"filepath": "test/e2e/app-dir/navigation/app/hash/page.js",
"language": "javascript",
"file_size": 1233,
"cut_index": 518,
"middle_length": 229
} |
from 'next/link'
import '../hash/global.css'
export default function HashPage() {
// Create list of 5000 items that all have unique id
const items = Array.from({ length: 5000 }, (_, i) => ({ id: i }))
return (
<div style={{ fontFamily: 'sans-serif', fontSize: '16px' }}>
<p>Hash Page</p>
<Link hr... | <div>
<div id={`hash-${item.id}`}>{item.id}</div>
</div>
<div key="to-other-page">
<div>
<Link
href="/hash-link-back-to-same-page/o | Link href="/hash-link-back-to-same-page#hash-160" id="link-to-160">
To 160
</Link>
<div>
{items.map((item) => {
if (item.id === 160) {
return (
<div key={item.id}>
| {
"filepath": "test/e2e/app-dir/navigation/app/hash-link-back-to-same-page/page.js",
"language": "javascript",
"file_size": 1419,
"cut_index": 524,
"middle_length": 229
} |
} from 'react'
import { notFound } from 'next/navigation'
function createSuspenseyComponent(Component, { timeout = 0, expire = 10 }) {
let result
let promise
return function Data() {
if (result) return result
if (!promise)
promise = new Promise((resolve) => {
setTimeout(() => {
r... | return <></>
}
const SuspenseyNotFound = createSuspenseyComponent(NotFound, {
timeout: 300,
})
export default function () {
return (
<div className="suspense">
<Suspense fallback="fallback">
<SuspenseyNotFound />
</Suspense> | w promise
}
}
function NotFound() {
notFound()
| {
"filepath": "test/e2e/app-dir/navigation/app/not-found/suspense/page.js",
"language": "javascript",
"file_size": 855,
"cut_index": 529,
"middle_length": 52
} |
from 'react'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { useEffect, useTransition } from 'react'
let listening = false
let startedNavigating = false
export default function Page({ params }) {
if (typeof window === 'undefined') {
throw new Error('Client render only')
}
... | sionStorage.setItem(`${storageKey}/lastIsPending`, isPending)
}
})
// Read all matching logs and print them
let storage = Object.fromEntries(
Object.entries(sessionStorage).flatMap(([key, value]) =>
key.startsWith(`${storageKey}/`)
|
}
// Log every pathname+searchParams we've seen
sessionStorage.setItem(`${storageKey}/path-${path}`, 'true')
let [isPending, startTransition] = useTransition()
useEffect(() => {
if (startedNavigating) {
ses | {
"filepath": "test/e2e/app-dir/navigation/app/external-push/[storageKey]/page.js",
"language": "javascript",
"file_size": 2062,
"cut_index": 563,
"middle_length": 229
} |
getCategories = () => [
{
name: 'Electronics',
slug: 'electronics',
count: 11,
items: [
{ name: 'Phones', slug: 'phones', count: 4 },
{ name: 'Tablets', slug: 'tablets', count: 5 },
{ name: 'Laptops', slug: 'laptops', count: 2 },
],
},
{
name: 'Clothing',
slug: 'clot... | n', count: 3 },
],
},
{
name: 'Shoes',
slug: 'shoes',
count: 5,
items: [],
prefetch: false,
},
]
export async function fetchCategoryBySlug(slug) {
// Assuming it always return expected categories
return getCategories().fi | },
{
name: 'Books',
slug: 'books',
count: 10,
items: [
{ name: 'Fiction', slug: 'fiction', count: 5 },
{ name: 'Biography', slug: 'biography', count: 2 },
{ name: 'Education', slug: 'educatio | {
"filepath": "test/e2e/app-dir/navigation/app/nested-navigation/getCategories.js",
"language": "javascript",
"file_size": 1450,
"cut_index": 524,
"middle_length": 229
} |
t from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
const HashChanges = () => {
const router = useRouter()
return (
<div id="hash-changes-page">
<div>
<Link href="#via-link" id="via-link">
Via Link
</Link>
</div>
<div>
<a ... | ink>
</div>
<div>
<Link
href="#name-item-400"
scroll={false}
id="scroll-to-name-item-400-no-scroll"
>
Go to name item 400 (no scroll)
</Link>
</div>
<div>
<Li | <Link href="#item-400" id="scroll-to-item-400">
Go to item 400
</Link>
</div>
<div>
<Link href="#name-item-400" id="scroll-to-name-item-400">
Go to name item 400
</L | {
"filepath": "test/e2e/app-dir/navigation/app/hash-changes/page.js",
"language": "javascript",
"file_size": 1623,
"cut_index": 537,
"middle_length": 229
} |
} from 'e2e-utils'
import cheerio from 'cheerio'
import { retry } from 'next-test-utils'
const { i18n } = require('./next.config')
const urls = [
// Include the app page without a locale.
...(global.isNextDeploy
? []
: [
// TODO: enable for deploy mode when behavior is corrected
{
... | lt
// locale).
{
pathname: '/about',
expected: {
pathname: `/${i18n.defaultLocale}/about`,
page: '/pages/about.js',
},
},
// Include the locale prefixed urls for the pages page (should resolve).
...i18n.locales.map((local | e app pages with locales (should not resolve).
...i18n.locales.map((locale) => ({
pathname: `/${locale}/blog/first-post`,
expected: null,
})),
// Include the pages page without a locale (should default to the defau | {
"filepath": "test/e2e/app-dir/i18n-hybrid/i18n-hybrid.test.ts",
"language": "typescript",
"file_size": 2124,
"cut_index": 563,
"middle_length": 229
} |
from 'e2e-utils'
import stripAnsi from 'strip-ansi'
describe('proxy-runtime', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
skipStart: true,
})
if (skipped) {
return
}
it('should error when proxy file has runtime config export', async (... | CLI output.
if (process.env.IS_TURBOPACK_TEST && !isNextDev) {
expect(stripAnsi(cliOutput)).toContain(`proxy.ts:3:14
Next.js can't recognize the exported \`config\` field in route. Proxy does not support Edge runtime.
1 | export default functi | ait next.browser('/').catch(() => {})
cliOutput = next.cliOutput
} else {
cliOutput = (await next.build()).cliOutput
}
// TODO: Investigate why in dev-turbo, the error is shown in the browser console, not | {
"filepath": "test/e2e/app-dir/proxy-runtime/proxy-runtime.test.ts",
"language": "typescript",
"file_size": 1551,
"cut_index": 537,
"middle_length": 229
} |
check } from 'next-test-utils'
describe('parallel-routes-catchall', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should match correctly when defining an explicit page & slot', async () => {
const browser = await next.browser('/')
await check(() => browser.elementById('slot').tex... | page but no slot', async () => {
const browser = await next.browser('/')
await check(() => browser.elementById('slot').text(), /@slot default/)
await browser.elementByCss('[href="/bar"]').click()
// bar has defined a slot but no page rou | ot content & the page content
await check(() => browser.elementById('children').text(), /foo/)
await check(() => browser.elementById('slot').text(), /foo slot/)
})
it('should match correctly when defining an explicit | {
"filepath": "test/e2e/app-dir/parallel-routes-catchall/parallel-routes-catchall.test.ts",
"language": "typescript",
"file_size": 2542,
"cut_index": 563,
"middle_length": 229
} |
xtTestSetup } from 'e2e-utils'
describe('adapter-dynamic-metadata', () => {
const { next, isNextDev, isNextDeploy } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
it('should skip next dev', () => {})
return
}
if (!isNextDeploy) {
it('should classify dynamic metadata routes as app r... | = outputs.prerenders.map((item) => item.pathname)
const appRoutePathnames = outputs.appRoutes.map((item) => item.pathname)
expect(staticFilePathnames).toEqual(
expect.not.arrayContaining(expectedDynamicMetadataRoutes)
)
exp | cMetadataRoutes = [
'/robots.txt',
'/sitemap.xml',
'/favicon.ico',
]
const staticFilePathnames = outputs.staticFiles.map(
(item) => item.pathname
)
const prerenderPathnames | {
"filepath": "test/e2e/app-dir/adapter-dynamic-metadata/adapter-dynamic-metadata.test.ts",
"language": "typescript",
"file_size": 2232,
"cut_index": 563,
"middle_length": 229
} |
leRef(path.resolve(__dirname, 'packages')),
'pnpm-workspace.yaml': `packages:
- 'apps/*'
- 'packages/*'
`,
},
packageJson: require('./package.json'),
buildCommand: 'pnpm build',
startCommand: (global as any).isNextDev ? 'pnpm dev' : 'pnpm start',
installCommand: 'pnpm i',
... | cript')
})
it('should work on client-side', async () => {
const browser = await next.browser('/monorepo-package-ssr')
expect(await browser.elementByCss('p').text()).toBe('Hello Typescript')
await waitForNoRedbox(browser)
ex | o-package-rsc')
expect($('p').text()).toBe('Hello Typescript')
})
it('should work during SSR', async () => {
const $ = await next.render$('/monorepo-package-ssr')
expect($('p').text()).toBe('Hello Types | {
"filepath": "test/e2e/app-dir/non-root-project-monorepo/non-root-project-monorepo.test.ts",
"language": "typescript",
"file_size": 11692,
"cut_index": 921,
"middle_length": 229
} |
p } from 'e2e-utils'
import { splitResponseWithPPRSentinel } from 'e2e-utils/ppr'
const isAdapterTest = Boolean(process.env.NEXT_ENABLE_ADAPTER)
describe('partial-fallback-root-blocking', () => {
const { next, isNextDev, isNextDeploy } = nextTestSetup({
files: __dirname,
// The latest changes to support thi... | ync () => {
response = await next.fetch(pathname)
expect(response.status).toBe(200)
if (!response.body) {
throw new Error(`Expected a streamed response body for ${pathname}`)
}
return response.body
| () => {})
return
}
async function fetchSplitHTML(pathname: string) {
let response: Awaited<ReturnType<typeof next.fetch>> | undefined
const [staticPart, dynamicPart] = await splitResponseWithPPRSentinel(
as | {
"filepath": "test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts",
"language": "typescript",
"file_size": 2593,
"cut_index": 563,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
describe('app dir - search params keys', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should keep the React router instance the same when changing the search params', async () => {
const browser = await next.brows... | await browser.waitForElementByCss('#count').text()
return newSearchParams !== searchParams && count === '2'
? 'success'
: 'retry'
}, 'success')
await browser.elementByCss('#increment').click()
await browser.elementByCss | '#increment').click()
await browser.elementByCss('#push').click()
await check(async () => {
const newSearchParams = await browser
.waitForElementByCss('#search-params')
.text()
const count = | {
"filepath": "test/e2e/app-dir/search-params-react-key/layout-params.test.ts",
"language": "typescript",
"file_size": 1421,
"cut_index": 524,
"middle_length": 229
} |
e,
skipDeployment: true,
})
if (skipped) {
return
}
if (isNextDev) {
it('should update cached data after editing a file', async () => {
const browser = await next.browser('/')
const [initialFetchedRandom, initialText, initialMathRandom] =
await Promise.all([
browser.... | content.replace('foo', 'bar')
)
let newFetchedRandom: string
let newText: string
let newMathRandom: string
await retry(async () => {
;[newFetchedRandom, newText, newMathRandom] = await Promise.all([
| 0,1]\.\d+/)
expect(initialText).toBe('foo')
expect(initialMathRandom).toMatch(/[0,1]\.\d+/)
// Edit something inside of "use cache" in the page.tsx file.
await next.patchFile('app/page.tsx', (content) =>
| {
"filepath": "test/e2e/app-dir/use-cache-dev/use-cache-dev.test.ts",
"language": "typescript",
"file_size": 8400,
"cut_index": 716,
"middle_length": 229
} |
import { revalidatePath } from 'next/cache'
import Link from 'next/link'
async function getRandomValue() {
'use cache'
return Math.random()
}
async function getData() {
'use cache'
return fetch('https://next-data-api-endpoint.vercel.app/api/random').then(
(res) =>
res
.text()
.then... |
action={async () => {
'use server'
revalidatePath('/')
}}
>
<button id="revalidate">Revalidate</button>
</form>
<p>
<Link href="/some/path">Go to /some/path</Link>
</p>
</>
| <div id="container">
<p id="fetchedRandom">{fetchedRandom}</p>
<p id="text">{text}</p>
<p id="mathRandom">{mathRandom}</p>
</div>
<p id="uncached">{new Date().toISOString()}</p>
<form | {
"filepath": "test/e2e/app-dir/use-cache-dev/app/page.tsx",
"language": "tsx",
"file_size": 1001,
"cut_index": 512,
"middle_length": 229
} |
`) was passed to startActiveSpan which means it will receive a Span argument with a possibly random ID on every invocation leading to cache misses. Provide a wrapping function around the Cache Function that does not forward the Span argument to avoid this issue.",
"environmentLabel": "Cache",
"lab... | it expect(browser).toDisplayCollapsedRedbox(`
{
"code": "E394",
"description": "A Cache Function (\`use cache\`) was passed to startActiveSpan which means it will receive a Span argument with a possibly random ID on every inv | ^",
"stack": [
"<anonymous> app/traced-work.tsx (26:19)",
"Inner app/traced-work.tsx (97:26)",
"Page <anonymous>",
],
}
`)
} else {
awa | {
"filepath": "test/e2e/app-dir/cache-components-allow-otel-spans/cache-components-allow-otel-spans.test.ts",
"language": "typescript",
"file_size": 17636,
"cut_index": 1331,
"middle_length": 229
} |
lt function Page() {
return (
<main>
<h1>OTel Cache Components Compat Test</h1>
<p>
Span generation causes random IDs to be created. There is a tradeoff
with this while prerendering since sync IO like Math.random() should be
excluded from static prerenders but spans are so wide... | ssed into Cache Functions for proper functioning of Cache
Components.
</p>
<ul>
<li>
<a href="/novel/cache">
"use cache" Page without build-time prerendering
</a>
</li>
<li>
| ans are constructed. However it is possible for the span
object to be passed to a Cache Component where the random ID will cause
cache misses while prerendering. It is important that Span objects not
be pa | {
"filepath": "test/e2e/app-dir/cache-components-allow-otel-spans/app/page.tsx",
"language": "tsx",
"file_size": 1429,
"cut_index": 524,
"middle_length": 229
} |
function asyncWork() {
await new Promise((resolve) => setTimeout(resolve, 1000))
return 42
}
async function cachedAsyncWork() {
'use cache'
return asyncWork()
}
function withSpan(fn) {
return function () {
const tracer = trace.getTracer('tracer-manual-span')
const span = tracer.startSpan('span-manu... | pan = withSpan(cachedAsyncWork)
const cachedAsyncWorkWithActiveSpan = withActiveSpan(cachedAsyncWork)
export function CachedInnerTraceManualSpan() {
async function Inner() {
const result = await cachedAsyncWorkWithManualSpan()
return <p classNam | 'tracer-active-span')
return tracer.startActiveSpan('span-active-span', fn)
}
}
const asyncWorkWithManualSpan = withSpan(asyncWork)
const asyncWorkWithActiveSpan = withActiveSpan(asyncWork)
const cachedAsyncWorkWithManualS | {
"filepath": "test/e2e/app-dir/cache-components-allow-otel-spans/app/traced-work.tsx",
"language": "tsx",
"file_size": 4500,
"cut_index": 614,
"middle_length": 229
} |
InnerTraceManualSpan,
InnerTraceManualSpan,
CachedTracedComponentManualSpan,
TracedComponentManualSpan,
CachedInnerTraceActiveSpan,
InnerTraceActiveSpan,
CachedTracedComponentActiveSpan,
TracedComponentActiveSpan,
} from '../../traced-work'
export function generateStaticParams() {
return [{ slug: 'prer... | Span />
<InnerTraceManualSpan />
<CachedTracedComponentManualSpan />
<TracedComponentManualSpan />
<CachedInnerTraceActiveSpan />
<InnerTraceActiveSpan />
<CachedTracedComponentActiveSpan />
<TracedComponentActiveS | se server" scope</div>
<CachedInnerTraceManual | {
"filepath": "test/e2e/app-dir/cache-components-allow-otel-spans/app/[slug]/fallback/page.tsx",
"language": "tsx",
"file_size": 858,
"cut_index": 529,
"middle_length": 52
} |
raceManualSpan,
CachedTracedComponentManualSpan,
TracedComponentManualSpan,
CachedInnerTraceActiveSpan,
InnerTraceActiveSpan,
CachedTracedComponentActiveSpan,
TracedComponentActiveSpan,
} from '../../traced-work'
export function generateStaticParams() {
return [{ slug: 'prerendered' }]
}
export default ... | nerTraceManualSpan />
<CachedTracedComponentManualSpan />
<TracedComponentManualSpan />
<CachedInnerTraceActiveSpan />
<InnerTraceActiveSpan />
<CachedTracedComponentActiveSpan />
<TracedComponentActiveSpan />
</>
| /div>
<CachedInnerTraceManualSpan />
<In | {
"filepath": "test/e2e/app-dir/cache-components-allow-otel-spans/app/[slug]/cache/page.tsx",
"language": "tsx",
"file_size": 871,
"cut_index": 559,
"middle_length": 52
} |
InnerTraceManualSpan,
InnerTraceManualSpan,
CachedTracedComponentManualSpan,
TracedComponentManualSpan,
CachedInnerTraceActiveSpan,
InnerTraceActiveSpan,
CachedTracedComponentActiveSpan,
TracedComponentActiveSpan,
} from '../../traced-work'
export function generateStaticParams() {
return [{ slug: 'prer... | Span />
<InnerTraceManualSpan />
<CachedTracedComponentManualSpan />
<TracedComponentManualSpan />
<CachedInnerTraceActiveSpan />
<InnerTraceActiveSpan />
<CachedTracedComponentActiveSpan />
<TracedComponentActiveS | se server" scope</div>
<CachedInnerTraceManual | {
"filepath": "test/e2e/app-dir/cache-components-allow-otel-spans/app/[slug]/server/page.tsx",
"language": "tsx",
"file_size": 858,
"cut_index": 529,
"middle_length": 52
} |
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('proxy-with-middleware', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
skipStart: true,
})
if (skipped) {
return
}
it('should error when both mid... | tDev) {
await next.start().catch(() => {})
await retry(async () => {
expect(next.cliOutput).toContain(message)
})
} else {
const { cliOutput } = await next.build()
expect(cliOutput).toContain(message)
}
})
}) |
if (isNex | {
"filepath": "test/e2e/app-dir/proxy-with-middleware/proxy-with-middleware.test.ts",
"language": "typescript",
"file_size": 783,
"cut_index": 512,
"middle_length": 14
} |
as cheerio from 'cheerio'
const isAdapterTest = Boolean(process.env.NEXT_ENABLE_ADAPTER)
describe('sub-shell-generation', () => {
const { next, isNextDev, isNextDeploy } = nextTestSetup({
files: __dirname,
// The latest changes to support this behavior on deployed infra are available in the adapter,
// ... | ['/es/1', '/es/2'],
true,
],
[
'/en/[slug]',
{
page: 'Page: (runtime)',
langLayout: 'Lang Layout: (buildtime)',
rootLayout: 'Root Layout: (buildtime)',
},
['/en/1', ' | rect shell', () => {
describe.each([
[
'/[lang]/[slug]',
{
page: 'Page: (runtime)',
langLayout: 'Lang Layout: (runtime)',
rootLayout: 'Root Layout: (buildtime)',
},
| {
"filepath": "test/e2e/app-dir/sub-shell-generation/sub-shell-generation.test.ts",
"language": "typescript",
"file_size": 2275,
"cut_index": 563,
"middle_length": 229
} |
deredAt1).toBe(renderedAt2)
} else {
// Should be re-rendered.
expect(renderedAt1).toBeLessThan(renderedAt2)
}
}
describe('Switchable runtime', () => {
let context
if ((global as any).isNextDeploy) {
// TODO-APP: re-enable after Prerenders are handled on deploy
it('should skip for deploy tempo... | fest', async () => {
const res = await fetchViaHTTP(
next.url,
`/_next/static/${next.buildId}/_devMiddlewareManifest.json`
)
const devMiddlewareManifest = await res.json()
expect(devMiddlewareManifest).to | estDir,
stdout: '',
stderr: '',
}
})
if ((global as any).isNextDev) {
describe('Switchable runtime (dev)', () => {
it('should not include edge api routes and edge ssr routes into dev middleware mani | {
"filepath": "test/e2e/switchable-runtime/index.test.ts",
"language": "typescript",
"file_size": 20780,
"cut_index": 1331,
"middle_length": 229
} |
om 'e2e-utils'
describe('parallel-routes-leaf-segments-no-build-error', () => {
const { next } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'no-build-error'),
})
it('should build successfully without default.tsx for leaf segments', async () => {
// This test verifies that the build does not... | th all parallel slots', async () => {
const $ = await next.render$('/leaf-segment')
// Verify main page content
expect($('h2').text()).toBe('Leaf Segment Page')
expect($('.main p').first().text()).toContain(
'This is a leaf | cludes('MissingDefaultParallelRouteError')) {
throw new Error('MissingDefaultParallelRouteError was thrown')
}
})
describe('leaf segment without child routes', () => {
it('should render the leaf segment page wi | {
"filepath": "test/e2e/app-dir/parallel-routes-leaf-segments/parallel-routes-leaf-segments.no-build-error.test.ts",
"language": "typescript",
"file_size": 2856,
"cut_index": 563,
"middle_length": 229
} |
from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('after during server shutdown - next start', () => {
const { next, skipped, isNextDev } = nextTestSetup({
files: __dirname,
skipDeployment: true, // the tests use cli logs
skipStart: true,
})
if (skipped) {
return
}
beforeEach... | it for after callbacks when the server receives %s',
async (signal) => {
await next.render('/')
await retry(async () => {
expect(next.cliOutput).toInclude('[after] starting sleep')
})
await next.stop(signal)
| ev) {
// `next dev` shuts down the child process that runs the server without waiting for cleanups,
// so `after` callbacks won't have the chance to complete
it.each(['SIGINT', 'SIGTERM'] as const)(
'does not wa | {
"filepath": "test/e2e/app-dir/graceful-shutdown-next-after/next-start/index.test.ts",
"language": "typescript",
"file_size": 1531,
"cut_index": 537,
"middle_length": 229
} |
= process.env.__NEXT_CACHE_COMPONENTS === 'true'
// Skip PPR test as it's covered in test/e2e/app-dir/ppr-metadata-streaming/ppr-metadata-streaming.test.ts
;(isPPREnabled ? describe.skip : describe)(
'app-dir - metadata-streaming-static-generation',
() => {
const { next, isNextDev, isNextStart } = nextTestSetu... | )
const staticRoutes = prerenderManifest.routes
expect(Object.keys(staticRoutes).sort()).toEqual([
'/',
'/_global-error',
'/_not-found',
'/slow/static',
'/suspenseful/static',
] | routes
// are all listed in the prerender manifest.
it('should generate all pages static', async () => {
const prerenderManifest = JSON.parse(
await next.readFile('.next/prerender-manifest.json')
| {
"filepath": "test/e2e/app-dir/metadata-streaming-static-generation/metadata-streaming-static-generation.test.ts",
"language": "typescript",
"file_size": 4468,
"cut_index": 614,
"middle_length": 229
} |
ev, isTurbopack, isRspack } = nextTestSetup({
files: __dirname,
skipStart: process.env.NEXT_TEST_MODE !== 'dev',
skipDeployment: true,
})
if (skipped) {
return
}
it("it should error when using segment configs that aren't supported by useCache", async () => {
if (isNextDev) {
const br... | )
Route segment config "runtime" is not compatible with \`nextConfig.experimental.useCache\`. Please remove it.
> 1 | export const runtime = 'edge'
| ^^^^^^^",
"stack": [],
}
`)
| segment config "runtime" is not compatible with \`nextConfig.experimental.useCache\`. Please remove it.",
"environmentLabel": null,
"label": "Build Error",
"source": "./app/runtime/page.tsx (1:14 | {
"filepath": "test/e2e/app-dir/use-cache-segment-configs/use-cache-segment-configs.test.ts",
"language": "typescript",
"file_size": 5939,
"cut_index": 716,
"middle_length": 229
} |
import { nextTestSetup } from 'e2e-utils'
import { waitFor } from 'next-test-utils'
describe('app-prefetch-static', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
it('should skip next dev', () => {})
return
}
it('should correctly navigate between stati... | s('#dynamic-prefetch-page').text()).toBe(
'Hello from Dynamic Prefetch Page'
)
await browser.elementByCss('#static-prefetch').click()
expect(await browser.elementByCss('#static-prefetch-page').text()).toBe(
'Hello from Static Pref | lick()
expect(await browser.elementByCss('#static-prefetch-page').text()).toBe(
'Hello from Static Prefetch Page'
)
await browser.elementByCss('#dynamic-prefetch').click()
expect(await browser.elementByCs | {
"filepath": "test/e2e/app-dir/app-prefetch-static/app-prefetch-static.test.ts",
"language": "typescript",
"file_size": 1022,
"cut_index": 512,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
describe('turbo-resolve-extensions', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should SSR', async () => {
const res = await next.fetch('/')
const html = await res.text()
expect(html).toContain('hello world')
expect(html).toContain('hello ... | nc () => {
// When both PlatformComponent.web.tsx and PlatformComponent.tsx exist,
// the .web.tsx variant must win because it appears first in resolveExtensions.
// This guards against a Turbopack bug where the alternative index was
// har | ')
const text = await browser.elementByCss('body').text()
expect(text).toContain('hello world')
expect(text).toContain('hello client')
})
it('should respect resolveExtensions priority (.web.tsx before .tsx)', asy | {
"filepath": "test/e2e/app-dir/resolve-extensions/resolve-extensions.test.ts",
"language": "typescript",
"file_size": 1338,
"cut_index": 524,
"middle_length": 229
} |
nd-interception-nested-dynamic-routes', () => {
const { next } = nextTestSetup({
files: __dirname,
// TODO: re-enable when resolved related thread
// https://vercel.slack.com/archives/C07UCHRBWGK/p1759165345308879
skipDeployment: true,
})
it('should intercept the route for nested dynamic routes',... | r.waitForElementByCss('p').text()).toBe('intercepted!')
// Should preserve the previous component.
expect(await browser.elementByCss('h1').text()).toBe('foo id 1, bar id 1')
await browser.refresh()
// Should display the correct /baz_id/1 c | Should intercept the route.
expect(await browse | {
"filepath": "test/e2e/app-dir/parallel-routes-and-interception-nested-dynamic-routes/parallel-routes-and-interception-nested-dynamic-routes.test.ts",
"language": "typescript",
"file_size": 981,
"cut_index": 582,
"middle_length": 52
} |
('css-media-query', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should preserve max-width media query syntax instead of transpiling to range syntax', async () => {
const browser = await next.browser('/')
// Get all stylesheets from the document
const stylesheetContents = aw... | contents.push(rule.cssText)
}
}
} catch (e) {
// Skip stylesheets we can't access due to CORS
continue
}
}
return contents
})
// Find the media query rule
const mediaQueryR | / Only check stylesheets that have cssRules (not external ones we can't access)
if (stylesheet.cssRules) {
const rules = Array.from(stylesheet.cssRules)
for (const rule of rules) {
| {
"filepath": "test/e2e/app-dir/css-media-query/css-media-query.test.ts",
"language": "typescript",
"file_size": 2313,
"cut_index": 563,
"middle_length": 229
} |
import { nextTestSetup } from 'e2e-utils'
describe('next-image-legacy-src-with-query-without-local-patterns', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
it('should throw error for relative ... | liOutput } = await next.build()
expect(cliOutput).toContain(
'Image with src "/test.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpa | 'Image with src "/test.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns'
)
} else {
const { c | {
"filepath": "test/e2e/app-dir/next-image-legacy-src-with-query-without-local-patterns/next-image-legacy-src-with-query-without-local-patterns.test.ts",
"language": "typescript",
"file_size": 1027,
"cut_index": 512,
"middle_length": 229
} |
error after reset', async () => {
const browser = await next.browser('/client-component')
// Try triggering and resetting a few times in a row
for (let i = 0; i < 5; i++) {
await browser
.elementByCss('#error-trigger-button')
.click()
.waitForElementByCss('#error-boundary-mes... | unstable_retry', async () => {
const browser = await next.browser('/client-component')
// Try triggering and retrying a few times in a row
for (let i = 0; i < 5; i++) {
await browser
.elementByCss('#error-trigger-button')
| .waitForElementByCss('#error-trigger-button')
expect(await browser.elementByCss('#error-trigger-button').text()).toBe(
'Trigger Error!'
)
}
})
it('should recover Client Component error after | {
"filepath": "test/e2e/app-dir/catch-error/catch-error.test.ts",
"language": "typescript",
"file_size": 5441,
"cut_index": 716,
"middle_length": 229
} |
waitForRedbox,
waitForNoRedbox,
getRedboxDescription,
} from 'next-test-utils'
describe('app dir - forbidden with default forbidden boundary', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
// TODO: error for... | // TODO: error forbidden usage in root layout
it.skip('should error on server forbidden from root layout on server-side', async () => {
const browser = await next.browser('/?root-forbidden=1')
if (isNextDev) {
await waitForRedbox(browser)
| '#trigger-forbidden').click()
if (isNextDev) {
await waitForRedbox(browser)
expect(await getRedboxDescription(browser)).toMatch(
/forbidden\(\) is not allowed to use in root layout/
)
}
})
| {
"filepath": "test/e2e/app-dir/forbidden/default/forbidden-default.test.ts",
"language": "typescript",
"file_size": 2536,
"cut_index": 563,
"middle_length": 229
} |
during rendering', async () => {
const pageErrors: unknown[] = []
const browser = await next.browser('/client-component', {
beforePageLoad: (page) => {
page.on('pageerror', (error: unknown) => {
pageErrors.push(error)
})
},
})
await browser.element... | ed: this is a test')
}
// Handled by custom error boundary.
expect(pageErrors).toEqual([])
})
it('should trigger error component when undefined is thrown from a client component in the browser', async () => {
const pageErr | box(browser)
// expect(await getRedboxHeader(browser)).toMatch(/this is a test/)
} else {
expect(
await browser.waitForElementByCss('#error-boundary-message').text()
).toBe('An error occurr | {
"filepath": "test/e2e/app-dir/errors/index.test.ts",
"language": "typescript",
"file_size": 16718,
"cut_index": 921,
"middle_length": 229
} |
Setup } from 'e2e-utils'
describe('next-dist-client-esm-import', () => {
const dependencies = require('./package.json').dependencies
if ((global as any).isNextDeploy) {
// The `link:` protocol is incompatible with the npm version that's used
// when this test is deployed, so we use `file:` instead.
de... | // The filename for the client component module that's imported in this
// fixture is: <node_modules>/@monorepo/adapter-next/dist/client/index.js
const browser = await next.browser('/')
expect(await browser.elementByCss('p').text()).toBe('he | ext/dist/client" in their filename', async () => {
| {
"filepath": "test/e2e/app-dir/next-dist-client-esm-import/next-dist-client-esm-import.test.ts",
"language": "typescript",
"file_size": 857,
"cut_index": 529,
"middle_length": 52
} |
tTestSetup } from 'e2e-utils'
import fs from 'fs'
import path from 'path'
// This test verifies a case when the "proxy.ts" bundle is being traced into the NFT file as "proxy.js".
// As Next.js renames "proxy.js" to "middleware.js" during webpack build, the files in NFT will differ
// from the actual outputs, which wil... | () => {
const nfc = JSON.parse(
fs.readFileSync(
path.join(next.testDir, '.next/server/middleware.js.nft.json'),
'utf-8'
)
)
expect(nfc.files).toContain('middleware.js')
expect(nfc.files).not.toC | })
// 'middleware.js' won't be traced because Turbopack doesn't bundle all code to .next/server/middleware.js
if (isNextStart && !isTurbopack) {
it('should have renamed trace file as middleware instead of proxy', async | {
"filepath": "test/e2e/app-dir/proxy-nfc-traced/proxy-nfc-traced.test.ts",
"language": "typescript",
"file_size": 1300,
"cut_index": 524,
"middle_length": 229
} |
node:fs/promises'
const errorMessage = `This function is what Next.js runs for every request handled by this proxy (previously called middleware).
Why this happens:
- You are migrating from \`middleware\` to \`proxy\`, but haven't updated the exported function.
- The file exists but doesn't export a function.
- The e... | skipStart: true,
})
if (skipped) {
return
}
it('should error when proxy file has invalid export named middleware', async () => {
await writeFile(
join(next.testDir, 'proxy.ts'),
'export function middleware() {}'
)
let | tion export.
Learn more: https://nextjs.org/docs/messages/middleware-to-proxy`
describe('proxy-missing-export', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
| {
"filepath": "test/e2e/app-dir/proxy-missing-export/proxy-missing-export.test.ts",
"language": "typescript",
"file_size": 4400,
"cut_index": 614,
"middle_length": 229
} |
extDev, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('after during server shutdown - custom server', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
startCommand: 'node server.mjs',
serverReadyPattern: /Custom server started/,
forcedPort: 'rand... | // unlike the above test for `next dev`, NextCustomServer has no logic that'd cause it to skip cleanups in dev mode,
// so this is the same in both modes
it.each(['SIGINT', 'SIGTERM'] as const)(
'waits for after callbacks when the server receives | })
if (skipped) {
return
}
beforeEach(async () => {
await next.start()
})
afterEach(async () => {
// if the test didn't manage to kill next, we should do it ourselves
await next.stop()
}, 10_000)
| {
"filepath": "test/e2e/app-dir/graceful-shutdown-next-after/custom-server/index.test.ts",
"language": "typescript",
"file_size": 1284,
"cut_index": 524,
"middle_length": 229
} |
import { nextTestSetup } from 'e2e-utils'
describe('hello-world', () => {
const { next } = nextTestSetup({
files: __dirname,
})
// Recommended for tests that check HTML. Cheerio is a HTML parser that has a jQuery like API.
it('should work using cheerio', async () => {
const $ = await next.render$('/')... | ender('/')
expect(html).toContain('hello world')
})
// In case you need to test the response object.
it('should work with fetch', async () => {
const res = await next.fetch('/')
const html = await res.text()
expect(html).toContain('h | ('/')
expect(await browser.elementByCss('p').text()).toBe('hello world')
})
// In case you need the full HTML. Can also use $.html() with cheerio.
it('should work with html', async () => {
const html = await next.r | {
"filepath": "test/e2e/app-dir/hello-world/hello-world.test.ts",
"language": "typescript",
"file_size": 1018,
"cut_index": 512,
"middle_length": 229
} |
e NextInstance, nextTestSetup } from 'e2e-utils'
import type { Response } from 'node-fetch'
async function getLastModifiedTime(next: NextInstance, pathname: string) {
const content = await (await next.fetch(pathname)).text()
return content.match(/<lastmod>([^<]+)<\/lastmod>/)[1]
}
function assertSitemapResponse(r... | , 'sitemap/0.xml')
const secondTime = await getLastModifiedTime(next, 'sitemap/0.xml')
expect(firstTime).not.toEqual(secondTime)
})
it('should be able to call while generating multiple dynamic sitemaps', async () => {
const res0 = await n | } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
it('should render sitemap with generateSitemaps in force-dynamic config dynamically', async () => {
const firstTime = await getLastModifiedTime(next | {
"filepath": "test/e2e/app-dir/dynamic-in-generate-params/index.test.ts",
"language": "typescript",
"file_size": 1434,
"cut_index": 524,
"middle_length": 229
} |
, isNextDev, skipped } = nextTestSetup({
files: __dirname + '/fixtures/cache-components',
skipDeployment: true,
})
if (skipped) {
return
}
it('should make content after io() dynamic during prerender', async () => {
const $ = await next.render$('/io-boundary')
if (isNextDev) {
// In d... | // hanging promise prevented it from executing during the build prerender.
expect($('#before').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at buildtime')
expect($('#after-io').text()).toBe('at runtime')
}
})
| me')
} else {
// In production with cache components, io() creates a dynamic
// boundary. Content in the static shell is rendered at buildtime.
// Content after io() is rendered at request time because the
| {
"filepath": "test/e2e/app-dir/io/io.test.ts",
"language": "typescript",
"file_size": 3514,
"cut_index": 614,
"middle_length": 229
} |
p the test for now. Need to address react/compiler-runtime
// compatibility with React below 19.
// _describe for cleaner git history.
const _describe = isReact18 ? describe.skip : describe
_describe('app-dir - unstable_catchError with react compiler', () => {
const { next, isNextDev } = nextTestSetup({
files: _... | er-button')
.click()
.waitForElementByCss('#error-boundary-message')
expect(await browser.elementByCss('#error-boundary-message').text()).toBe(
'this is a test'
)
await browser
.elementByCss('#reset')
| reset', async () => {
const browser = await next.browser('/client-component')
// Try triggering and resetting a few times in a row
for (let i = 0; i < 5; i++) {
await browser
.elementByCss('#error-trigg | {
"filepath": "test/e2e/app-dir/catch-error/catch-error-react-compiler.test.ts",
"language": "typescript",
"file_size": 3822,
"cut_index": 614,
"middle_length": 229
} |
State } from 'react'
import { unstable_catchError, type ErrorInfo } from 'next/error'
function ErrorFallback(
{ clearError }: { clearError: () => void },
{ error, reset, unstable_retry }: ErrorInfo
) {
const [retryError, setRetryError] = useState<string | null>(null)
return (
<>
<p id="pages-error-m... | Retry
</button>
{retryError ? <p id="pages-retry-error">{retryError}</p> : null}
</>
)
}
const ErrorBoundary = unstable_catchError(ErrorFallback)
function ErrorThrower({ shouldThrow }: { shouldThrow: boolean }) {
if (shouldThrow) {
|
<button
id="pages-retry"
onClick={() => {
try {
unstable_retry()
} catch (error) {
setRetryError((error as Error).message)
}
}}
>
| {
"filepath": "test/e2e/app-dir/catch-error/pages/pages-router.tsx",
"language": "tsx",
"file_size": 1421,
"cut_index": 524,
"middle_length": 229
} |
} from 'next/cache'
const getData = unstable_cache(
async () => {
const noStore = await fetch(
process.env.TEST_DATA_SERVER + '?cache=no-store',
{ method: 'GET', cache: 'no-store' }
).then((res) => res.text())
const forceCache = await fetch(
process.env.TEST_DATA_SERVER + '?cache=force... | forceCache,
noStore,
},
},
null,
2
)
},
undefined,
{
tags: ['unstable-cache-fetch'],
}
)
export default async function Page() {
const data = await getData()
return <pre id="data">{data}</pre>
}
| data: {
| {
"filepath": "test/e2e/app-dir/ppr-unstable-cache/app/page.jsx",
"language": "jsx",
"file_size": 806,
"cut_index": 536,
"middle_length": 14
} |
tTestSetup } from 'e2e-utils'
describe('app-dir - reexport-client-component-metadata', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should render the page metadata if override', async () => {
const $ = await next.render$('/override')
expect($('title').text()).toBe('Page 1')
... | ride', async () => {
const $ = await next.render$('/no-override')
expect($('title').text()).toBe('Root Layout')
expect($('meta[name="description"]').attr('content')).toBe(
'Root Description'
)
const browser = await next.browser(' | .text()).toBe('Page 1')
expect(
await browser
.elementByCss('meta[name="description"]')
.getAttribute('content')
).toBe('Page 1 Description')
})
it('should render the layout metadata if not over | {
"filepath": "test/e2e/app-dir/reexport-client-component-metadata/reexport-client-component-metadata.test.ts",
"language": "typescript",
"file_size": 1253,
"cut_index": 524,
"middle_length": 229
} |
path = require('path')
/** @type {import('next').NextConfig} */
const nextConfig = {
turbopack: {
rules: {
'*.mdx': {
loaders: [require.resolve('./test-file-loader.js')],
as: '*.js',
},
'*.txt': [
{
condition: { query: '?reverse' },
loaders: [require.... | nfig.module.rules.push({
resourceQuery: '?reverse',
use: require.resolve('./reverse-loader.js'),
})
config.module.rules.push({
resourceQuery: /\?upper/,
use: require.resolve('./upper-loader.js'),
})
config.resolve.al | '*.js',
},
],
},
resolveAlias: {
'@/*': './app/*',
},
},
webpack(config) {
config.module.rules.push({
test: /\.mdx/,
use: require.resolve('./test-file-loader.js'),
})
co | {
"filepath": "test/e2e/app-dir/webpack-loader-resource-query/next.config.js",
"language": "javascript",
"file_size": 1145,
"cut_index": 518,
"middle_length": 229
} |
NK_HEADER_SIZE = 111
/**
* Calculates the minimum header length that will be emitted by the server. This
* is calculated by taking the maximum header length and dividing it by the
* average header size including joining `, ` characters.
*
* @param maxLength the maximum header length
* @returns the minimum header... | ength === 'number') {
env.TEST_REACT_MAX_HEADERS_LENGTH = reactMaxHeadersLength.toString()
}
const { next } = nextTestSetup({ files: __dirname, env })
it('should respect reactMaxHeadersLength', async () => {
const res = | be('react-max-headers-length', () => {
describe.each([0, 400, undefined, 10000])(
'reactMaxHeadersLength = %s',
(reactMaxHeadersLength) => {
const env: Record<string, string> = {}
if (typeof reactMaxHeadersL | {
"filepath": "test/e2e/app-dir/react-max-headers-length/react-max-headers-length.test.ts",
"language": "typescript",
"file_size": 2290,
"cut_index": 563,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
describe('app dir - forbidden with customized boundary', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should match dynamic route forbidden boundary correctly', async () => {
// `/dynamic` display works
const browserDynamic = await next.browser('/dyn... | browserDynamicId.elementByCss('#page').text()).toBe(
'dynamic [id]'
)
})
it('should escalate forbidden to parent layout if no forbidden boundary present in current layer', async () => {
const browserDynamic = await next.browser(
' | or = await next.browser('/dynamic/403')
expect(await browserError.elementByCss('#forbidden').text()).toBe(
'dynamic/[id] forbidden'
)
const browserDynamicId = await next.browser('/dynamic/123')
expect(await | {
"filepath": "test/e2e/app-dir/forbidden/basic/forbidden-basic.test.ts",
"language": "typescript",
"file_size": 1473,
"cut_index": 524,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.