prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
ort React from 'react'
import Script from 'next/script'
const Page = () => {
const [counter, setCounter] = React.useState(0)
const [scriptURL, toggleScriptSource] = React.useReducer(
(currentScriptURL, id) => {
const scriptSource =
typeof currentScriptURL === 'string'
? currentScriptURL... | e="abc123" src={scriptSource} />
<h1 id="h1">{'Count ' + counter}</h1>
<button id="force-rerender" onClick={() => setCounter(counter + 1)}>
Re-render
</button>
<button id="change-script" onClick={toggleScriptSource}>
| (`/src-1.js?key=${Math.random()}`, window.location)
}
},
'/src-1.js'
)
const scriptSource =
typeof scriptURL === 'string' ? scriptURL : scriptURL.href
return (
<>
<Script key={scriptSource} nonc | {
"filepath": "test/e2e/nonce-head-manager/app/pages/index.js",
"language": "javascript",
"file_size": 1070,
"cut_index": 515,
"middle_length": 229
} |
import React, { useCallback, useEffect, useRef, useState } from 'react'
import Link from 'next/link'
const useClickAway = (ref, onClickAway) => {
useEffect(() => {
const handler = (event) => {
const el = ref.current
// when menu is open and clicked inside menu, A is expected to be false
// wh... | removeEventListener('click', handler)
}
}, [onClickAway, ref])
}
export default function App() {
const [open, setOpen] = useState(false)
const menuRef = useRef(null)
const onClickAway = useCallback(() => {
console.log('click away, open', |
let timeoutID = setTimeout(() => {
timeoutID = null
document.addEventListener('click', handler)
}, 0)
return () => {
if (timeoutID != null) {
clearTimeout(timeoutID)
}
document. | {
"filepath": "test/e2e/link-ref-app/app/click-away-race-condition/page.js",
"language": "javascript",
"file_size": 1361,
"cut_index": 524,
"middle_length": 229
} |
{ FileRef, nextTestSetup } from 'e2e-utils'
import { renderViaHTTP, fetchViaHTTP } from 'next-test-utils'
import path from 'path'
import cheerio from 'cheerio'
const appDir = path.join(__dirname, 'app')
// TODO: This test needs to check multiple files and syntax features.
describe.skip('default browserslist target', ... | = $(el).attr('src')
const res = await fetchViaHTTP(next.url, src)
const code = await res.text()
// Default compiles for ES Modules output
if (code.includes('async ()=>')) {
return src
| nst html = await renderViaHTTP(next.url, '/')
const $ = cheerio.load(html)
expect(
(
await Promise.all(
$('script')
.toArray()
.map(async (el) => {
const src | {
"filepath": "test/e2e/browserslist/default-target.test.ts",
"language": "typescript",
"file_size": 1176,
"cut_index": 518,
"middle_length": 229
} |
rom 'e2e-utils'
import { join } from 'path'
describe('postcss-config-json', () => {
const { next } = nextTestSetup({
files: new FileRef(join(__dirname, 'app')),
dependencies: {
autoprefixer: '10.4.19',
postcss: '8.4.38',
tailwindcss: '3.4.4',
},
packageJson: {
postcss: {
... | = await browser.elementByCss('.text-6xl').text()
expect(text).toMatch(/Welcome to/)
const cssBlue = await browser
.elementByCss('#test-link')
.getComputedCss('color')
expect(cssBlue).toBe('rgb(37, 99, 235)')
} finally | = await next.browser('/')
try {
const text | {
"filepath": "test/e2e/postcss-config-package/index.test.ts",
"language": "typescript",
"file_size": 900,
"cut_index": 547,
"middle_length": 52
} |
rom 'next/server'
export default function middleware(request) {
const res = NextResponse.rewrite(new URL('/', request.url))
res.headers.set('X-From-Middleware', 'true')
return res
}
export const config = {
matcher: [
{ source: '/source-match' },
{
source: '/has-match-1',
has: [
{
... | ],
},
{
source: '/has-match-4',
has: [
{
type: 'host',
value: 'example.com',
},
],
},
{
source: '/has-match-5',
has: [
{
type: 'header',
key: 'h | 'query',
key: 'my-query',
},
],
},
{
source: '/has-match-3',
has: [
{
type: 'cookie',
key: 'loggedIn',
value: '(?<loggedIn>true)',
},
| {
"filepath": "test/e2e/middleware-custom-matchers/app/middleware.js",
"language": "javascript",
"file_size": 1829,
"cut_index": 537,
"middle_length": 229
} |
tTestSetup, isNextDev, isNextDeploy } from 'e2e-utils'
const installCheckVisible = (browser) => {
return browser.eval(`(function() {
window.checkInterval = setInterval(function() {
const root = document.querySelector('nextjs-portal').shadowRoot;
const statusElement = root.querySelector('[data-indic... | escribe('Build Activity Indicator', () => {
// Use describe.skip so that this suite does not fail with "no tests" during deploy tests.
;(isNextDeploy ? describe.skip : describe)('Invalid position config', () => {
const { next } = nextTestSetup({
| ile status
window.showedBuilder = window.showedBuilder || (
statusElement !== null || (status && status !== 'none')
)
if (window.showedBuilder) clearInterval(window.checkInterval)
}, 5)
})()`)
}
d | {
"filepath": "test/e2e/build-indicator/test/index.test.ts",
"language": "typescript",
"file_size": 3539,
"cut_index": 614,
"middle_length": 229
} |
mport { FileRef, nextTestSetup } from 'e2e-utils'
jest.setTimeout(2 * 60 * 1000)
export function runTests(
example = '',
testPath = '/',
expectedContent = ['index page']
) {
const versionParts = process.versions.node.split('.').map((i) => Number(i))
if ((global as any).isNextDeploy) {
it('should not ru... | the install, we also need to fulfill the peerDependencies.
// However, the example specified latest next which may have different peerDependencies that the next that we test here i.e. the next on this commit.
delete packageJson.dependencies['react | mples', example)
const srcFiles = fs.readdirSync(srcDir)
const packageJson = fs.readJsonSync(join(srcDir, 'package.json'))
// Use the default versions that are usually used in tests.
// Since we replace `next` in | {
"filepath": "test/e2e/yarn-pnp/test/utils.ts",
"language": "typescript",
"file_size": 3244,
"cut_index": 614,
"middle_length": 229
} |
sNextDev, isNextStart } from 'e2e-utils'
import { BUILD_ID_FILE, BUILD_MANIFEST } from 'next/constants'
describe('distDir', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
it('should render the page', async () => {
const html = await... | ect(await next.hasFile('.next')).toBe(false)
})
})
if (isNextStart) {
describe('distDir config validation', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if | e(`dist/dev/${BUILD_MANIFEST}`)).toBe(true)
} else {
expect(await next.hasFile(`dist/${BUILD_ID_FILE}`)).toBe(true)
}
})
it('should not build the app within the default `.next` directory', async () => {
exp | {
"filepath": "test/e2e/dist-dir/dist-dir.test.ts",
"language": "typescript",
"file_size": 1932,
"cut_index": 537,
"middle_length": 229
} |
ort React from 'react'
import Script from 'next/script'
const Page = () => {
const [counter, setCounter] = React.useState(0)
const [scriptURL, toggleScriptSource] = React.useReducer(
(currentScriptURL, id) => {
const scriptSource =
typeof currentScriptURL === 'string'
? currentScriptURL... | e="abc123" src={scriptSource} />
<h1 id="h1">{'Count ' + counter}</h1>
<button id="force-rerender" onClick={() => setCounter(counter + 1)}>
Re-render
</button>
<button id="change-script" onClick={toggleScriptSource}>
| (`/src-1.js?key=${Math.random()}`, window.location)
}
},
'/src-1.js'
)
const scriptSource =
typeof scriptURL === 'string' ? scriptURL : scriptURL.href
return (
<>
<Script key={scriptSource} nonc | {
"filepath": "test/e2e/nonce-head-manager/app/pages/csp.js",
"language": "javascript",
"file_size": 1070,
"cut_index": 515,
"middle_length": 229
} |
om 'e2e-utils'
import { retry } from 'next-test-utils'
describe('Link ref app', () => {
const { next } = nextTestSetup({
files: __dirname,
})
const noError = async (pathname: string) => {
const browser = await next.browser('/')
await browser.eval(`(function() {
window.caughtErrors = []
c... | name: string) => {
const requests: string[] = []
const browser = await next.browser(pathname, {
beforePageLoad(page: any) {
page.on('request', async (req: any) => {
const url = new URL(req.url())
const headers = aw | place('${pathname}')
})()`)
await retry(async () => {
const errors = await browser.eval(`window.caughtErrors`)
expect(errors).toEqual([])
})
await browser.close()
}
const didPrefetch = async (path | {
"filepath": "test/e2e/link-ref-app/link-ref-app.test.ts",
"language": "typescript",
"file_size": 2844,
"cut_index": 563,
"middle_length": 229
} |
v className="flex flex-col items-center justify-center min-h-screen py-2">
<main className="flex flex-col items-center justify-center w-full flex-1 px-20 text-center">
<h1 className="text-blue-600 text-6xl font-bold">
Welcome to{' '}
<a className="text-blue-600" href="https://nextjs.or... | g/docs"
className="p-6 mt-6 text-left border w-96 rounded-xl hover:text-blue-600 focus:text-blue-600"
>
<h3 className="text-2xl font-bold">Documentation →</h3>
<p className="mt-4 text-xl">
Fi | lg bg-gray-100 rounded-md">
pages/index.js
</code>
</p>
<div className="flex flex-wrap items-center justify-around max-w-4xl mt-6 sm:w-full">
<a
href="https://nextjs.or | {
"filepath": "test/e2e/postcss-config-package/app/pages/index.js",
"language": "javascript",
"file_size": 2481,
"cut_index": 563,
"middle_length": 229
} |
-check
import { NextResponse } from 'next/server'
/**
* @param {NextRequest} req
*/
export default async function middleware(req) {
const res = NextResponse.next()
res.headers.set('x-incoming-content-type', req.headers.get('content-type'))
const handler =
bodyHandlers[req.nextUrl.searchParams.get('middle... | [
['x-req-type', 'json'],
['x-serialized', JSON.stringify(json)],
]
},
text: async (req) => {
const text = await req.text()
return [
['x-req-type', 'text'],
['x-serialized', text],
]
},
formData: async (req) | .NextRequest} NextRequest
* @typedef {(req: NextRequest) => Promise<[string, string][]>} Handler
* @type {Record<string, Handler>}
*/
const bodyHandlers = {
json: async (req) => {
const json = await req.json()
return | {
"filepath": "test/e2e/edge-can-read-request-body/app/middleware.js",
"language": "javascript",
"file_size": 1181,
"cut_index": 518,
"middle_length": 229
} |
m 'next/dist/compiled/strip-ansi'
const unsupportedFunctions = [
'setImmediate',
'clearImmediate',
'process.cwd',
'process.cpuUsage',
'process.getuid',
]
const undefinedProperties = ['process.arch', 'process.version']
const unsupportedClasses = [
'BroadcastChannel',
'ByteLengthQueuingStrategy',
'Compre... | ({
files: __dirname,
// Turbopack builds fail (non-zero exit) when edge code uses Node.js APIs,
// but the CLI output still contains the warnings we're asserting on. Skip
// the automatic start so we can run the build manually and ignore th | BRequest',
'ReadableStreamDefaultController',
'TransformStreamDefaultController',
'WritableStreamDefaultController',
]
describe('Edge runtime with Node.js APIs', () => {
const { next, isNextDev, skipped } = nextTestSetup | {
"filepath": "test/e2e/edge-runtime-with-node.js-apis/edge-runtime-with-node.js-apis.test.ts",
"language": "typescript",
"file_size": 3497,
"cut_index": 614,
"middle_length": 229
} |
r-with-rewrites', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should preserve current pathname when using useRouter.push with rewrites', async () => {
const browser = await next.browser('/')
await browser.elementById('router-push').click()
const url = new URL(await browser.... | ing Link with rewrites', async () => {
const browser = await next.browser('/')
await browser.elementByCss('a').click()
const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe('/?param=1')
})
describe('rewrite t | next.browser('/')
await browser.elementById('router-replace').click()
const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe('/?param=1')
})
it('should preserve current pathname when us | {
"filepath": "test/e2e/use-router-with-rewrites/use-router-with-rewrites.test.ts",
"language": "typescript",
"file_size": 3906,
"cut_index": 614,
"middle_length": 229
} |
import { check } from 'next-test-utils'
import { join } from 'path'
const locales = ['', '/en', '/sv', '/nl']
describe('i18n-ignore-redirect-source-locale', () => {
const { next } = nextTestSetup({
files: {
pages: new FileRef(join(__dirname, 'app/pages')),
},
dependencies: {},
nextConfig: {
... | locale: false,
},
{
source: '/:locale/to-slash',
destination: '/newpage',
permanent: false,
locale: false,
},
{
source: '/:locale/to-same',
des | destination: '/sv/newpage',
permanent: false,
locale: false,
},
{
source: '/:locale/to-en',
destination: '/en/newpage',
permanent: false,
| {
"filepath": "test/e2e/i18n-ignore-redirect-source-locale/redirects.test.ts",
"language": "typescript",
"file_size": 2236,
"cut_index": 563,
"middle_length": 229
} |
scribe('Preview mode with fallback pages', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
cookie: '0.7.2',
},
})
let previewCookie: string
it('should get preview cookie correctly', async () => {
const res = await next.fetch('/api/enable')
previewCookie = '... | `${
isBypass ? '__prerender_bypass' : '__next_preview_data'
}=${cookies[isBypass ? '__prerender_bypass' : '__next_preview_data']}`
}
})
})
it('should not write preview index SSG page to cache', async () => {
con | {
const cookies = cookie.parse(c)
const isBypass = cookies.__prerender_bypass
if (isBypass || cookies.__next_preview_data) {
if (previewCookie) previewCookie += '; '
previewCookie += | {
"filepath": "test/e2e/preview-fallback/preview-fallback.test.ts",
"language": "typescript",
"file_size": 7628,
"cut_index": 716,
"middle_length": 229
} |
bsocket',
destination:
'http://localhost:__EXTERNAL_PORT__/_next/hmr?page=/about',
},
{
source: '/websocket-to-page',
destination: '/hello',
},
{
source: '/to-nowhere',
destination: 'http://localhost:12233',
},
... | },
{
source: '/hello-world',
destination: '/static/hello.txt',
},
{
source: '/',
destination: '/another',
},
{
source: '/another',
destination: '/multi-r | destination: '/auto-export/another?rewrite=1',
},
{
source: '/to-another',
destination: '/another/one',
},
{
source: '/nav',
destination: '/404',
| {
"filepath": "test/e2e/custom-routes/next.config.js",
"language": "javascript",
"file_size": 17267,
"cut_index": 921,
"middle_length": 229
} |
from 'next/link'
const Page = () => (
<>
<h3 id="nav">Nav</h3>
<Link href="/hello" as="/first" id="to-hello">
to hello
</Link>
<br />
<Link href="/hello-again" as="/second" id="to-hello-again">
to hello-again
</Link>
<br />
<Link
href={{
pathname: '/with-para... | br />
<Link href="/hello?overrideMe=1" id="to-overridden">
to /hello?overrideMe=1
</Link>
<br />
<Link href="/old-blog/about" id="to-old-blog">
to /old-blog/post-1
</Link>
<br />
<Link href="/overridden" id="to-befor | </Link>
<br />
<Link href="/params/1?another=value" id="to-params">
to params
</Link>
<br />
<Link href="/rewriting-to-auto-export" id="to-rewritten-dynamic">
to rewritten dynamic
</Link>
< | {
"filepath": "test/e2e/custom-routes/pages/nav.js",
"language": "javascript",
"file_size": 1297,
"cut_index": 524,
"middle_length": 229
} |
port { ImageResponse } from 'next/og'
import fs from 'fs'
import path from 'path'
export async function GET() {
const font = await fs.promises.readFile(
// We need to use process.cwd() instead of import.meta.url for nft tracing purpose
path.join(process.cwd(), 'assets/typewr__.ttf')
)
return new ImageRes... | 88,
background: '#fff',
color: '#000',
}}
>
Typewriter og
</div>
),
{
fonts: [
{
name: 'Typewriter',
data: font,
style: 'normal',
},
],
} | fontSize: | {
"filepath": "test/e2e/og-routes-custom-font/app/app/og-node/route.js",
"language": "javascript",
"file_size": 791,
"cut_index": 514,
"middle_length": 14
} |
'
import { retry, waitFor } from 'next-test-utils'
// Eviction requires the dev server (HMR) and persistent caching (Turbopack).
// Skip entirely in prod/start mode.
;(isNextDev ? describe : describe.skip)('evict-after-snapshot', () => {
const envVars = [
'ENABLE_CACHING=1',
'TURBO_ENGINE_IGNORE_DIRTY=1',
... | otAndEviction() {
// The idle timeout is 1s, give extra time for snapshot + eviction to complete
await waitFor(5000)
}
// Turbopack-only: eviction requires persistent caching
;(process.env.IS_TURBOPACK_TEST ? it : it.skip)(
'should serve | nt: true,
packageJson: {
scripts: {
dev: `${envVars} next dev`,
},
},
installCommand: 'npm i',
startCommand: 'npm run dev',
})
if (skipped) {
return
}
async function waitForSnapsh | {
"filepath": "test/e2e/filesystem-cache/evict-after-snapshot.test.ts",
"language": "typescript",
"file_size": 2599,
"cut_index": 563,
"middle_length": 229
} |
return 0
}
let totalSize = 0
const entries = await fs.readdir(dirPath, {
recursive: true,
withFileTypes: true,
})
for (const entry of entries) {
if (entry.isFile()) {
const filePath = path.join(entry.parentPath ?? entry.path, entry.name)
const stat = await fs.stat(filePath)
tot... | // Make it easier to run in development, test directories are cleared between runs already so this is safe.
`TURBO_ENGINE_IGNORE_DIRTY=1`,
// decrease the idle timeout to make the test more reliable
`TURBO_ENGINE_SNAPSHOT_IDLE_TIMEOUT_M | beforeAll(() => {
process.env.NEXT_PUBLIC_ENV_VAR = 'hello world'
})
afterAll(() => {
delete process.env.NEXT_PUBLIC_ENV_VAR
})
let envVars = [
`ENABLE_CACHING=${cacheEnabled ? '1' : ''}`,
| {
"filepath": "test/e2e/filesystem-cache/filesystem-cache.test.ts",
"language": "typescript",
"file_size": 15325,
"cut_index": 921,
"middle_length": 229
} |
enableCaching = !!process.env.ENABLE_CACHING
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
turbopack: {
rules: {
'./app/**/page.{jsx,tsx}': {
loaders: ['./my-timestamp-loader.js'],
},
'./app/loader/page.tsx': {
loaders: ['./my-loader.js'],
},
'./p... | ader.js'],
})
config.module.rules.push({
test: /app\/loader(?:\/client)?\/page\.tsx/,
use: ['./my-loader.js'],
})
if (enableCaching) {
config.cache = Object.freeze({
type: 'memory',
})
}
if (dev) {
| : enableCaching,
},
env: {
NEXT_PUBLIC_CONFIG_ENV: 'hello world',
},
webpack(config, { dev }) {
config.module.rules.push({
test: /app(?:\/.*)?\/page\.[tj]sx|pages\/pages\.tsx/,
use: ['./my-timestamp-lo | {
"filepath": "test/e2e/filesystem-cache/next.config.js",
"language": "javascript",
"file_size": 1250,
"cut_index": 518,
"middle_length": 229
} |
cycle, run a warm
// cycle and snapshot the set of turbo-tasks functions that had any cache
// miss. If a task previously cached (e.g. via a persistable entries map)
// regresses to recomputing on warm restart, this snapshot will change and
// fail the test.
//
// When the snapshot moves:
// - FEWER entries → that's... | , TaskFunctionStatistics>
const STATS_RELATIVE_PATH = '.next/warm-restart-task-stats.json'
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'warm-restart task statistics',
() => {
const env = [
'ENABLE_CACHING=1',
'TURBO_E | snapshots are kept separate because the warm graphs
// differ: dev brings up HMR/Fast Refresh infra that build doesn't.
interface TaskFunctionStatistics {
cache_hit: number
cache_miss: number
}
type TaskStats = Record<string | {
"filepath": "test/e2e/filesystem-cache/warm-restart-task-stats.test.ts",
"language": "typescript",
"file_size": 5918,
"cut_index": 716,
"middle_length": 229
} |
source: '/add-header',
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
{
source: '/add-header-no-basepath',
basePath: false,
headers: [
{
... | click()
.waitForElementByCss('input', { state: 'attached' })
.back()
.waitForElementByCss('p')
await waitFor(1000)
const newText = await browser.elementByCss('p').text()
expect(newText).toBe('server')
})
if (process.env. | > {
const browser = await next.browser(`${basePath}/external-and-back`)
const initialText = await browser.elementByCss('p').text()
expect(initialText).toBe('server')
await browser
.elementByCss('a')
. | {
"filepath": "test/e2e/basepath/basepath.test.ts",
"language": "typescript",
"file_size": 19594,
"cut_index": 1331,
"middle_length": 229
} |
etup({
files: __dirname,
nextConfig: {
basePath,
onDemandEntries: {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60,
},
},
})
describe('client-side navigation', () => {
it('should navigate to /404 correctly client-side', async () => {
... | Be(`${basePath}/slug-2`)
})
it('should navigate to /_error correctly client-side', async () => {
const browser = await next.browser(`${basePath}/slug-1`)
await check(
() => browser.eval('document.documentElement.innerHTML'),
| r.eval('next.router.push("/404", "/slug-2")')
await check(
() => browser.eval('document.documentElement.innerHTML'),
/page could not be found/
)
expect(await browser.eval('location.pathname')).to | {
"filepath": "test/e2e/basepath/error-pages.test.ts",
"language": "typescript",
"file_size": 5604,
"cut_index": 716,
"middle_length": 229
} |
xt-test-utils'
import { nextTestSetup } from 'e2e-utils'
describe('basePath query/hash handling', () => {
const basePath = '/docs'
const { next } = nextTestSetup({
files: __dirname,
nextConfig: {
basePath,
onDemandEntries: {
// Make sure entries are not getting disposed.
maxInac... | )(
'is correct during query updating $hash $search',
async ({ hash, search, query }) => {
const browser = await next.browser(
`${basePath}${search || ''}${hash || ''}`
)
await check(
() =>
browser.eval(' | },
{ hash: '#hello?world' },
{ search: '?hello=world', hash: '#a', query: { hello: 'world' } },
{ search: '?hello', hash: '#a', query: { hello: '' } },
{ search: '?hello=', hash: '#a', query: { hello: '' } },
] | {
"filepath": "test/e2e/basepath/query-hash.test.ts",
"language": "typescript",
"file_size": 1857,
"cut_index": 537,
"middle_length": 229
} |
'
describe('basePath', () => {
const basePath = '/docs'
const { next, isNextDeploy } = nextTestSetup({
files: __dirname,
nextConfig: {
basePath,
onDemandEntries: {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60,
},
async rewrites() {
... | ,
destination: '/gssp',
},
]
},
async redirects() {
return [
{
source: '/redirect-1',
destination: '/somewhere-else',
permanent: false,
},
| ttps://example.vercel.sh',
basePath: false,
},
{
source: '/rewrite/chain-1',
destination: '/rewrite/chain-2',
},
{
source: '/rewrite/chain-2' | {
"filepath": "test/e2e/basepath/redirect-and-rewrite.test.ts",
"language": "typescript",
"file_size": 4112,
"cut_index": 614,
"middle_length": 229
} |
-utils'
describe('basePath', () => {
const basePath = '/docs'
const { next } = nextTestSetup({
files: __dirname,
nextConfig: {
basePath,
onDemandEntries: {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60,
},
},
})
it('should use urls... | t eventLog = await browser.eval('window._getEventLog()')
expect(
eventLog.filter((item) => item[1]?.endsWith('/other-page'))
).toEqual([
['routeChangeStart', `${basePath}/other-page`, { shallow: false }],
['beforeHistory | Ready')).resolves.toBe(true)
)
await browser.eval('window._clearEventLog()')
await browser
.elementByCss('#other-page-link')
.click()
.waitForElementByCss('#other-page-title')
cons | {
"filepath": "test/e2e/basepath/router-events.test.ts",
"language": "typescript",
"file_size": 4175,
"cut_index": 614,
"middle_length": 229
} |
'basePath + trailingSlash', () => {
const basePath = '/docs'
const { next } = nextTestSetup({
files: __dirname,
nextConfig: {
trailingSlash: true,
basePath,
onDemandEntries: {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60,
},
},
... | s (see #13132, #13560)
setTimeout(resolve, dev ? 10000 : 1000)
})
expect(await browser.eval('window.itdidnotrefresh')).toBe('hello')
const pathname = await browser.elementByCss('#pathname').text()
expect(pathname) | try {
await browser.eval('window.itdidnotrefresh = "hello"')
await new Promise((resolve, reject) => {
// Timeout of EventSource created in setupPing()
// (on-demand-entries-utils.js) is 5000 m | {
"filepath": "test/e2e/basepath/trailing-slash.test.ts",
"language": "typescript",
"file_size": 3114,
"cut_index": 614,
"middle_length": 229
} |
'react'
import { useRouter } from 'next/router'
// We use session storage for the event log so that it will survive
// page reloads, which happen for instance during routeChangeError
const EVENT_LOG_KEY = 'router-event-log'
function getEventLog() {
const data = sessionStorage.getItem(EVENT_LOG_KEY)
return data ?... | g = getEventLog
}
function useLoggedEvent(event, serializeArgs = (...args) => args) {
const router = useRouter()
useEffect(() => {
const logEvent = (...args) => {
addEvent([event, ...serializeArgs(...args)])
}
router.events.on(event, | rage.setItem(EVENT_LOG_KEY, JSON.stringify(eventLog))
}
if (typeof window !== 'undefined') {
// global functions introduced to interface with the test infrastructure
window._clearEventLog = clearEventLog
window._getEventLo | {
"filepath": "test/e2e/basepath/pages/_app.js",
"language": "javascript",
"file_size": 1599,
"cut_index": 537,
"middle_length": 229
} |
nk'
import { useRouter } from 'next/router'
function Page() {
const router = useRouter()
const routerObj = router.isReady ? router : { pathname: '', asPath: '' }
return (
<>
<Link href="/other-page" id="other-page-link">
<h1>Hello World</h1>
</Link>
<br />
<Link href="/gsp" id... | catchall page</h1>
</Link>
<br />
<Link href="/" id="index-gsp">
<h1>index getStaticProps</h1>
</Link>
<br />
<Link href="/index" id="nested-index-gsp">
<h1>nested index getStaticProps</h1>
</Link>
| ="/[slug]" as="/first" id="dynamic-link">
<h1>dynamic page</h1>
</Link>
<br />
<Link
href="/catchall/[...parts]"
as="/catchall/hello/world"
id="catchall-link"
>
<h1> | {
"filepath": "test/e2e/basepath/pages/hello.js",
"language": "javascript",
"file_size": 1955,
"cut_index": 537,
"middle_length": 229
} |
r } from 'next/router'
import Link from 'next/link'
import { useState } from 'react'
import { useEffect } from 'react'
export const getStaticProps = () => {
return {
props: {
nested: false,
hello: 'hello',
},
}
}
export default function Index({ hello, nested }) {
const { query, pathname, asP... | 'yes' : 'no'}</p>
<p id="prop">{hello} world</p>
<p id="query">{JSON.stringify(query)}</p>
<p id="pathname">{pathname}</p>
<p id="as-path">{mounted ? asPath : ''}</p>
<Link href="/hello" id="hello-link">
to /hello
| age">index page</h1>
<p id="nested">{nested ? | {
"filepath": "test/e2e/basepath/pages/index.js",
"language": "javascript",
"file_size": 861,
"cut_index": 529,
"middle_length": 52
} |
skipDeployment: true,
})
const gip404Err =
/`pages\/404` can not have getInitialProps\/getServerSideProps/
it('should use pages/404', async () => {
const html = await next.render('/abc')
expect(html).toContain('custom 404 page')
})
it('should set correct status code with pages/404', async () =... | in('custom 404 page')
})
it('should render _error for a 500 error still', async () => {
const html = await next.render('/err')
expect(html).not.toContain('custom 404 page')
expect(html).toContain(isNextDev ? 'oops' : 'Internal Server Error | ion')
expect(html).toContain('custom 404 page')
})
it('should not error when visited directly', async () => {
const res = await next.fetch('/404')
expect(res.status).toBe(404)
expect(await res.text()).toConta | {
"filepath": "test/e2e/404-page/404-page.test.ts",
"language": "typescript",
"file_size": 8138,
"cut_index": 716,
"middle_length": 229
} |
using webpack.
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'postcss-config-ts',
() => {
describe('postcss.config.ts', () => {
const { next } = nextTestSetup({
files: new FileRef(join(__dirname, 'postcss-config')),
})
it('works with postcss.config.ts files', async () =... | test')
.getComputedCss('color')
expect(color).toBe('rgb(0, 128, 0)')
} finally {
await browser.close()
}
})
})
describe('.postcssrc.ts', () => {
const { next } = nextTestSetup({
f | CSS has `color: red` but the PostCSS plugin transforms it to green.
// If this is green, it proves the TypeScript PostCSS config was loaded and applied.
const color = await browser
.elementByCss('# | {
"filepath": "test/e2e/postcss-config-ts/index.test.ts",
"language": "typescript",
"file_size": 3423,
"cut_index": 614,
"middle_length": 229
} |
\\.json$`
),
page: '/blog',
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/blog/(?<nxtPpost>[^/]+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/blog\\/([^\\/]+?)\\.json$`
),
page: '/blog/[post]',
routeKeys: {
... | mment: 'nxtPcomment',
},
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/catchall/(?<nxtPpath>.+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/catchall\\/(.+?)\\. | gex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/blog\\/([^\\/]+?)\\/([^\\/]+?)\\.json$`
),
page: '/blog/[post]/[comment]',
routeKeys: {
nxtPpost: 'nxtPpost',
nxtPco | {
"filepath": "test/e2e/getserversideprops/test/index.test.ts",
"language": "typescript",
"file_size": 29110,
"cut_index": 1331,
"middle_length": 229
} |
react-dom/server'
import { RouterContext } from 'next/dist/shared/lib/router-context.shared-runtime'
import { useRouter } from 'next/router'
function RouterComp(props) {
const router = useRouter()
if (!router) {
throw new Error('router is missing!')
}
return (
<>
<p>props {JSON.stringify(props)... | w: preview,
}}
>
<p>hello world</p>
<RouterComp hello={'world'} />
</RouterContext.Provider>
)
)
return {
props: {
url: req.url,
world: 'world',
time: new Date().getTime(),
},
}
}
con | useRouter hook
// no matter where it is imported
console.log(
ReactDOM.renderToString(
<RouterContext.Provider
value={{
query,
pathname: '/',
asPath: req.url,
isPrevie | {
"filepath": "test/e2e/getserversideprops/app/pages/index.js",
"language": "javascript",
"file_size": 2420,
"cut_index": 563,
"middle_length": 229
} |
port React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getServerSideProps({ params, query }) {
return {
world: 'world',
query: query || {},
params: params || {},
time: new Date().getTime(),
random: Math.random(),
}
}
export default ({... | {JSON.stringify(query)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/" id="home">
to home
</Link>
<br />
<Link href="/another" id="another">
to another
</Link>
</>
)
| ingify(params)}</div>
<div id="initial-query"> | {
"filepath": "test/e2e/getserversideprops/app/pages/invalid-keys.js",
"language": "javascript",
"file_size": 824,
"cut_index": 514,
"middle_length": 52
} |
React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getServerSideProps({ params, query, resolvedUrl }) {
return {
props: {
resolvedUrl: resolvedUrl,
world: 'world',
query: query || {},
params: params || {},
time: new Date().... | iv id="query">{JSON.stringify(router.query)}</div>
<div id="app-query">{JSON.stringify(appProps.query)}</div>
<div id="app-url">{appProps.url}</div>
<div id="resolved-url">{resolvedUrl}</div>
<div id="as-path">{router.asPath}</div>
| (
<>
<p>hello: {world}</p>
<span>time: {time}</span>
<div id="random">{random}</div>
<div id="params">{JSON.stringify(params)}</div>
<div id="initial-query">{JSON.stringify(query)}</div>
<d | {
"filepath": "test/e2e/getserversideprops/app/pages/something.js",
"language": "javascript",
"file_size": 1167,
"cut_index": 518,
"middle_length": 229
} |
ort React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getServerSideProps({ params, resolvedUrl }) {
if (params.post === 'post-10') {
await new Promise((resolve) => {
setTimeout(() => resolve(), 1000)
})
}
if (params.post === 'post-100') {... | /div>
<div id="query">{JSON.stringify(router.query)}</div>
<div id="app-query">{JSON.stringify(appProps.query)}</div>
<div id="app-url">{appProps.url}</div>
<div id="resolved-url">{resolvedUrl}</div>
<div id="as-path">{router. | }
}
export default ({ post, time, params, appProps, resolvedUrl }) => {
const router = useRouter()
return (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}< | {
"filepath": "test/e2e/getserversideprops/app/pages/blog/[post]/index.js",
"language": "javascript",
"file_size": 1090,
"cut_index": 515,
"middle_length": 229
} |
ware')
})
it('adds the header for a matched data path (with header)', async () => {
const response = await fetchViaHTTP(
next.url,
`/_next/data/${next.buildId}/with-middleware.json`,
undefined,
{ headers: { 'x-nextjs-data': '1' } }
)
expect(await response.json()).toMatchObject({... | message: 'Hello, cruel world.',
},
})
expect(response.headers.get('X-From-Middleware')).toBe('true')
})
it('adds the header for another matched path', async () => {
const response = await fetchViaHTTP(next.url, '/another-middlewa | th (without header)', async () => {
const response = await fetchViaHTTP(
next.url,
`/_next/data/${next.buildId}/with-middleware.json`
)
expect(await response.json()).toMatchObject({
pageProps: {
| {
"filepath": "test/e2e/middleware-matcher/index.test.ts",
"language": "typescript",
"file_size": 22774,
"cut_index": 1331,
"middle_length": 229
} |
fetchViaHTTP } from 'next-test-utils'
describe('undici fetch', () => {
const { next } = nextTestSetup({
files: {
'pages/api/globalFetch.js': `
import { ReadableStream } from 'node:stream/web';
export default async function globalFetch(req, res) {
try {
const response =... | 'entries'
})
}
`,
'pages/api/globalRequest.js': `
export default async function globalRequest(req, res) {
res.json({
value: (new Request('https://example.vercel.sh')).headers[Symbol.iterator].name | .send(error);
}
}
`,
'pages/api/globalHeaders.js': `
export default async function globalHeaders(req, res) {
res.json({
value: (new Headers())[Symbol.iterator].name === | {
"filepath": "test/e2e/undici-fetch/index.test.ts",
"language": "typescript",
"file_size": 2333,
"cut_index": 563,
"middle_length": 229
} |
b/constants'
describe('GS(S)P Page Errors', () => {
;(isNextDev ? describe : describe.skip)('development mode', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
it('should show error for getStaticProps as component member', ... | t and must be exported from the page`
)
})
it('should show error for getServerSideProps as component member', async () => {
const outputIndex = next.cliOutput.length
await next.patchFile(
'pages/index.js',
`
| > ({ props: { hello: 'world' }})
export default Page
`
)
await next.render('/')
expect(next.cliOutput.slice(outputIndex)).toContain(
`getStaticProps can not be attached to a page's componen | {
"filepath": "test/e2e/data-fetching-errors/data-fetching-errors.test.ts",
"language": "typescript",
"file_size": 6574,
"cut_index": 716,
"middle_length": 229
} |
sNextDev, isNextStart } from 'e2e-utils'
import stripAnsi from 'next/dist/compiled/strip-ansi'
import { retry } from 'next-test-utils'
describe('jsconfig.json baseurl', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
describe('default be... | ld` below.
;(isNextDev ? it : it.skip)(
'should have correct module not found error',
async () => {
const contents = await next.readFile('pages/hello.js')
try {
await next.patchFile(
'pages/hello.js',
| under `launchApp` only. e2e splits dev vs `next start` jobs, so
// `it.skip` when !isNextDev is correct: the module-not-found overlay is dev-only; production
// jobs still cover `should trace correctly` under `should bui | {
"filepath": "test/e2e/jsconfig-baseurl/jsconfig-baseurl.test.ts",
"language": "typescript",
"file_size": 2001,
"cut_index": 537,
"middle_length": 229
} |
loader that returns invalid CSS with a source map.
// The source map points back to the original file, making it clear that the
// loader is responsible for the broken output (not the original source).
module.exports = function (source) {
// Generate a source map that maps generated lines back to the original source... | -> original line 2 (" font-size: 16px;")
// generated line 4 (" background: {{{...") -> original line 1 (" color: blue;")
// generated line 5 ("}") -> original line 3 ("}")
const sourceMap = {
version: 3,
| e 0 (".page {")
// generated line 1 (".page {") -> original line 0 (".page {")
// generated line 2 (" color: red") -> original line 1 (" color: blue;")
// generated line 3 (" @@@ ...") | {
"filepath": "test/e2e/webpack-loader-parse-error/broken-css-loader.js",
"language": "javascript",
"file_size": 1373,
"cut_index": 524,
"middle_length": 229
} |
tput.replaceAll(testDir + '/', '')
const relMatch = testDir.match(/(test\/tmp\/next-test-[^/]+)/)
if (relMatch) {
result = result.replaceAll('./' + relMatch[1] + '/', './')
result = result.replaceAll(relMatch[1] + '/', '')
}
return result
}
/**
* Extracts a single error block from CLI output by search... | n ''
const beforeTitle = output.substring(0, titleIdx)
// In dev mode, errors start with a `⨯` marker on the same line as the file path.
// In prod mode, errors start with a bare file-path line above the title.
const markerIdx = beforeTitle.lastI | hat
* isn't followed by continuation content (indented lines or file paths).
*/
function extractErrorBlock(output: string, errorTitle: string): string {
const titleIdx = output.indexOf(errorTitle)
if (titleIdx === -1) retur | {
"filepath": "test/e2e/webpack-loader-parse-error/webpack-loader-parse-error.test.ts",
"language": "typescript",
"file_size": 9479,
"cut_index": 921,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('router.isReady with appGip', () => {
const { next } = nextTestSetup({
files: __dirname,
})
const checkIsReadyValues = async (browser: any, expected: boolean[] = []) => {
await retry(async () => {
const values = JSON.st... | uery', async () => {
const browser = await next.browser('/appGip?hello=world')
await checkIsReadyValues(browser, [true])
})
it('isReady should be true immediately for getStaticProps page without query', async () => {
const browser = await | pages without getStaticProps', async () => {
const browser = await next.browser('/appGip')
await checkIsReadyValues(browser, [true])
})
it('isReady should be true immediately for pages without getStaticProps, with q | {
"filepath": "test/e2e/router-is-ready-app-gip/router-is-ready-app-gip.test.ts",
"language": "typescript",
"file_size": 1301,
"cut_index": 524,
"middle_length": 229
} |
derChunkUrlPath,
retry,
} from 'next-test-utils'
describe('Link ref forwarding', () => {
const { next } = nextTestSetup({
files: __dirname,
})
async function noError(pathname: string) {
const browser = await next.browser('/')
await browser.eval(`(function() {
window.caughtErrors = []
c... | name: string) {
const browser = await next.browser(pathname)
const chunk = getClientBuildManifestLoaderChunkUrlPath(next.testDir, '/')
await retry(async () => {
const links = await browser.elementsByCss('link[rel=prefetch]')
const | place('${pathname}')
})()`)
await retry(async () => {
const errors = await browser.eval(`window.caughtErrors`)
expect(errors).toEqual([])
})
await browser.close()
}
async function didPrefetch(path | {
"filepath": "test/e2e/link-ref-pages/link-ref-pages.test.ts",
"language": "typescript",
"file_size": 3060,
"cut_index": 614,
"middle_length": 229
} |
ls'
describe('404 Page Support SSG', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
disableAutoSkewProtection: true,
// Assertions don't apply to deploy mode (output differs vs. local Next.js server).
skipDeployment: true,
})
if (skipped) return
it('should respond to 404 c... | error in the logs for 404 SSG', async () => {
const gip404Err =
/`pages\/404` can not have getInitialProps\/getServerSideProps/
await next.render('/non-existent')
expect(next.cliOutput).not.toMatch(gip404Err)
})
it('should render in | rectly', async () => {
const text = await next.render('/err')
if (isNextStart) {
expect(text).toContain('Internal Server Error')
} else {
expect(text).toContain('oops')
}
})
it('should not show an | {
"filepath": "test/e2e/404-page-ssg/404-page-ssg.test.ts",
"language": "typescript",
"file_size": 2364,
"cut_index": 563,
"middle_length": 229
} |
s from './Component2.module.scss'
export default function Content2() {
return (
<div className={styles.container}>
<h1 className={styles.header}>Where does it come from?</h1>
<div className={styles.textContent}>
Contrary to popular belief, Lorem Ipsum is not simply random text. It
has... | ctions 1.10.32 and 1.10.33
of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by
Cicero, written in 45 BC. This book is a treatise on the theory of
ethics, very popular during the Renaissance. The first line of Lorem | p one of the more obscure
Latin words, consectetur, from a Lorem Ipsum passage, and going through
the cites of the word in classical literature, discovered the
undoubtable source. Lorem Ipsum comes from se | {
"filepath": "test/e2e/next-dynamic-css-asset-prefix/src/Component2.jsx",
"language": "jsx",
"file_size": 1461,
"cut_index": 524,
"middle_length": 229
} |
tent.module.css'
import Content2 from './Component2'
export default function Content() {
return (
<div className={styles.container}>
<h1 className={styles.header}>Where does it come from?</h1>
<div className={styles.textContent}>
Contrary to popular belief, Lorem Ipsum is not simply random te... | psum comes from sections 1.10.32 and 1.10.33
of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by
Cicero, written in 45 BC. This book is a treatise on the theory of
ethics, very popular during the Renaissance. The f | Virginia, looked up one of the more obscure
Latin words, consectetur, from a Lorem Ipsum passage, and going through
the cites of the word in classical literature, discovered the
undoubtable source. Lorem I | {
"filepath": "test/e2e/next-dynamic-css-asset-prefix/src/Content.jsx",
"language": "jsx",
"file_size": 1511,
"cut_index": 537,
"middle_length": 229
} |
OCESS_ENV_KEY',
'ENV_FILE_KEY',
'ENV_FILE_EMPTY_FIRST',
'ENV_FILE_PROCESS_ENV',
'LOCAL_ENV_FILE_KEY',
'ENV_FILE_LOCAL_OVERRIDE_TEST',
'PRODUCTION_ENV_FILE_KEY',
'LOCAL_PRODUCTION_ENV_FILE_KEY',
'DEVELOPMENT_ENV_FILE_KEY',
'LOCAL_DEVELOPMENT_ENV_FILE_KEY',
'ENV_FILE_DEVELOPMENT_OVERRIDE_TEST',
'ENV... | _LOCAL_KEY',
'NEW_ENV_DEV_KEY',
'NEXT_PUBLIC_HELLO_WORLD',
]
export async function getStaticProps() {
const items = {}
variables.forEach((variable) => {
if (typeof process.env[variable] !== 'undefined') {
items[variable] = process.env[v | E_KEY',
'ENV_FILE_TEST_OVERRIDE_TEST',
'ENV_FILE_TEST_LOCAL_OVERRIDEOVERRIDE_TEST',
'ENV_FILE_EXPANDED',
'ENV_FILE_EXPANDED_CONCAT',
'ENV_FILE_EXPANDED_ESCAPED',
'ENV_FILE_KEY_EXCLAMATION',
'NEW_ENV_KEY',
'NEW_ENV | {
"filepath": "test/e2e/env-config/pages/some-ssg.js",
"language": "javascript",
"file_size": 1570,
"cut_index": 537,
"middle_length": 229
} |
OCESS_ENV_KEY',
'ENV_FILE_KEY',
'ENV_FILE_EMPTY_FIRST',
'ENV_FILE_PROCESS_ENV',
'LOCAL_ENV_FILE_KEY',
'ENV_FILE_LOCAL_OVERRIDE_TEST',
'PRODUCTION_ENV_FILE_KEY',
'LOCAL_PRODUCTION_ENV_FILE_KEY',
'DEVELOPMENT_ENV_FILE_KEY',
'LOCAL_DEVELOPMENT_ENV_FILE_KEY',
'ENV_FILE_DEVELOPMENT_OVERRIDE_TEST',
'ENV... | _LOCAL_KEY',
'NEW_ENV_DEV_KEY',
'NEXT_PUBLIC_HELLO_WORLD',
]
export async function getServerSideProps() {
const items = {}
variables.forEach((variable) => {
if (typeof process.env[variable] !== 'undefined') {
items[variable] = process.e | E_KEY',
'ENV_FILE_TEST_OVERRIDE_TEST',
'ENV_FILE_TEST_LOCAL_OVERRIDEOVERRIDE_TEST',
'ENV_FILE_EXPANDED',
'ENV_FILE_EXPANDED_CONCAT',
'ENV_FILE_EXPANDED_ESCAPED',
'ENV_FILE_KEY_EXCLAMATION',
'NEW_ENV_KEY',
'NEW_ENV | {
"filepath": "test/e2e/env-config/pages/some-ssp.js",
"language": "javascript",
"file_size": 1555,
"cut_index": 537,
"middle_length": 229
} |
mpiled/strip-ansi'
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('edge-runtime-streaming-error', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
disableAutoSkewProtection: true,
// Assertions don't apply to deploy mode (output differs vs. l... | 00)
await retry(() => {
expect(stripAnsi(next.cliOutput)).toMatch(
/The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received type boolean/
)
})
expect(stripAnsi(next.cliOutput)).not.toCon | xt()).toEqual('hello')
expect(res.status).toBe(2 | {
"filepath": "test/e2e/edge-runtime-streaming-error/edge-runtime-streaming-error.test.ts",
"language": "typescript",
"file_size": 889,
"cut_index": 547,
"middle_length": 52
} |
from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
if (router.isFallback) return 'Loading...'
return (
<>
<p id="gsp">gsp page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
... | locale, locales, defaultLocale }) => {
// ensure getStaticProps isn't called without params
if (!params || !params.slug) {
throw new Error(`missing params ${JSON.stringify(params)}`)
}
return {
props: {
params,
locale,
lo | <p id="router-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/" id="to-index">
to /
</Link>
<br />
</>
)
}
export const getStaticProps = ({ params, | {
"filepath": "test/e2e/i18n-support-base-path/pages/gsp/no-fallback/[slug].js",
"language": "javascript",
"file_size": 1310,
"cut_index": 524,
"middle_length": 229
} |
k from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="gsp">gsp page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-locales">{JSON.stringify(ro... | "to-index">
to /
</Link>
<br />
</>
)
}
export const getStaticProps = ({ locale, locales }) => {
if (locale === 'en' || locale === 'nl') {
return {
notFound: true,
}
}
return {
props: {
locale,
| k href="/" id= | {
"filepath": "test/e2e/i18n-support-base-path/pages/not-found/index.js",
"language": "javascript",
"file_size": 816,
"cut_index": 522,
"middle_length": 14
} |
from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="dynamic">dynamic page</p>
<p id="router-locale">{router.locale}</p>
<p id="router-default-locale">{router.defaultLocale}</p>
<p id="router-locale... | fallback-first">
to /gsp/fallback/first
</Link>
<br />
<Link href="/gsp/fallback/hello" id="to-fallback-hello">
to /gsp/fallback/hello
</Link>
<br />
<Link href="/gsp/no-fallback/first" id="to-no-fallback | sPath}</p>
<Link href="/another" id="to-another">
to /another
</Link>
<br />
<Link href="/gsp" id="to-gsp">
to /gsp
</Link>
<br />
<Link href="/gsp/fallback/first" id="to- | {
"filepath": "test/e2e/i18n-support-base-path/pages/dynamic/[slug].js",
"language": "javascript",
"file_size": 1276,
"cut_index": 524,
"middle_length": 229
} |
from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('Scroll Forward Restoration Support', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should restore the scroll position on navigating forward', async () => {
const browser = await next.browser('/another')
await brow... | ion).toBe('manual')
const scrollX = Math.floor(await browser.eval(() => window.scrollX))
const scrollY = Math.floor(await browser.eval(() => window.scrollY))
expect(scrollX).not.toBe(0)
expect(scrollY).not.toBe(0)
await browser.eval( | })
await browser.eval(() =>
document.querySelector('#to-another')!.scrollIntoView()
)
const scrollRestoration = await browser.eval(
() => window.history.scrollRestoration
)
expect(scrollRestorat | {
"filepath": "test/e2e/scroll-forward-restoration/scroll-forward-restoration.test.ts",
"language": "typescript",
"file_size": 1692,
"cut_index": 537,
"middle_length": 229
} |
http = require('http')
const { parse } = require('url')
const next = require('next')
const getPort = require('get-port')
async function main() {
const dev = process.env.NEXT_TEST_MODE === 'dev'
process.env.NODE_ENV = dev ? 'development' : 'production'
const port = await getPort()
const app = next({ dev, port ... | sCode = 500
res.end('Internal Server Error')
}
})
server.once('error', (err) => {
console.error(err)
process.exit(1)
})
server.listen(port, '::', () => {
console.log(`- Local: http://localhost:${port}`)
console.log(`- Ne | { pathname, query } = parsedUrl
if (pathname.startsWith('/render')) {
await app.render(req, res, pathname, query)
} else {
await handle(req, res, parsedUrl)
}
} catch (err) {
res.statu | {
"filepath": "test/e2e/custom-app-render/server.js",
"language": "javascript",
"file_size": 1134,
"cut_index": 518,
"middle_length": 229
} |
mport Link from 'next/link'
const Page = () => (
<div>
<h3>My blog</h3>
<Link href="/[post]" as="/post-1" id="view-post-1">
View post 1
</Link>
<br />
<Link
href="/[post]/comments"
as="/post-1/comments"
id="view-post-1-comments"
>
View post 1 comments
</Link>... | t-1?fromHome=true"
id="view-post-1-with-query"
>
View post 1 with query
</Link>
<br />
<Link
href="/on-mount/[post]"
as="/on-mount/test-w-hash#item-400"
id="view-dynamic-with-hash"
>
View test with ha | ref="/blog/[post]/comment/[id]"
as="/blog/321/comment/123"
id="view-nested-dynamic-cmnt"
>
View comment 123 on blog post 321
</Link>
<br />
<Link
href="/[post]?fromHome=true"
as="/pos | {
"filepath": "test/e2e/src-dir-support/src/pages/index.js",
"language": "javascript",
"file_size": 1045,
"cut_index": 513,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import cheerio from 'cheerio'
describe('disabled runtime JS', () => {
const { next, isNextDev, isNextStart, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
it('should render the page', async () => {
const html = await next.re... | () => {
const html = await next.render('/')
const $ = cheerio.load(html)
expect($('script[src]').length).toBe(0)
})
it('should not have preload links', async () => {
const html = await next.render('/')
const $ = chee | if (isNextStart) {
expect($('script#__NEXT_DATA__').length).toBe(0)
}
if (isNextDev) {
expect($('script#__NEXT_DATA__').length).toBe(1)
}
})
if (isNextStart) {
it('should not have scripts', async | {
"filepath": "test/e2e/disable-js/disable-js.test.ts",
"language": "typescript",
"file_size": 1469,
"cut_index": 524,
"middle_length": 229
} |
y which is not supported on `NextDeployInstance`.
skipDeployment: true,
})
if (skipped) return
async function launchDevServer(
port: number,
opts: {
env?: Record<string, string>
onStderr?: (msg: string) => void
onStdout?: (msg: string) => void
} = {}
): Promise<{ child: ChildP... | env: opts.env,
onStdout(msg) {
opts.onStdout?.(msg)
if (readyPattern.test(msg)) resolveReady()
},
onStderr(msg) {
opts.onStderr?.(msg)
if (readyPattern.test(msg)) resolveReady()
},
| => {
if (!ready) {
ready = true
r()
}
}
})
const readyPattern = /- Local:|✓ Ready/i
const exit = next
.runCommand(['dev', next.testDir, '-p', String(port)], {
| {
"filepath": "test/e2e/telemetry/page-features.test.ts",
"language": "typescript",
"file_size": 9743,
"cut_index": 921,
"middle_length": 229
} |
', () => {
const { next, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
let originalApiRoute: string
let originalMiddleware: string
let originalLib: string
beforeAll(async () => {
originalApiRoute = await next.readF... | s', originalApiRoute)
await next.patchFile('middleware.js', originalMiddleware)
await next.patchFile(LIB_PATH, originalLib)
})
// Webpack treats `node_modules` as a "managed path" in its snapshot
// config (see packages/next/src/bu | t.readFile(LIB_PATH)
} catch (e) {
// File doesn't exist, use default content
originalLib = '// populated by tests\n'
}
})
afterEach(async () => {
await next.patchFile('pages/api/route.j | {
"filepath": "test/e2e/edge-runtime-configurable-guards/edge-runtime-configurable-guards.test.ts",
"language": "typescript",
"file_size": 24339,
"cut_index": 1331,
"middle_length": 229
} |
eEffect, useState } from 'react'
const NONE = '(none)'
export default function ClientComponent() {
const [pageOrigin, setPageOrigin] = useState<string>(NONE)
const [workerCtorUrl, setWorkerCtorUrl] = useState<string>(NONE)
const [workerCtorError, setWorkerCtorError] = useState<string>(NONE)
useEffect(() => {... | tring,
options?: object
) {
const urlString = typeof url === 'string' ? url : url.toString()
setWorkerCtorUrl(urlString)
try {
return new OriginalWorker(url, options)
} catch (err) {
setWorkerCtorError(err | // test can assert on it. Browsers reject cross-origin Worker URLs
// synchronously, so we surface that too.
const OriginalWorker = window.Worker
;(window as any).Worker = function PatchedWorker(
url: URL | s | {
"filepath": "test/e2e/turbopack-worker-asset-prefix/app/client.tsx",
"language": "tsx",
"file_size": 1835,
"cut_index": 537,
"middle_length": 229
} |
type { Server } from 'http'
import { findPort } from 'next-test-utils'
import { nextTestSetup, isNextDev } from 'e2e-utils'
describe('next/dynamic with assetPrefix', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
dependencies: {
sass: '1.54.0',
},
skip... | headers: clientReq.headers,
},
(proxyRes) => {
proxyRes.headers['Access-Control-Allow-Origin'] =
`http://localhost:${targetPort}`
clientRes.writeHead(proxyRes.statusCode!, proxyRes.headers)
| const proxyPath = clientReq.url!.slice('/path-prefix'.length)
const proxyReq = request(
{
hostname: 'localhost',
port: targetPort,
path: proxyPath,
method: clientReq.method,
| {
"filepath": "test/e2e/next-dynamic-css-asset-prefix/next-dynamic-css-asset-prefix.test.ts",
"language": "typescript",
"file_size": 2791,
"cut_index": 563,
"middle_length": 229
} |
path: string) => {
const html = await next.render(path)
const $ = cheerio.load(html)
const env = JSON.parse($('p').text())
env.nextConfigEnv = $('#nextConfigEnv').text()
env.nextConfigPublicEnv = $('#nextConfigPublicEnv').text()
env.nextConfigNewPublicEnv = $('#nextConfigNewPublicEnv').text()
... |
expect(data.TEST_ENV_FILE_KEY).toBe(undefined)
expect(data.LOCAL_TEST_ENV_FILE_KEY).toBe(undefined)
expect(data.PRODUCTION_ENV_FILE_KEY).toBe(
isNextDev ? undefined : 'production'
)
expect(data.LOCAL_PRODUCTION_ENV_FILE_KEY).toBe | _KEY).toBe('localenv')
expect(data.DEVELOPMENT_ENV_FILE_KEY).toBe(
isNextDev ? 'development' : undefined
)
expect(data.LOCAL_DEVELOPMENT_ENV_FILE_KEY).toBe(
isNextDev ? 'localdevelopment' : undefined
) | {
"filepath": "test/e2e/env-config/env-config.test.ts",
"language": "typescript",
"file_size": 11225,
"cut_index": 921,
"middle_length": 229
} |
on('error', (err) => {
console.error(err)
socket.close()
reject()
})
})
await retry(() => {
expect(messages.length).toBeGreaterThan(0)
})
ws.close()
expect([...externalServerHits]).toEqual(['/_next/hmr?page=/about'])
})
it('should successfully rewrite a WebS... | rr) => {
console.error(err)
socket.close()
reject()
})
})
ws.close()
} catch (err) {
messages.push(err)
}
expect(next.cliOutput).not.toContain('unhandledRejection')
})
it('should not | ://localhost:${next.appPort}/websocket-to-page`
)
socket.on('message', (data) => {
messages.push(data.toString())
})
socket.on('open', () => resolve(socket))
socket.on('error', (e | {
"filepath": "test/e2e/custom-routes/custom-routes.test.ts",
"language": "typescript",
"file_size": 118943,
"cut_index": 3790,
"middle_length": 229
} |
from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
if (router.isFallback) return 'Loading...'
return (
<>
<p id="gsp">gsp page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
... | without params
if (!params || !params.slug) {
throw new Error(`missing params ${JSON.stringify(params)}`)
}
if (locale === 'en' || locale === 'nl') {
return {
notFound: true,
}
}
return {
props: {
params,
loca | uter-as-path">{router.asPath}</p>
<Link href="/" id="to-index">
to /
</Link>
<br />
</>
)
}
export const getStaticProps = ({ params, locale, locales }) => {
// ensure getStaticProps isn't called | {
"filepath": "test/e2e/i18n-support-base-path/pages/not-found/fallback/[slug].js",
"language": "javascript",
"file_size": 1266,
"cut_index": 524,
"middle_length": 229
} |
Link from 'next/link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="gsp">gsp page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-locales">{JSON.stringif... | .slug) {
throw new Error(`missing params ${JSON.stringify(params)}`)
}
if (locale === 'en' || locale === 'nl') {
return {
notFound: true,
}
}
return {
props: {
params,
locale,
locales,
},
}
}
export | <Link href="/" id="to-index">
to /
</Link>
<br />
</>
)
}
export const getStaticProps = ({ params, locale, locales }) => {
// ensure getStaticProps isn't called without params
if (!params || !params | {
"filepath": "test/e2e/i18n-support-base-path/pages/not-found/blocking-fallback/[slug].js",
"language": "javascript",
"file_size": 1226,
"cut_index": 518,
"middle_length": 229
} |
e/proxy'
describe('testmode', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
dependencies: require('./package.json').dependencies,
})
if (skipped) {
return
}
let proxyServer: Awaited<ReturnType<typeof createProxyServer>>
beforeEach(async () => {... | t.url === 'https://example.com/middleware'
) {
return new Response(`middleware-${testData}`)
}
return undefined
},
})
})
afterEach(async () => {
proxyServer.close()
})
const fetchForTest = async (ur | 'https://next-data-api-endpoint.vercel.app/api/random',
].includes(request.url)
) {
return new Response(testData)
}
if (
request.method === 'GET' &&
reques | {
"filepath": "test/e2e/testmode/testmode.test.ts",
"language": "typescript",
"file_size": 4365,
"cut_index": 614,
"middle_length": 229
} |
const readyPromise = new Promise<void>((r) => {
resolveReady = () => {
if (!ready) {
ready = true
r()
}
}
})
const readyPattern = /- Local:|✓ Ready/i
const exit = next
.runCommand(['dev', next.testDir, '-p', String(port)], {
env: opts.env,
... | NextStart ? describe : describe.skip)('production mode', () => {
it('detects rewrites, headers, and redirects for next build', async () => {
await fs.rename(
path.join(next.testDir, 'next.config.custom-routes'),
path.join(next.tes | Pattern.test(msg)) resolveReady()
},
instance: (p) => {
child = p
},
})
.finally(() => {
resolveReady()
})
await readyPromise
return { child, exit }
}
;(is | {
"filepath": "test/e2e/telemetry/config.test.ts",
"language": "typescript",
"file_size": 24771,
"cut_index": 1331,
"middle_length": 229
} |
etry feature itself is not React-version-specific, so
// skipping under React 18 is fine until the underlying build/server lifecycle
// race is fixed.
;(isReact18 ? describe.skip : describe)('Telemetry CLI', () => {
const { next, isNextStart, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
skipStar... | t(stdout).toMatch(/Success/)
expect(stdout).toMatch(/Status: Enabled/)
})
it('can disable telemetry with flag', async () => {
const { stdout } = await next.runCommand(['telemetry', '--disable'], {
env: {
NEXT_TELEMETRY_DISABLED: | oMatch(/Status: .*/)
})
it('can enable telemetry with flag', async () => {
const { stdout } = await next.runCommand(['telemetry', '--enable'], {
env: {
NEXT_TELEMETRY_DISABLED: '',
},
})
expec | {
"filepath": "test/e2e/telemetry/telemetry.test.ts",
"language": "typescript",
"file_size": 12245,
"cut_index": 921,
"middle_length": 229
} |
OCESS_ENV_KEY',
'ENV_FILE_KEY',
'ENV_FILE_EMPTY_FIRST',
'ENV_FILE_PROCESS_ENV',
'LOCAL_ENV_FILE_KEY',
'ENV_FILE_LOCAL_OVERRIDE_TEST',
'PRODUCTION_ENV_FILE_KEY',
'LOCAL_PRODUCTION_ENV_FILE_KEY',
'DEVELOPMENT_ENV_FILE_KEY',
'LOCAL_DEVELOPMENT_ENV_FILE_KEY',
'ENV_FILE_DEVELOPMENT_OVERRIDE_TEST',
'ENV... | _LOCAL_KEY',
'NEW_ENV_DEV_KEY',
'NEXT_PUBLIC_HELLO_WORLD',
'NEXT_PUBLIC_EMPTY_ENV_VAR',
]
export async function getStaticProps() {
const items = {}
variables.forEach((variable) => {
if (typeof process.env[variable] !== 'undefined') {
| E_KEY',
'ENV_FILE_TEST_OVERRIDE_TEST',
'ENV_FILE_TEST_LOCAL_OVERRIDEOVERRIDE_TEST',
'ENV_FILE_EXPANDED',
'ENV_FILE_EXPANDED_CONCAT',
'ENV_FILE_EXPANDED_ESCAPED',
'ENV_FILE_KEY_EXCLAMATION',
'NEW_ENV_KEY',
'NEW_ENV | {
"filepath": "test/e2e/env-config/pages/index.js",
"language": "javascript",
"file_size": 1715,
"cut_index": 537,
"middle_length": 229
} |
nk'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
if (router.isFallback) return 'Loading...'
return (
<>
<p id="gsp">gsp page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="rou... | es, defaultLocale }) => {
// ensure getStaticProps isn't called without params
if (!params || !params.slug) {
throw new Error(`missing params ${JSON.stringify(params)}`)
}
if (params && params.slug === 'mixed-not-found-redirect') {
return | er-pathname">{router.pathname}</p>
<p id="router-as-path">{router.asPath}</p>
<Link href="/" id="to-index">
to /
</Link>
<br />
</>
)
}
export const getStaticProps = ({ params, locale, local | {
"filepath": "test/e2e/i18n-support-base-path/pages/gsp/fallback/[slug].js",
"language": "javascript",
"file_size": 1903,
"cut_index": 537,
"middle_length": 229
} |
from 'e2e-utils'
describe('Dynamic Routing with src dir', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should render normal route', async () => {
const html = await next.render('/')
expect(html).toMatch(/my blog/i)
})
it('should render another normal route', async () => {
... | })
it('should render nested dynamic page', async () => {
const html = await next.render('/post-1/comment-1')
expect(html).toMatch(/i am.*comment-1.*on.*post-1/i)
})
it('should navigate to a dynamic page successfully', async () => {
co | )
expect(html).toMatch(/this is.*?post-1/i)
})
it('should prioritize a non-dynamic page', async () => {
const html = await next.render('/post-1/comments')
expect(html).toMatch(/show comments for.*post-1.*here/i)
| {
"filepath": "test/e2e/src-dir-support/src-dir-support.test.ts",
"language": "typescript",
"file_size": 1822,
"cut_index": 537,
"middle_length": 229
} |
xDescription,
} from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils'
describe('Conflict between app file and pages file', () => {
const { next, isNextDev, isNextStart, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
skipStart: true,
})
if (skipped) {
return
}
... | xpect(cliOutput).toMatch(
/Conflicting app and page files? (were|was) found/
)
for (const [pagePath, appPath] of [
['pages/index.js', 'app/page.js'],
['pages/another.js', 'app/another/page.js'],
]) {
| (cliOutput).toContain(
'App Router and Pages Router both match path: /'
)
expect(cliOutput).toContain(
'App Router and Pages Router both match path: /another'
)
} else {
e | {
"filepath": "test/e2e/conflicting-app-page-error/index.test.ts",
"language": "typescript",
"file_size": 4084,
"cut_index": 614,
"middle_length": 229
} |
link'
import { useRouter } from 'next/router'
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="developments">developments page</p>
<p id="props">{JSON.stringify(props)}</p>
<p id="router-locale">{router.locale}</p>
<p id="router-default-locale">{route... | }</p>
<Link href="/" id="to-index">
to /
</Link>
<br />
</>
)
}
export const getServerSideProps = ({ locale, locales, defaultLocale }) => {
return {
props: {
locale,
locales,
defaultLocale,
},
| ame}</p>
<p id="router-as-path">{router.asPath | {
"filepath": "test/e2e/i18n-support-base-path/pages/developments/index.js",
"language": "javascript",
"file_size": 847,
"cut_index": 535,
"middle_length": 52
} |
variables = [
'PROCESS_ENV_KEY',
'ENV_FILE_KEY',
'ENV_FILE_EMPTY_FIRST',
'ENV_FILE_PROCESS_ENV',
'LOCAL_ENV_FILE_KEY',
'ENV_FILE_LOCAL_OVERRIDE_TEST',
'PRODUCTION_ENV_FILE_KEY',
'LOCAL_PRODUCTION_ENV_FILE_KEY',
'DEVELOPMENT_ENV_FILE_KEY',
'LOCAL_DEVELOPMENT_ENV_FILE_KEY',
'ENV_FILE_DEVELOPMENT_OVE... | NV_KEY',
'NEW_ENV_LOCAL_KEY',
'NEW_ENV_DEV_KEY',
'NEXT_PUBLIC_HELLO_WORLD',
]
export default async function handler(req, res) {
const items = {
nextConfigEnv: process.env.nextConfigEnv,
nextConfigPublicEnv: process.env.nextConfigPublicEnv, | 'LOCAL_TEST_ENV_FILE_KEY',
'ENV_FILE_TEST_OVERRIDE_TEST',
'ENV_FILE_TEST_LOCAL_OVERRIDEOVERRIDE_TEST',
'ENV_FILE_EXPANDED',
'ENV_FILE_EXPANDED_CONCAT',
'ENV_FILE_EXPANDED_ESCAPED',
'ENV_FILE_KEY_EXCLAMATION',
'NEW_E | {
"filepath": "test/e2e/env-config/pages/api/all.js",
"language": "javascript",
"file_size": 1230,
"cut_index": 518,
"middle_length": 229
} |
_TEST
const describeTurbopack =
isTurbopack && !isNextDeploy ? describe : describe.skip
// CORS so cross-origin script tags from `assetPrefix` can be fetched. Workers
// are NOT covered by CORS — `new Worker(crossOriginUrl)` is rejected
// regardless — so this only unblocks regular script loading.
const corsHeadersC... | t.js server bound to all interfaces.
*
* The fixture intercepts `new Worker()` to capture the URL the turbopack
* runtime helper resolved from `turbopackWorkerAssetPrefix`, so each test
* can assert on that URL directly.
*/
describeTurbopack('turbopac | gin setup: the page is served at `http://localhost:PORT/`,
* `assetPrefix` points to `http://127.0.0.1:PORT` (different origin —
* browsers treat `localhost` and `127.0.0.1` as distinct origins). Both
* resolve to the same Nex | {
"filepath": "test/e2e/turbopack-worker-asset-prefix/turbopack-worker-asset-prefix.test.ts",
"language": "typescript",
"file_size": 5186,
"cut_index": 716,
"middle_length": 229
} |
xtTestSetup({
files: __dirname,
// Deployed environment has it's own configured limits.
skipDeployment: true,
})
if (skipped) return
it('should accept request body over 10MB but only buffer up to limit', async () => {
const bodySize = 11 * 1024 * 1024 // 11MB
const body = 'x'... | Equal(10 * 1024 * 1024)
expect(responseBody.bodySize).toBeLessThan(bodySize)
expect(next.cliOutput).toContain(
'Request body exceeded 10MB for /api/echo'
)
})
it('should accept request body at exactly 10MB', async () => { | res.status).toBe(200)
const responseBody = await res.json()
expect(responseBody.message).toBe('Hello World')
// Should only buffer up to 10MB, not the full 11MB
expect(responseBody.bodySize).toBeLessThanOr | {
"filepath": "test/e2e/client-max-body-size/index.test.ts",
"language": "typescript",
"file_size": 6937,
"cut_index": 716,
"middle_length": 229
} |
sNextDeploy } from 'e2e-utils'
import { pathExists, readdir } from 'fs-extra'
import { join } from 'path'
describe('CPU Profiling - next build', () => {
const { next, isNextDev, skipped, isTurbopack } = nextTestSetup({
files: __dirname,
buildCommand: 'pnpm next build --experimental-cpu-prof',
dependencie... | r build', async () => {
const profileDir = join(next.testDir, '.next-profiles')
const profileDirExists = await pathExists(profileDir)
expect(profileDirExists).toBe(true)
const files = await readdir(profileDir)
const cpuProfiles = file | || skipped) {
it('skip for development/deploy mode', () => {})
return
}
beforeAll(async () => {
// Run the build with CPU profiling enabled
await next.build()
})
it('should create CPU profile files afte | {
"filepath": "test/e2e/cpu-profiling/cpu-profiling-build.test.ts",
"language": "typescript",
"file_size": 1917,
"cut_index": 537,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import { pathExists, readdir } from 'fs-extra'
import { join } from 'path'
import { retry } from 'next-test-utils'
describe('CPU Profiling - next dev', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
startCommand: 'pnpm next dev --experimental-cpu-prof',
... | ILL doesn't allow cleanup)
await next.stop('SIGTERM')
// Retry until profile files are written
const cpuProfiles = await retry(async () => {
const profileDirExists = await pathExists(profileDir)
expect(profileDirExists).toBe(true)
| join(next.testDir, '.next-profiles')
// Make a request to ensure the server is running
const res = await next.fetch('/')
expect(res.status).toBe(200)
// Stop the server with SIGTERM to trigger profile save (SIGK | {
"filepath": "test/e2e/cpu-profiling/cpu-profiling-dev.test.ts",
"language": "typescript",
"file_size": 1439,
"cut_index": 524,
"middle_length": 229
} |
sNextDeploy } from 'e2e-utils'
import { pathExists, readdir } from 'fs-extra'
import { join } from 'path'
import { retry } from 'next-test-utils'
describe('CPU Profiling - next start', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
startCommand: 'pnpm next start --experimental... | => {
const profileDir = join(next.testDir, '.next-profiles')
// Make a request to ensure the server is running
const res = await next.fetch('/')
expect(res.status).toBe(200)
// Stop the server with SIGTERM to trigger profile save (SI | es
if (isNextDev || isNextDeploy || skipped) {
it('skip for development/deploy mode', () => {})
return
}
beforeAll(async () => {
await next.start()
})
it('should create CPU profile files on exit', async () | {
"filepath": "test/e2e/cpu-profiling/cpu-profiling.test.ts",
"language": "typescript",
"file_size": 1703,
"cut_index": 537,
"middle_length": 229
} |
import { nextTestSetup } from 'e2e-utils'
describe('styled-jsx', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
dependencies: {
'styled-jsx': '5.0.0', // styled-jsx on user side
},
})
if (skipped) {
return
}
it('should contain styled-jsx ... | t('should render styles inside TypeScript', async () => {
const browser = await next.browser('/typescript')
const color = await browser.eval(
`getComputedStyle(document.querySelector('button')).color`
)
expect(color).toMatch('255, 0, | ring CSR', async () => {
const browser = await next.browser('/')
const color = await browser.eval(
`getComputedStyle(document.querySelector('button')).color`
)
expect(color).toMatch('0, 255, 255')
})
i | {
"filepath": "test/e2e/styled-jsx/index.test.ts",
"language": "typescript",
"file_size": 1010,
"cut_index": 512,
"middle_length": 229
} |
t.meta.glob is a Turbopack-only feature; skip under webpack
const testFn = process.env.IS_WEBPACK_TEST ? describe.skip : describe
testFn('import-meta-glob', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
it('should resolve lazy glob mo... | : 'skip',
})
})
it('should resolve eager glob modules', async () => {
const $ = await next.render$('/')
const eagerKeys = JSON.parse($('#eager-keys').text())
expect(eagerKeys).toEqual([
'./modules/bar.ts',
'./modules/foo.ts | o.ts',
'./modules/skip.ts',
])
const lazyResults = JSON.parse($('#lazy-results').text())
expect(lazyResults).toEqual({
'./modules/bar.ts': 'bar',
'./modules/foo.ts': 'foo',
'./modules/skip.ts' | {
"filepath": "test/e2e/import-meta-glob/import-meta-glob.test.ts",
"language": "typescript",
"file_size": 2597,
"cut_index": 563,
"middle_length": 229
} |
./modules/*.ts')
// Eager glob
const eagerModules = import.meta.glob('./modules/*.ts', { eager: true })
// Named import (eager)
const defaultExports = import.meta.glob('./modules/*.ts', {
import: 'default',
eager: true,
})
// Negative pattern
const filteredModules = import.meta.glob(['./modules/*.ts', '!**/skip.... | (mod as any).name
}
// Get eager module names
const eagerKeys = Object.keys(eagerModules).sort()
const eagerResults: Record<string, string> = {}
for (const key of eagerKeys) {
eagerResults[key] = (eagerModules[key] as any).name
}
// Ge | age() {
// Resolve lazy modules
const lazyKeys = Object.keys(lazyModules).sort()
const lazyResults: Record<string, string> = {}
for (const key of lazyKeys) {
const mod = await lazyModules[key]()
lazyResults[key] = | {
"filepath": "test/e2e/import-meta-glob/app/page.tsx",
"language": "tsx",
"file_size": 2422,
"cut_index": 563,
"middle_length": 229
} |
ort { FileRef, nextTestSetup } from 'e2e-utils'
import { spawnSync } from 'child_process'
function createTemporaryFixture(fixtureName: string) {
const fixturePath = join(__dirname, fixtureName)
const stat = statSync(fixturePath)
if (!stat.isDirectory()) {
throw new Error(`Fixture ${fixtureName} is not a dire... | `experimental-test` mode
skipDeployment: true,
})
if (skipped) return
afterAll(async () => {
await basicExample.destroy()
})
describe('first time setup', () => {
it.each([['first-time-setup-js'], ['first-time-setup-ts']])(
' | mple, skipped } = nextTestSetup({
files: new FileRef(join(__dirname, 'basic-example')),
dependencies: {
'@playwright/test': '1.43.1',
},
skipStart: true,
// This doesn't need to be deployed as it's using | {
"filepath": "test/e2e/next-test/next-test.test.ts",
"language": "typescript",
"file_size": 5633,
"cut_index": 716,
"middle_length": 229
} |
'start',
assertions: (getOutput: () => string) => void | Promise<void>
) {
if (mode === 'dev') {
await next.start()
try {
await next.fetch('/').catch(() => {})
await retry(async () => {
await assertions(() => next.cliOutput)
})
} finally {
await next... | ) => {
await writeConfig(
[
{
source: `/:path*`,
headers: [],
},
],
'headers'
)
await captureStderr(mode, (getOutput) => {
const stderr = getOutput()
expe | }
afterAll(async () => {
await next.patchFile('next.config.js', `module.exports = {}\n`)
})
function runTests(mode: 'dev' | 'start') {
it('should error when empty headers array is present on header item', async ( | {
"filepath": "test/e2e/invalid-custom-routes/invalid-custom-routes.test.ts",
"language": "typescript",
"file_size": 18100,
"cut_index": 1331,
"middle_length": 229
} |
{ isNextDev, nextTestSetup } from 'e2e-utils'
import { renderViaHTTP } from 'next-test-utils'
describe('handle-non-hoisted-swc-helpers', () => {
const { next } = nextTestSetup({
files: {
'pages/index.js': `
export default function Page() {
return <p>hello world</p>
}
exp... | },
installCommand:
'npm install; mkdir -p node_modules/next/node_modules/@swc; mv node_modules/@swc/helpers node_modules/next/node_modules/@swc/',
buildCommand: 'npm run build',
startCommand: isNextDev ? 'npm run dev' : 'npm run start',
| ate.now()
}
}
}
`,
},
packageJson: {
packageManager: 'npm@10.9.2',
scripts: {
build: 'next build',
dev: 'next dev',
start: 'next start',
},
| {
"filepath": "test/e2e/handle-non-hoisted-swc-helpers/index.test.ts",
"language": "typescript",
"file_size": 1167,
"cut_index": 518,
"middle_length": 229
} |
RewriteTo,
} from './shared-tests.util'
import { nextTestSetup, isNextDev } from 'e2e-utils'
// we don't need to exhaustively test this, just do some basic sanity checks
// for use in combiantion with basePath
;(isNextDev ? describe : describe.skip)(
'Trailing slashes in development mode, with basepath, trailingSlas... | ['/docs', '/docs/'],
['/docs/catch-all/hello/world', '/docs/catch-all/hello/world/'],
['/docs/catch-all/hello.world/', '/docs/catch-all/hello.world'],
])
testLinkShouldRewriteTo(next, [
['/docs/linker?href=/about', '/docs/a | rect(next, [
['/docs/about', '/docs/about/'],
| {
"filepath": "test/e2e/trailing-slashes/basepath.test.ts",
"language": "typescript",
"file_size": 953,
"cut_index": 582,
"middle_length": 52
} |
.test.ts` so that both test suites can be run in parallel.
import cheerio from 'cheerio'
import type { NextInstance, Playwright } from 'e2e-utils'
export function testShouldRedirect(
next: NextInstance,
expectations: [string, string][]
) {
it.each(expectations)(
'%s should redirect to %s',
async (route,... | th %s',
async (route, expectedPage, expectedRouterPath) => {
const res = await next.fetch(route, { redirect: 'error' })
expect(res.status).toBe(200)
const $ = cheerio.load(await res.text())
expect($('#page-marker').text()).toBe( | expect(pathname).toBe(expectedLocation)
}
)
}
export function testShouldResolve(
next: NextInstance,
expectations: [string, string, string][]
) {
it.each(expectations)(
'%s should resolve to %s, with router pa | {
"filepath": "test/e2e/trailing-slashes/shared-tests.util.ts",
"language": "typescript",
"file_size": 3757,
"cut_index": 614,
"middle_length": 229
} |
ndalone-expect */
import {
testShouldRedirect,
testLinkShouldRewriteTo,
testShouldResolve,
testExternalLinkShouldRewriteTo,
} from './shared-tests.util'
import { nextTestSetup } from 'e2e-utils'
import { join } from 'path'
describe('Trailing slashes with trailingSlash: true', () => {
const { next, isNextSta... | s', '/about'],
[
'/catch-all/hello/world/',
'/catch-all/[...slug].js',
'/catch-all/[...slug]',
],
['/about/?hello=world', '/about.js', '/about'],
])
testLinkShouldRewriteTo(next, [
['/linker?href=/', '/'],
['/link | catch-all/hello/world/'],
['/catch-all/hello.world/', '/catch-all/hello.world'],
])
testShouldResolve(next, [
// visited url, expected page, expected router path
['/', '/index.js', '/'],
['/about/', '/about.j | {
"filepath": "test/e2e/trailing-slashes/with-trailing-slash.test.ts",
"language": "typescript",
"file_size": 2484,
"cut_index": 563,
"middle_length": 229
} |
ndalone-expect */
import {
testShouldRedirect,
testLinkShouldRewriteTo,
testShouldResolve,
testExternalLinkShouldRewriteTo,
} from './shared-tests.util'
import { nextTestSetup } from 'e2e-utils'
import { join } from 'path'
describe('Trailing slashes with trailingSlash: false', () => {
const { next, isNextSt... | js', '/about'],
[
'/catch-all/hello/world',
'/catch-all/[...slug].js',
'/catch-all/[...slug]',
],
['/about?hello=world', '/about.js', '/about'],
])
testLinkShouldRewriteTo(next, [
['/linker?href=/', '/'],
['/linke | '/catch-all/hello/world'],
['/catch-all/hello.world/', '/catch-all/hello.world'],
])
testShouldResolve(next, [
// visited url, expected page, expected router path
['/', '/index.js', '/'],
['/about', '/about. | {
"filepath": "test/e2e/trailing-slashes/without-trailing-slash.test.ts",
"language": "typescript",
"file_size": 2198,
"cut_index": 563,
"middle_length": 229
} |
from 'e2e-utils'
import { retry } from 'next-test-utils'
import path from 'path'
describe('deprecation-warnings', () => {
describe('without next.config.js', () => {
const { next } = nextTestSetup({
files: path.join(__dirname, 'fixtures/no-config'),
skipStart: true,
})
it('should not emit any... | res/with-deprecated-config'),
skipStart: true,
})
it('should emit deprecation warnings for explicitly configured deprecated options', async () => {
await next.start()
await retry(async () => {
const logs = next.cliOutput | ot.toContain('has been renamed')
expect(logs).not.toContain('no longer needed')
})
})
describe('with deprecated config options', () => {
const { next } = nextTestSetup({
files: path.join(__dirname, 'fixtu | {
"filepath": "test/e2e/deprecation-warnings/deprecation-warnings.test.ts",
"language": "typescript",
"file_size": 1977,
"cut_index": 537,
"middle_length": 229
} |
io from 'cheerio'
import { FileRef, nextTestSetup } from 'e2e-utils'
import { renderViaHTTP } from 'next-test-utils'
import { join } from 'path'
const mockedGoogleFontResponses = require.resolve(
'./google-font-mocked-responses.js'
)
describe('next/font/google basepath', () => {
if ((global as any).isNextDeploy) ... | await renderViaHTTP(next.url, '/dashboard')
const $ = cheerio.load(html)
// Preconnect
expect($('link[rel="preconnect"]').length).toBe(0)
// Preload
expect($('link[as="font"]').length).toBe(1)
expect($('link[as="font"]').get(0).a | onfig.js': new FileRef(join(__dirname, 'basepath/next.config.js')),
},
env: {
NEXT_FONT_GOOGLE_MOCKED_RESPONSES: mockedGoogleFontResponses,
},
})
test('preload correct files', async () => {
const html = | {
"filepath": "test/e2e/next-font/basepath.test.ts",
"language": "typescript",
"file_size": 1350,
"cut_index": 524,
"middle_length": 229
} |
import { join } from 'path'
const mockedGoogleFontResponses = require.resolve(
'./google-font-mocked-responses.js'
)
describe('next/font/google fetch error', () => {
const isDev = (global as any).isNextDev
if ((global as any).isNextDeploy) {
it('should skip next deploy for now', () => {})
return
}
... | ser('/')
const ascentOverride = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Inter Fallback")).ascentOverride'
)
expect(ascentOverride).toMatchInlineSnapshot(`"90.44%"`)
const | tResponses,
},
skipStart: true,
})
if (isDev) {
it('should use a fallback font in dev', async () => {
await next.start()
const outputIndex = next.cliOutput.length
const browser = await next.brow | {
"filepath": "test/e2e/next-font/google-fetch-error.test.ts",
"language": "typescript",
"file_size": 2141,
"cut_index": 563,
"middle_length": 229
} |
BA-UvWbX2vVnXBbObj2OVTS2mu0SC55K5gw.woff2) format('woff2');
unicode-range: U+0590-05FF, U+200C-2010, U+20AA, U+25CC, U+FB1D-FB4F;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300 800;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s... | BA-UvWbX2vVnXBbObj2OVTSGmu0SC55K5gw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
| EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300 800;
font-stretch: 100%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/opensans/v34/memvYaGs126MiZp | {
"filepath": "test/e2e/next-font/google-font-mocked-responses.js",
"language": "javascript",
"file_size": 38998,
"cut_index": 2151,
"middle_length": 229
} |
// Turbopack includes the file hash
/\/_next\/static\/(immutable\/)?media\/(.*)\.p\.(.*)\.woff2/
)
} else {
expect(href).toMatch(/\/_next\/static\/(immutable\/)?media\/(.*)\.p\.woff2/)
}
}
describe('next/font', () => {
if ((global as any).isNextDeploy) {
it('should skip next deploy for now... | bal as any).isNextDev) {
it('should use production cache control for fonts', async () => {
const $ = await next.render$('/')
const link = $('[rel="preload"][as="font"]').attr('href')
expect(link).toBeDefined()
const res = await | ts`)),
fonts: new FileRef(join(__dirname, `app/fonts`)),
},
dependencies: {
'@next/font': 'canary',
},
env: {
NEXT_FONT_GOOGLE_MOCKED_RESPONSES: mockedGoogleFontResponses,
},
})
if ((glo | {
"filepath": "test/e2e/next-font/index.test.ts",
"language": "typescript",
"file_size": 23558,
"cut_index": 1331,
"middle_length": 229
} |
'next-test-utils'
import { join } from 'path'
const mockedGoogleFontResponses = require.resolve(
'./google-font-mocked-responses.js'
)
const isDev = (global as any).isNextDev
describe('next/font/google with-font-declarations-file', () => {
if ((global as any).isNextDeploy) {
it('should skip next deploy for n... | length).toBe(0)
if (isDev) {
// In dev all fonts will be preloaded since it's before DCE
expect($('link[as="font"]').length).toBe(4)
} else {
// Preload
expect($('link[as="font"]').length).toBe(
// TODO: Remove this | tResponses,
},
})
test('preload correct files at /inter', async () => {
const html = await renderViaHTTP(next.url, '/inter')
const $ = cheerio.load(html)
// Preconnect
expect($('link[rel="preconnect"]'). | {
"filepath": "test/e2e/next-font/with-font-declarations-file.test.ts",
"language": "typescript",
"file_size": 4463,
"cut_index": 614,
"middle_length": 229
} |
import { findPort, renderViaHTTP, fetchViaHTTP } from 'next-test-utils'
import { join } from 'path'
import spawn from 'cross-spawn'
describe('next/font/google with proxy', () => {
if ((global as any).isNextDeploy) {
it('should skip next deploy', () => {})
return
}
const { next } = nextTestSetup({
fi... | ERVER_PORT.toString(),
},
})
await next.start({
env: { http_proxy: 'http://localhost:' + PROXY_PORT },
})
})
afterAll(() => {
proxy?.kill('SIGKILL')
})
// Reqwest doesn't seem to fully work with https proxy
;(process | RVER_PORT = await findPort()
proxy = spawn('node', [require.resolve('./with-proxy/server.js')], {
stdio: 'inherit',
env: {
...process.env,
PROXY_PORT: PROXY_PORT.toString(),
SERVER_PORT: S | {
"filepath": "test/e2e/next-font/with-proxy.test.ts",
"language": "typescript",
"file_size": 2349,
"cut_index": 563,
"middle_length": 229
} |
P } from 'next-test-utils'
import { join } from 'path'
const mockedGoogleFontResponses = require.resolve(
'./google-font-mocked-responses.js'
)
describe('next/font/google without-preloaded-fonts without _app', () => {
if ((global as any).isNextDeploy) {
it('should skip next deploy for now', () => {})
retu... | preload', async () => {
const html = await renderViaHTTP(next.url, '/no-preload')
const $ = cheerio.load(html)
// Preconnect
expect($('link[rel="preconnect"]').length).toBe(1)
expect($('link[rel="preconnect"]').get(0).attribs).toEqual( | ithout-fonts.js': new FileRef(
join(__dirname, 'without-preloaded-fonts/pages/without-fonts.js')
),
},
env: {
NEXT_FONT_GOOGLE_MOCKED_RESPONSES: mockedGoogleFontResponses,
},
})
test('without | {
"filepath": "test/e2e/next-font/without-preloaded-fonts.test.ts",
"language": "typescript",
"file_size": 3143,
"cut_index": 614,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.