prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
have polyfilled node.js builtins for the browser correctly', async () => {
const browser = await next.browser('/')
await browser.waitForCondition('window.didRender', 15000)
const data = await browser
.waitForElementByCss('#node-browser-polyfills')
.text()
const parsedData = JSON.parse(data... | dData.https).toBe(true)
expect(parsedData.os).toBe('\n')
expect(parsedData.path).toBe('/hello/world/test.txt')
expect(parsedData.process).toBe('browser')
expect(parsedData.querystring).toBe('a=b')
expect(parsedData.stringDecoder).toBe(t | o world')
expect(parsedData.stream).toBe(true)
expect(parsedData.assert).toBe(true)
expect(parsedData.constants).toBe(7)
expect(parsedData.domain).toBe(true)
expect(parsedData.http).toBe(true)
expect(parse | {
"filepath": "test/development/basic/node-builtins.test.ts",
"language": "typescript",
"file_size": 7101,
"cut_index": 716,
"middle_length": 229
} |
import { waitForNoRedbox, check } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils'
import stripAnsi from 'strip-ansi'
// TODO: investigate occasional failure
describe.skip('Project Directory Renaming', () => {
const { next } = nextTestSetup({
files: {
'pages/index.js': `
export d... | ove(next.testDir, newTestDir)
next.testDir = newTestDir
await check(
() => stripAnsi(next.cliOutput),
/Detected project directory rename, restarting in new location/
)
await check(async () => {
return (await browser.eval | ()
})
it('should detect project dir rename and restart', async () => {
const browser = await next.browser('/')
await browser.eval('window.beforeNav = 1')
let newTestDir = `${next.testDir}-renamed`
await fs.m | {
"filepath": "test/development/basic/project-directory-rename.test.ts",
"language": "typescript",
"file_size": 1774,
"cut_index": 537,
"middle_length": 229
} |
n } from 'path'
import { FileRef, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
// TODO: Somehow the warning doesn't show up with Turbopack, even though the transform is not enabled.
// TODO: It no longer shows up with Webpack either in tests.
describe.skip('styled-components SWC transform',... | {
let browser
try {
// Compile /_error
browser = await next.browser('/404')
await browser.loadPage(new URL('/', next.url).toString())
await retry(async () => {
const logs = await browser.log()
expect(logs).t | eRef(join(__dirname, 'styled-components-disabled/pages')),
},
dependencies: {
'styled-components': '6.1.16',
},
})
it('should have hydration mismatch with styled-components transform disabled', async () => | {
"filepath": "test/development/basic/styled-components-disabled.test.ts",
"language": "typescript",
"file_size": 1358,
"cut_index": 524,
"middle_length": 229
} |
estSetup, type Playwright } from 'e2e-utils'
import { check } from 'next-test-utils'
// [TODO]: It is unclear why turbopack takes longer to run this test
// remove once it's fixed
if (process.env.IS_TURBOPACK_TEST) {
jest.setTimeout(1000 * 60 * 5)
}
describe('TailwindCSS JIT', () => {
const { next } = nextTestSet... | , async () => {
let browser: Playwright
try {
browser = await next.browser('/')
const text = await browser.elementByCss('.text-6xl').text()
expect(text).toMatch(/Welcome to/)
const cssBlue = await browser
.elementByC | ailwind-jit/tailwind.config.js')
),
pages: new FileRef(join(__dirname, 'tailwind-jit/pages')),
},
dependencies: {
tailwindcss: '2.2.19',
postcss: '8.3.5',
},
})
it('works with JIT enabled' | {
"filepath": "test/development/basic/tailwind-jit.test.ts",
"language": "typescript",
"file_size": 2050,
"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-6xl font-bold">
Welcome to{' '}
<a className="text-blue-600" href="https://nextjs.org" id="test-li... | 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">
Find in-depth in | 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.org/docs"
| {
"filepath": "test/development/basic/tailwind-jit/pages/index.js",
"language": "javascript",
"file_size": 2467,
"cut_index": 563,
"middle_length": 229
} |
import { join } from 'path'
import { nextTestSetup } from 'e2e-utils'
import { waitForNoRedbox } from 'next-test-utils'
// This is implemented in Turbopack, but Turbopack doesn't log the module count.
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'Skipped in Turbopack',
() => {
describe('optimiz... | const $ = await next.render$('/mui')
expect($('#button').text()).toContain('button')
expect($('#typography').text()).toContain('typography')
const browser = await next.browser('/mui')
await waitForNoRedbox(browser)
| : {
'@mui/material': '5.15.15',
'@emotion/react': '11.11.1',
'@emotion/styled': '11.11.0',
},
})
it('should support MUI', async () => {
// Ensure that MUI is working
| {
"filepath": "test/development/basic/barrel-optimization/barrel-optimization-mui.test.ts",
"language": "typescript",
"file_size": 1015,
"cut_index": 512,
"middle_length": 229
} |
n } from 'path'
import { nextTestSetup } from 'e2e-utils'
// This is implemented in Turbopack, but Turbopack doesn't log the module count.
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'Skipped in Turbopack',
() => {
describe('optimizePackageImports - basic', () => {
const { next } = nextT... | const html = await next.render('/recursive')
expect(html).toContain('<h1>42</h1>')
})
it('should support visx', async () => {
const html = await next.render('/visx')
expect(html).toContain('<linearGradient')
})
| ui/react': '1.7.17',
'@heroicons/react': '2.0.18',
'@visx/visx': '3.3.0',
'recursive-barrel': '1.0.0',
},
})
it('should handle recursive wildcard exports', async () => {
| {
"filepath": "test/development/basic/barrel-optimization/barrel-optimization.test.ts",
"language": "typescript",
"file_size": 1430,
"cut_index": 524,
"middle_length": 229
} |
IceCream,
BackpackIcon,
LucideActivity,
Code,
Menu,
SortAsc,
SortAscIcon,
LucideSortDesc,
VerifiedIcon,
CurlyBraces,
Slash,
SquareGantt,
CircleSlashed,
SquareKanban,
SquareKanbanDashed,
Stars,
Edit,
Edit2,
LucideEdit3,
TextSelection,
createLucideIcon,
} from 'lucide-react'
impor... | quareKanban />
<SquareKanbanDashed />
<Stars />
<Edit />
<Edit2 />
<LucideEdit3 />
<TextSelection />
<Tab.Group>
<Tab.List>
<Tab>Tab 1</Tab>
<Tab>Tab 2</Tab>
<Tab>Tab 3</Tab>
| <LucideActivity />
<Code />
<Menu />
<SortAsc />
<SortAscIcon />
<LucideSortDesc />
<VerifiedIcon />
<CurlyBraces />
<Slash />
<SquareGantt />
<CircleSlashed />
<S | {
"filepath": "test/development/basic/barrel-optimization/fixture/components/slow-component.js",
"language": "javascript",
"file_size": 1696,
"cut_index": 537,
"middle_length": 229
} |
t styled, { css } from 'styled-components'
const Button = styled.a`
/* This renders the buttons above... Edit me! */
display: inline-block;
border-radius: 3px;
padding: 0.5rem 0;
margin: 0.5rem 1rem;
width: 11rem;
background: transparent;
color: white;
border: 2px solid white;
/* The GitHub button ... | n (
<div>
<Button
href="https://github.com/styled-components/styled-components"
target="_blank"
rel="noopener"
$primary
>
GitHub
</Button>
<Button href="/docs">Documentation</Button>
| me() {
retur | {
"filepath": "test/development/basic/styled-components-disabled/pages/index.js",
"language": "javascript",
"file_size": 800,
"cut_index": 517,
"middle_length": 14
} |
fetchViaHTTP, renderViaHTTP } from 'next-test-utils'
describe('styled-components SWC transform', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
'styled-components': '6.1.16',
},
})
async function matchLogs$(browser) {
let foundLog = false
const browserLogs =... | 4')
// Try 4 times to be sure there is no mismatch
expect(await matchLogs$(browser)).toBe(false)
await browser.refresh()
expect(await matchLogs$(browser)).toBe(false)
await browser.refresh()
expect(await matchLogs$(brow | it('should not have hydration mismatch with styled-components transform enabled', async () => {
let browser
try {
browser = await next.browser('/')
// Compile /_error
await fetchViaHTTP(next.url, '/40 | {
"filepath": "test/development/basic/styled-components/styled-components.test.ts",
"language": "typescript",
"file_size": 2383,
"cut_index": 563,
"middle_length": 229
} |
buttons above... Edit me! */
display: inline-block;
border-radius: 3px;
padding: 0.5rem 0;
margin: 0.5rem 1rem;
width: 11rem;
background: transparent;
color: white;
border: 2px solid white;
/* The GitHub button is a primary button
* edit this to target it specifically! */
${(props) =>
props... | on
href="https://github.com/styled-components/styled-components"
target="_blank"
rel="noopener"
$primary
>
GitHub
</Button>
<Button id="btn" href="/docs">
Documentation
</Button>
| background: black;
`}
>
<Butt | {
"filepath": "test/development/basic/styled-components/pages/index.js",
"language": "javascript",
"file_size": 927,
"cut_index": 606,
"middle_length": 52
} |
nextTestSetup } from 'e2e-utils'
export function runBasicHmrTest(nextConfig: {
basePath: string
assetPrefix: string
}) {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
nextConfig,
patchFileDelay: 500,
forcedPort: 'random',
})
const { basePath } = nextConfig
it('should have... | r.elementByCss('#ready').text()).toBe('yes')
})
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({
hello: 'world',
})
})
it('should have correct router.isReady for getStaticProps page', async () => {
let br | oBe('yes')
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({})
browser = await next.browser(basePath + '/auto-export-is-ready?hello=world')
await retry(async () => {
expect(await browse | {
"filepath": "test/development/basic/hmr/run-basic-hmr-test.util.ts",
"language": "typescript",
"file_size": 3179,
"cut_index": 614,
"middle_length": 229
} |
Output).toContain('GET /hmr/new-page 404')
let cliOutputLength = next.cliOutput.length
// Add the page
await next.patchFile(
join('pages', 'hmr', 'new-page.js'),
'export default () => (<div id="new-page">the-new-page</div>)',
async () => {
await retry(async () => {
expec... | )
})
expect(next.cliOutput.slice(cliOutputLength)).toContain(
'GET /hmr/new-page 404'
)
})
it('should recover from 404 after a page has been added with dynamic segments', async () => {
const browser = await next.browser(basePa | OutputLength = next.cliOutput.length
}
)
// page was deleted at the end of patchFile
await retry(async () => {
expect(await getBrowserBodyText(browser)).toMatch(
/This page could not be found/
| {
"filepath": "test/development/basic/hmr/run-error-recovery-hmr-test.util.ts",
"language": "typescript",
"file_size": 20494,
"cut_index": 1331,
"middle_length": 229
} |
tils'
import { nextTestSetup } from 'e2e-utils'
export function runFullReloadHmrTest(nextConfig: {
basePath: string
assetPrefix: string
}) {
const { next } = nextTestSetup({
files: __dirname,
nextConfig,
patchFileDelay: 500,
})
const { basePath } = nextConfig
it('should warn about full reload ... | ').text()).toBe('hello world')
expect(next.cliOutput.slice(start)).not.toContain(cliWarning)
const currentFileContent = await next.readFile(
'./pages/hmr/anonymous-page-function.js'
)
const newFileContent = currentFileContent.replace | const cliWarning =
'Fast Refresh had to perform a full reload when ./pages/hmr/anonymous-page-function.js changed. Read more: https://nextjs.org/docs/messages/fast-refresh-reload'
expect(await browser.elementByCss('p | {
"filepath": "test/development/basic/hmr/run-full-reload-hmr-test.util.ts",
"language": "typescript",
"file_size": 2946,
"cut_index": 563,
"middle_length": 229
} |
add it back', () => {
it('should load the page properly', async () => {
const contactPagePath = join('pages', 'hmr', 'contact.js')
const newContactPagePath = join('pages', 'hmr', '_contact.js')
const browser = await next.browser(basePath + '/hmr/contact')
try {
const text = await br... | /This page could not be found/
)
})
expect(next.cliOutput.slice(cliOutputLength)).toMatch(
/GET .*\/hmr\/contact 404/
)
cliOutputLength = next.cliOutput.length
// Rename the file back | Output.length
// Rename the file to mimic a deleted page
await next.renameFile(contactPagePath, newContactPagePath)
await retry(async () => {
expect(await getBrowserBodyText(browser)).toMatch(
| {
"filepath": "test/development/basic/hmr/run-hot-module-reload-hmr-test.util.ts",
"language": "typescript",
"file_size": 10098,
"cut_index": 921,
"middle_length": 229
} |
or('[data-indicator-status]')
const badge = root.querySelector('[data-next-badge]')
const status = badge ? badge.getAttribute('data-status') : null
// Check if we're showing any status
window.showedBuilder = window.showedBuilder || (
statusElement !== null || (status && status !== 'none... | er = await next.browser('/gsp-blog/first')
await check(() => browser.elementByCss('#change').text(), 'change me')
await browser.eval(`window.beforeChange = 'hi'`)
const props = JSON.parse(await browser.elementByCss('#props').text())
const |
files: {
pages: new FileRef(join(__dirname, '../pages')),
lib: new FileRef(join(__dirname, '../lib')),
},
})
it('should not reload page when client-side is changed too GSP', async () => {
const brows | {
"filepath": "test/development/basic/gssp-ssr-change-reloading/test/index.test.ts",
"language": "typescript",
"file_size": 12302,
"cut_index": 921,
"middle_length": 229
} |
</body>
</Html>
)
}
Document.getInitialProps = (ctx) => {
return ctx.defaultGetInitialProps(ctx)
}
`
const basePath = process.env.TEST_BASE_PATH || ''
const srcPrefix = process.env.TEST_SRC_DIR ? 'src/' : ''
describe('next/dynamic', () => {
const { next } = nextTestSetup({
files: {
[`${srcPre... | BABEL === '1' && {
'.babelrc': `{ "presets": ["next/babel"] }`,
}),
},
nextConfig: {
basePath,
},
})
async function get$(path, query?: any) {
const html = await renderViaHTTP(next.url, path, query)
return ch | [`${srcPrefix}/pages/_document.js`]: customDocumentGipContent,
}),
// When it's not turbopack and babel is enabled, we add a .babelrc file.
...(!process.env.IS_TURBOPACK_TEST &&
process.env.TEST_ | {
"filepath": "test/development/basic/next-dynamic/next-dynamic.test.ts",
"language": "typescript",
"file_size": 10522,
"cut_index": 921,
"middle_length": 229
} |
h'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
describe('useDefineForClassFields SWC option', () => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixture'),
dependencies: {
mobx: '6.3.7',
typescript: 'latest',
'@types/react': 'latest',
... | n with useDefineForClassFields enabled", async () => {
const browser = await next.browser('/animal')
expect(await browser.elementByCss('#dog').text()).toBe('undefined')
expect(await browser.elementByCss('#dogDecl').text()).toBe('dog')
})
a | await browser.elementByCss('#action').click()
await check(
() => browser.elementByCss('#name').text(),
/this is my name: next/
)
})
it("Initializes resident to undefined after the call to 'super()' whe | {
"filepath": "test/development/basic/define-class-fields/define-class-fields.test.ts",
"language": "typescript",
"file_size": 1758,
"cut_index": 537,
"middle_length": 229
} |
React from 'react'
interface Animal {
animalStuff: any
}
interface Dog extends Animal {
dogStuff: any
}
class AnimalHouse {
resident: Animal
constructor(animal: Animal) {
this.resident = animal
}
}
class DogHouse extends AnimalHouse {
// Initializes 'resident' to 'undefined'
// after the call to 's... | or */
constructor(dog: Dog) {
super(dog)
}
}
export default function AnimalView() {
const dog = new DogHouse({
animalStuff: 'animal',
dogStuff: 'dog',
})
const dogDeclare = new DogHouseWithDeclare({
animalStuff: 'animal',
dog | */
constructor(dog: Dog) {
super(dog)
}
}
class DogHouseWithDeclare extends AnimalHouse {
declare resident: Dog
// useless constructor only for type checker
/* eslint-disable @typescript-eslint/no-useless-construct | {
"filepath": "test/development/basic/define-class-fields/fixture/pages/animal.tsx",
"language": "tsx",
"file_size": 1169,
"cut_index": 518,
"middle_length": 229
} |
h'
import { nextTestSetup } from 'e2e-utils'
import { check, retry } from 'next-test-utils'
describe('asset-prefix', () => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixture'),
})
it('should load the app properly without reloading', async () => {
const browser = await next.browser('/')
... | vigate to another page without hard navigating', async () => {
const browser = await next.browser('/')
await browser.eval(`window.__v = 1`)
await browser.elementByCss('[href="/page2"]').click()
await retry(async () => {
expect(await b | const hasError = logs.some((log) =>
log.message.includes('Failed to fetch')
)
return hasError ? 'error' : 'success'
}, 'success')
expect(await browser.eval(`window.__v`)).toBe(1)
})
it('should na | {
"filepath": "test/development/basic/asset-prefix/asset-prefix.test.ts",
"language": "typescript",
"file_size": 1698,
"cut_index": 537,
"middle_length": 229
} |
rypto'
import vm from 'vm'
import constants from 'constants'
import domain from 'domain'
import http from 'http'
import https from 'https'
import os from 'os'
// TODO: These are accidentally polyfilled in edge runtime currently.
// import punycode from 'punycode'
// import process from 'process'
// import querystring f... | leware(request) {
if (request.nextUrl.pathname !== '/middleware-test') {
return
}
const response = NextResponse.next()
let emitted = false
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter()
// Only do this once so | ed in edge
import { Buffer } from 'buffer'
import assert from 'assert'
import util from 'util'
import { EventEmitter } from 'events'
// Other imports
import { NextResponse } from 'next/server'
export default async function midd | {
"filepath": "test/development/basic/node-builtins/middleware.js",
"language": "javascript",
"file_size": 3124,
"cut_index": 614,
"middle_length": 229
} |
rt path from 'path'
import crypto from 'crypto'
import { Buffer } from 'buffer'
import vm from 'vm'
import assert from 'assert'
import constants from 'constants'
import { useEffect, useState } from 'react'
import domain from 'domain'
import http from 'http'
import https from 'https'
import os from 'os'
import punycode ... | t writable = new Writable({
write(_chunk, _encoding, callback) {
callback()
},
})
writable.on('finish', () => {
closedStream = true
})
writable.end()
assert.ok(true)
assert.ok(!!domain)
assert.ok(!! | 'tty'
import util from 'util'
import zlib from 'zlib'
import 'setimmediate'
export default function NodeBrowserPolyfillPage() {
const [state, setState] = useState({})
useEffect(() => {
let closedStream = false
cons | {
"filepath": "test/development/basic/node-builtins/app/client-component/page.js",
"language": "javascript",
"file_size": 2244,
"cut_index": 563,
"middle_length": 229
} |
ck
// Import a .txt file using a raw loader via turbopackLoader
// turbopackAs tells turbopack to treat the loader output as JavaScript
import rawText from '../data.txt' with { turbopackLoader: 'test-raw-loader', turbopackAs: '*.js' }
// Import a .js file with a replace loader via turbopackLoader with options
import re... | port a non-.json file and treat it as JSON via turbopackModuleType
import jsonData from '../data.jsonlike' with { turbopackLoader: 'test-identity-loader', turbopackModuleType: 'json' }
// Normal rules should still work at the same time
import jsonData2 fro | txt file using turbopackModuleType to treat loader output as ecmascript
import rawTextViaModuleType from '../data2.txt' with { turbopackLoader: '../node_modules/test-raw-loader/index.js', turbopackModuleType: 'ecmascript' }
// Im | {
"filepath": "test/development/app-dir/turbopack-import-assertions-use/app/page.tsx",
"language": "tsx",
"file_size": 1363,
"cut_index": 524,
"middle_length": 229
} |
ort { FileRef, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import path from 'path'
const envFile = '.env.development.local'
describe(`app-dir hmr-env`, () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
patchFileDel... | ect(await browser.elementByCss('p').text()).toBe('ipad')
})
})
// ensure it's restored back to "mac" before the next test
await retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('mac')
})
| browser = await next.browser(`/env/${page}`)
expect(await browser.elementByCss('p').text()).toBe('mac')
await next.patchFile(envFile, 'MY_DEVICE="ipad"', async () => {
await retry(async () => {
exp | {
"filepath": "test/development/app-hmr/hmr-env.test.ts",
"language": "typescript",
"file_size": 1061,
"cut_index": 515,
"middle_length": 229
} |
import { retry, waitFor } from 'next-test-utils'
import path from 'path'
describe('app-dir server restart', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
patchFileDelay: 1000,
forcedPort: 'random',
})
it('should reload the page whe... | ick()
expect(await browser.elementById('counter-value').text()).toBe('Count: 1')
// Click again to make it 2
await browser.elementById('increment-button').click()
expect(await browser.elementById('counter-value').text()).toBe('Count: 2')
| })
// Verify the counter is at 0 initially
expect(await browser.elementById('counter-value').text()).toBe('Count: 0')
// Click increment button to change state
await browser.elementById('increment-button').cl | {
"filepath": "test/development/app-hmr/server-restart.test.ts",
"language": "typescript",
"file_size": 2069,
"cut_index": 563,
"middle_length": 229
} |
from 'e2e-utils'
import {
getRedboxDescription,
getRedboxSource,
waitForRedbox,
} from 'next-test-utils'
describe('Invalid Image Import (dev)', () => {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
})
it('should show error', async () => {
const browser = await next.browser('/')
... | cription).toContain(
'Image import "../public/invalid.svg" is not a valid image file. The image may be corrupted or an unsupported format.'
)
}
const source = await getRedboxSource(browser)
if (isTurbopack) {
expect(source). | (process.env.NEXT_RSPACK) {
expect(description).toContain(
'Image import "../public/invalid.svg" is not a valid image file. The image may be corrupted or an unsupported format.'
)
} else {
expect(des | {
"filepath": "test/development/next-image-new/invalid-image-import/invalid-image-import.test.ts",
"language": "typescript",
"file_size": 1767,
"cut_index": 537,
"middle_length": 229
} |
rt { useSearchParams, usePathname, useParams } from 'next/navigation'
function Box({
label,
children,
}: {
label: string
children: React.ReactNode
}) {
return (
<div
style={{
background: '#fff',
border: '1px solid #ddd',
borderRadius: 8,
padding: '1rem',
marg... | ode>{pathname}</code>
</p>
)
}
function ParamsDisplay() {
const params = useParams()
return (
<p style={{ margin: 0 }} data-testid="client-params">
<code>slug={String(params.slug ?? '(none)')}</code>
</p>
)
}
function SearchPar | marginBottom: '0.5rem',
}}
>
{label}
</div>
{children}
</div>
)
}
function PathnameDisplay() {
const pathname = usePathname()
return (
<p style={{ margin: 0 }}>
<c | {
"filepath": "test/development/app-dir/instant-navs-devtools/app/(main)/target-page/[slug]/client.tsx",
"language": "tsx",
"file_size": 2998,
"cut_index": 563,
"middle_length": 229
} |
{ nextTestSetup, FileRef } from 'e2e-utils'
import { waitForRedbox, waitForNoRedbox } from 'next-test-utils'
import { waitForHydration } from 'development-sandbox'
describe('hmr-deleted-page', () => {
const { next } = nextTestSetup({
files: {
app: new FileRef(join(__dirname, 'app')),
},
})
it('sh... | .deleteFile('app/page/style.css')
await waitForHydration(browser)
await waitForRedbox(browser)
await next.deleteFile('app/page')
await waitForHydration(browser)
await waitForNoRedbox(browser)
expect(await browser.elementByCss('h1 | next.deleteFile('app/page/test.tsx')
await next | {
"filepath": "test/development/app-dir/hmr-deleted-page/hmr-deleted-page.test.ts",
"language": "typescript",
"file_size": 886,
"cut_index": 547,
"middle_length": 52
} |
from 'e2e-utils'
import { join } from 'path'
import { existsSync } from 'fs'
import { parseTraceFile } from '../../../lib/parse-trace-file'
describe('render-path tracing', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (!isNextDev) {
it('should be skipped in production', () ... | RM')
await new Promise((resolve) => setTimeout(resolve, 500))
}
const traceStructure = parseTraceFile(tracePath)
// Check for render-path events
const renderPathEvents = traceStructure.eventsByName.get('render-path')
expect(rend | e doesn't exist yet
if (!existsSync(tracePath)) {
const browser = await next.browser('/')
expect(await browser.elementByCss('p').text()).toBe('hello world')
await browser.close()
await next.stop('SIGTE | {
"filepath": "test/development/app-dir/hmr-trace-timing/hmr-trace-timing.test.ts",
"language": "typescript",
"file_size": 1508,
"cut_index": 537,
"middle_length": 229
} |
from 'e2e-utils'
import { waitForNoRedbox } from 'next-test-utils'
describe('hmr-app-and-pages', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should do HMR when app router and pages router have shared CSS', async () => {
let browser = await next.browser('/')
await browser.eval('... | 'body').getComputedCss('background-color')
).toEqual('rgb(255, 0, 0)')
expect(await browser.eval('window.notReloaded')).toBe(true)
browser = await next.browser('/pages-router')
await browser.eval('window.notReloaded = true')
expect(
| ss', (content) =>
content.replace(
'background-color: rgb(255, 255, 255);',
'background-color: rgb(255, 0, 0);'
)
)
await waitForNoRedbox(browser)
expect(
await browser.elementByCss( | {
"filepath": "test/development/app-dir/hmr-shared-css/hmr-shared-css.test.ts",
"language": "typescript",
"file_size": 1594,
"cut_index": 537,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
describe('hook-function-names', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should show readable hook names in stacks', async () => {
const browser = await next.browser('/button')
await browser.elementByCss('button').click()
await expect(brow... | app/button/page.tsx (11:5)",
"Page app/button/page.tsx (18:10)",
],
}
`)
})
it('should show readable hook names in stacks for default-exported components', async () => {
const browser = await next.browser('/')
await e | useCallback[handleClick]
> 7 | throw new Error(message)
| ^",
"stack": [
"Button.useCallback[handleClick] app/button/page.tsx (7:11)",
"button <anonymous>",
"Button | {
"filepath": "test/development/app-dir/hook-function-names/hook-function-names.test.ts",
"language": "typescript",
"file_size": 1391,
"cut_index": 524,
"middle_length": 229
} |
} from 'e2e-utils'
import { getDevIndicatorPosition } from './utils'
describe('devtools-position-persistence', () => {
const { next } = nextTestSetup({
files: __dirname,
nextConfig: {
devIndicators: {
position: 'top-right',
},
},
})
it('should maintain devtools indicator position... | k devtools indicator position is maintained
await browser.refresh()
await browser.waitForIdleNetwork()
style = await getDevIndicatorPosition(browser)
expect(style).toContain('top: 20px')
expect(style).toContain('right: 20px')
})
})
| ).toContain('right: 20px')
// Navigate and chec | {
"filepath": "test/development/app-dir/devtools-position/position-persistence.test.ts",
"language": "typescript",
"file_size": 843,
"cut_index": 535,
"middle_length": 52
} |
from 'e2e-utils'
// This only works for Turbopack HMR builds
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'hmr-intercept-routes',
() => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should update intercept routes via HMR', async () => {
const browser = await n... | ercept/default.js', parallelDefaultContent)
await next.patchFile(
'app/@intercept/(.)intercept/page.js',
parallelInterceptContent
)
// Read the original code of the root layout page
const rootLayoutContent = await n | )
const parallelInterceptContent = await next.readFile(
'fixtures/@intercept/(.)intercept/page.js'
)
// Write the fixture files to the associated output location
await next.patchFile('app/@int | {
"filepath": "test/development/app-dir/hmr-intercept-routes/hmr-intercept-routes.test.ts",
"language": "typescript",
"file_size": 2009,
"cut_index": 537,
"middle_length": 229
} |
v jest */
import { nextTestSetup } from 'e2e-utils'
import * as Log from './basic/utils/log'
import { waitForRedbox, getRedboxSource } from '../../../lib/next-test-utils'
import { join } from 'path'
describe('after() - invalid usages', () => {
const { next } = nextTestSetup({
files: join(__dirname, 'basic'),
}... | errors at compile time when used in a client module', async () => {
const session = await next.browser('/invalid-in-client')
await waitForRedbox(session)
expect(await getRedboxSource(session)).toMatch(
/You're importing a module that dep | ndex) {
// cliOutput shrank since we started the test, so something (like a `sandbox`) reset the logs
currentCliOutputIndex = 0
}
return Log.readCliLogs(next.cliOutput.slice(currentCliOutputIndex))
}
it(' | {
"filepath": "test/development/app-dir/next-after-app-invalid-usage/index.test.ts",
"language": "typescript",
"file_size": 1268,
"cut_index": 524,
"middle_length": 229
} |
Count,
hasErrorToast,
retry,
} from 'next-test-utils'
describe('app-dir - missing required html tags', () => {
const { next } = nextTestSetup({ files: __dirname })
if (process.env.__NEXT_CACHE_COMPONENTS === 'true') {
// TODO(restart-on-cache-miss): reenable once the bug is fixed in:
// https://github... | w error overlay', async () => {
const browser = await next.browser('/')
await waitForRedbox(browser)
await expect(browser).toDisplayRedbox(`
{
"code": "E394",
"description": "Missing <html> and <body> tags in the root layout | browser = await next.browser('/')
await waitForRedbox(browser)
retry(async () => {
expect(await hasErrorToast(browser)).toBe(true)
})
expect(await getToastErrorCount(browser)).toBe(1)
})
it('should sho | {
"filepath": "test/development/app-dir/missing-required-html-tags/index.test.ts",
"language": "typescript",
"file_size": 3349,
"cut_index": 614,
"middle_length": 229
} |
utils'
import { retry } from 'next-test-utils'
describe('app-dir assetPrefix full URL', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
forcedPort: 'random',
})
beforeAll(async () => {
const port = next.forcedPort
await next.patchFile(
'next.config.js',
... | browser.elementByCss('p').text()
expect(text).toBe('before edit')
await next.patchFile('app/page.tsx', (content) => {
return content.replace('before', 'after')
})
await retry(async () => {
expect(await browser.elementByCss('p' | er = await next.browser('/')
const text = await | {
"filepath": "test/development/app-dir/hmr-asset-prefix-full-url/asset-prefix.test.ts",
"language": "typescript",
"file_size": 899,
"cut_index": 547,
"middle_length": 52
} |
'with turbopack.ignoreIssue config', () => {
const { next, skipped, isTurbopack } = nextTestSetup({
files: __dirname,
// turbopack.ignoreIssue is turbopack-only
nextConfig: {
turbopack: {
ignoreIssue: [
{
// glob string pattern for path
pat... | ],
},
},
})
if (skipped) return
if (!isTurbopack) {
it('should skip tests since turbopack.ignoreIssue only works with Turbopack', () => {})
return
}
it('should suppress ignored warning from cli output', a | {
path: '**/server-with-error/**',
},
{
path: '**/route-with-warning/**',
},
{
path: '**/route-with-error/**',
},
| {
"filepath": "test/development/app-dir/turbopack-ignore-issue/turbopack-ignore-issue.test.ts",
"language": "typescript",
"file_size": 6886,
"cut_index": 716,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
describe('experimental-lightningcss with default mode', () => {
describe('in dev server', () => {
const { isTurbopack, next } = nextTestSetup({
files: __dirname,
dependencies: { lightningcss: '^1.23.0' },
packageJson: {
browserslist: ['chrome 100'],
}... | ngcss does.
expect($('p').attr('class')).toBe(
'search-keyword style-module__hlQ3RG__blue'
)
} else {
// We remove hash from the class name in test mode using env var because it is not deterministic.
expect($ | der$('/')
expect($('p').text()).toBe('hello world')
// lightningcss produces different class names in turbo mode
if (isTurbopack) {
// swc_css does not include `-module` in the class name, while lightni | {
"filepath": "test/development/app-dir/experimental-lightningcss/experimental-lightningcss.test.ts",
"language": "typescript",
"file_size": 1385,
"cut_index": 524,
"middle_length": 229
} |
port path from 'path'
const envFile = '.env.development.local'
describe(`app-dir-hmr`, () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
patchFileDelay: 1000,
})
describe('filesystem changes', () => {
it('should not continously poll w... | lementByCss('body').text()
expect(body).toContain('404')
await waitFor(3000)
expect(requestCount).toBe(1)
})
it('should not break when renaming a folder', async () => {
const browser = await next.browser('/folder')
| ', (request) => {
const url = new URL(request.url())
if (url.pathname === '/does-not-exist') {
requestCount++
}
})
},
})
const body = await browser.e | {
"filepath": "test/development/app-hmr/hmr.test.ts",
"language": "typescript",
"file_size": 4767,
"cut_index": 614,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
// Only implemented in Turbopack
import { getRedboxSource, waitForRedbox } from 'next-test-utils'
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'report-system-env-var-inlining',
() => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should ... | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3 | }
4 |
This variable changes frequently, causing slower deploy times and worse browser client-side caching. Consider using \`process.env.NEXT_DEPLOYMENT_ID | expect(error).toMatchInlineSnapshot(`
"./app/foo.tsx (2:14)
TP1202 The commit hash is being inlined.
1 | export function Foo() {
> 2 | return <p>{process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA}</p>
| {
"filepath": "test/development/report-system-env-var-inlining/report-system-env-var-inlining.test.ts",
"language": "typescript",
"file_size": 1271,
"cut_index": 524,
"middle_length": 229
} |
xport const unstable_prefetch = 'force-runtime'
function Box({
label,
children,
}: {
label: string
children: React.ReactNode
}) {
return (
<div
style={{
background: '#fff',
border: '1px solid #ddd',
borderRadius: 8,
padding: '1rem',
marginBottom: '0.75rem',
... | o', value: '456' },
{ label: 'Stat three', value: '789' },
]
return (
<div data-testid="dynamic-content" style={{ display: 'flex', gap: '1rem' }}>
{stats.map((s) => (
<div key={s.label} style={{ flex: 1, textAlign: 'center' }}>
| : '0.5rem',
}}
>
{label}
</div>
{children}
</div>
)
}
async function DynamicStats() {
await connection()
const stats = [
{ label: 'Stat one', value: '123' },
{ label: 'Stat tw | {
"filepath": "test/development/app-dir/instant-navs-devtools/app/(main)/target-page/[slug]/page.tsx",
"language": "tsx",
"file_size": 7112,
"cut_index": 716,
"middle_length": 229
} |
-test-utils'
describe('app-dir - capture-console-error-owner-stack', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should capture browser console error and format the error message', async () => {
const browser = await next.browser('/browser/event')
await browser.elementByCss('bu... | rowser/event/page.js (7:17)",
"button <anonymous>",
"Page app/browser/event/page.js (5:5)",
],
}
`)
})
it('should capture browser console error in render and dedupe if necessary', async () => {
const browser = awa | label": "Console Error",
"source": "app/browser/event/page.js (7:17) @ onClick
> 7 | console.error('trigger an console <%s>', 'error')
| ^",
"stack": [
"onClick app/b | {
"filepath": "test/development/app-dir/capture-console-error-owner-stack/capture-console-error-owner-stack.test.ts",
"language": "typescript",
"file_size": 4110,
"cut_index": 614,
"middle_length": 229
} |
install
* reorganizes `node_modules` while the Next.js dev server is running.
*
* Specifically, when `next` (re)moves under `node_modules` mid-HMR, Turbopack
* fails to resolve `next/package.json` and emits a `MissingNextFolderIssue`.
* The dev server must:
* - surface the issue (recoverable, not Fatal)
* -... | t nextPath = path.join(next.testDir, 'node_modules', 'next')
// sanity check
await fs.lstat(nextPath)
return nextPath
}
async function moveNextAside(): Promise<{ original: string; stash: string }> {
const original = await getNextPath() |
describeMaybe('concurrent-install', () => {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
})
const itTurbopack = isTurbopack ? it : it.skip
async function getNextPath(): Promise<string> {
cons | {
"filepath": "test/development/app-dir/concurrent-install/concurrent-install.test.ts",
"language": "typescript",
"file_size": 5705,
"cut_index": 716,
"middle_length": 229
} |
<p>
This App is made up of a number of sub-pages which exercise the
Cache Components validation performed in dev to ensure it matches up
with the validation performed during the build.
</p>
<p>
When Building routes with dynamic params we validate t... | alues for that param.
</p>
<p>
In Dev, our validation needs to match and the way we do this is we
look at the current route and determine the most specific set of
params that would be availalbe during | led a fallback param which suspends as dynamic and is
required to be wrapped in Suspense if accessed so we can ensure
there is still an acceptable shell even when we don't know about
specific v | {
"filepath": "test/development/app-dir/cache-components-dev-fallback-validation/app/layout.tsx",
"language": "tsx",
"file_size": 6371,
"cut_index": 716,
"middle_length": 229
} |
from 'e2e-utils'
import { retry } from 'next-test-utils'
import cheerio from 'cheerio'
describe('dev-fetch-hmr', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should retain module level fetch patching', async () => {
const html = await next.render('/')
expect(html).toContain('mo... | to trigger HMR')
await next.patchFile('app/page.tsx', (content) =>
content.replace('touch to trigger HMR', 'touch to trigger HMR 2')
)
// For server hmr, we must touch the exact module to trigger re-evaluation
await next.patchFile(' | onst magicNumber2 = cheerio.load(html2)('#magic-number').text()
// Module was not re-evaluated
expect(magicNumber2).toBe(magicNumber)
const update = cheerio.load(html2)('#update').text()
expect(update).toBe('touch | {
"filepath": "test/development/app-dir/dev-fetch-hmr/dev-fetch-hmr.test.ts",
"language": "typescript",
"file_size": 1608,
"cut_index": 537,
"middle_length": 229
} |
mport { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
describe('app-dir - app routes errors', () => {
const { next } = nextTestSetup({
files: __dirname,
})
describe('bad lowercase exports', () => {
it.each([
['get'],
['head'],
['options'],
['post'],
... | method.toUpperCase()}' method name to fix this error.`
)
expect(next.cliOutput).toMatch(
/Detected lowercase method '.+' in '.+\/route\.js'\. Export the uppercase '.+' method name to fix this error\./
)
r | method)
await check(() => {
expect(next.cliOutput).toContain(
`Detected lowercase method '${method}' in`
)
expect(next.cliOutput).toContain(
`Export the uppercase '${ | {
"filepath": "test/development/app-dir/app-routes-error/index.test.ts",
"language": "typescript",
"file_size": 1050,
"cut_index": 513,
"middle_length": 229
} |
{ next } = nextTestSetup({
files: __dirname,
})
it('is none on initial load', async () => {
const browser = await next.browser('/')
const badge = await browser.elementByCss('[data-next-badge]')
const cacheStatus = await badge.getAttribute('data-status')
expect(cacheStatus).toBe('none')
})
... | data-next-badge]')
const cacheStatus = await badge.getAttribute('data-status')
expect(cacheStatus).toBe('prerendering')
})
await retry(async () => {
const text = await browser.elementByCss('#navigation-page').text()
|
// navigate to the navigation page
const link = await browser.waitForElementByCss('a[href="/navigation"]')
await link.click()
await retry(async () => {
const badge = await browser.elementByCss('[ | {
"filepath": "test/development/app-dir/cache-indicator/cache-indicator.test.ts",
"language": "typescript",
"file_size": 8127,
"cut_index": 716,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
describe('serialize-circular-error', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should serialize the object from server component in console correctly', async () => {
const browser = await next.browser('/')
await expect(browser).toDisplayRedbox(`... | ject from client component in console correctly', async () => {
const browser = await next.browser('/client')
// TODO: Format arbitrary messages in Redbox
await expect(browser).toDisplayRedbox(`
{
"code": "E394",
"descriptio | "source": null,
"stack": [],
}
`)
const output = next.cliOutput
expect(output).toContain(
'Error: {"objA":{"other":{"a":"[Circular]"}},"objB":"[Circular]"}'
)
})
it('should serialize the ob | {
"filepath": "test/development/app-dir/serialize-circular-error/serialize-circular-error.test.ts",
"language": "typescript",
"file_size": 1434,
"cut_index": 524,
"middle_length": 229
} |
waitForNoRedbox, retry } from 'next-test-utils'
// This tests file symlinks, but not directory symlinks. Directory symlinks are
// known to break route manifest generation:
// https://github.com/vercel/next.js/discussions/77463
describe('HMR symlinks', () => {
const { next } = nextTestSetup({
files: __dirname,
... | await waitForNoRedbox(browser)
expect(await browser.elementByCss('h1').text()).toBe(
'This is the updated symlink target'
)
})
}
)
})
/* eslint-disable jest/no-standalone-expect */
// This works | the symlink target'
)
await next.patchFile(
'app/symlink-target/page.tsx',
(content) => content.replace('symlink target', 'updated symlink target'),
async () => {
await retry(async () => {
| {
"filepath": "test/development/app-dir/hmr-symlink/hmr-symlink.test.ts",
"language": "typescript",
"file_size": 2782,
"cut_index": 563,
"middle_length": 229
} |
eact from 'react'
import { ReactNode } from 'react'
const magicNumber = Math.random()
const originalFetch = globalThis.fetch
if (originalFetch.name === 'monkeyPatchedFetch') {
throw new Error(
'Patching over already patched fetch. This creates a memory leak.'
)
}
globalThis.fetch = async function monkeyPatch... | fake.url/magic-number') {
return new Response(magicNumber.toString())
}
return originalFetch(resource, options)
}
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html | atching is fun')
}
if (request.url === 'http:// | {
"filepath": "test/development/app-dir/dev-fetch-hmr/app/layout.tsx",
"language": "tsx",
"file_size": 836,
"cut_index": 520,
"middle_length": 52
} |
rt { cacheTag } from 'next/cache'
import { Suspense } from 'react'
export default function Page() {
return (
<div id="navigation-page">
Hello navigation page!
<Suspense fallback={<div>Loading</div>}>
<Component />
</Suspense>
<SlowThing />
</div>
)
}
async function Componen... | sleep for 2s
await new Promise((resolve) => setTimeout(resolve, 2000))
return [{ id: 'foo', content: 'bar' }]
}
async function SlowThing() {
// sleep for 2s
await new Promise((resolve) => setTimeout(resolve, 2000))
return <div>Slow Thing</div | osts() {
'use cache'
cacheTag('blog-posts')
// | {
"filepath": "test/development/app-dir/cache-indicator/app/navigation/page.tsx",
"language": "tsx",
"file_size": 828,
"cut_index": 516,
"middle_length": 52
} |
ect to see any errors await params regarless of where there
// are Suspense boundaries.
const browser = await next.browser(
'/complete/prerendered/wrapped/prerendered'
)
await waitForNoRedbox(browser)
await browser.loadPage(`${next.url}/complete/prerendered/wrapped/novel`)
await waitForNo... | novel/unwrapped/novel`)
await waitForNoRedbox(browser)
})
it('should warn about missing Suspense when accessing params if static params are partially known at build time', async () => {
// when the params are partially complete we don't expect | unwrapped/prerendered`
)
await waitForNoRedbox(browser)
await browser.loadPage(`${next.url}/complete/prerendered/unwrapped/novel`)
await waitForNoRedbox(browser)
await browser.loadPage(`${next.url}/complete/ | {
"filepath": "test/development/app-dir/cache-components-dev-fallback-validation/cache-components-dev-fallback-validation.test.ts",
"language": "typescript",
"file_size": 12439,
"cut_index": 921,
"middle_length": 229
} |
ipStart: true,
dependencies: {
'styled-components': '6.1.16',
'@next/mdx': 'canary',
'@mdx-js/loader': '2.2.1',
'@mdx-js/react': '2.2.1',
},
})
// https://github.com/vercel/next.js/issues/12422
test('styled-components hydration mismatch', async () => {
const files = new Map([
... | ctx.renderPage = () =>
originalRenderPage({
enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
| class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
| {
"filepath": "test/development/acceptance/ReactRefreshRegression.test.ts",
"language": "typescript",
"file_size": 10986,
"cut_index": 921,
"middle_length": 229
} |
bkit } from 'playwright'
import type { Browser } from 'playwright'
describe('mcp-server get_errors tool', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
})
async function callGetErrors(id: string) {
const response = await fetch(`${next.... | const result = JSON.parse(match![1])
return result.result?.content?.[0]?.text
}
it('should handle no browser sessions gracefully', async () => {
const errorsText = await callGetErrors('test-no-session')
const errors = JSON.parse(errorsTe | ({
jsonrpc: '2.0',
id,
method: 'tools/call',
params: { name: 'get_errors', arguments: {} },
}),
})
const text = await response.text()
const match = text.match(/data: ({.*})/s)
| {
"filepath": "test/development/mcp-server/mcp-server-get-errors.test.ts",
"language": "typescript",
"file_size": 8860,
"cut_index": 716,
"middle_length": 229
} |
from 'path'
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('get-logs MCP tool', () => {
const { next, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'log-file-app'),
})
if (skipped) {
return
}
async function callGetLogs(id: string): P... | .text()
const match = text.match(/data: ({.*})/s)
const result = JSON.parse(match![1])
return result.result?.content?.[0]?.text
}
it('should return log file path via MCP get_logs tool', async () => {
// Generate some logs by visiting p | n, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id,
method: 'tools/call',
params: { name: 'get_logs', arguments: {} },
}),
})
const text = await response | {
"filepath": "test/development/mcp-server/mcp-server-get-logs.test.ts",
"language": "typescript",
"file_size": 1479,
"cut_index": 524,
"middle_length": 229
} |
adata tool', () => {
async function callGetPageMetadata(url: string, id: string) {
const response = await fetch(`${url}/_next/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
... | path.join(__dirname, 'fixtures', 'parallel-routes-template')
),
})
it('should return metadata for basic page', async () => {
await next.browser('/')
const metadataText = await callGetPageMetadata(next.url, 'test-basic')
co | atch = text.match(/data: ({.*})/s)
const result = JSON.parse(match![1])
return result.result?.content?.[0]?.text
}
describe('app router', () => {
const { next } = nextTestSetup({
files: new FileRef(
| {
"filepath": "test/development/mcp-server/mcp-server-get-page-metadata.test.ts",
"language": "typescript",
"file_size": 8071,
"cut_index": 716,
"middle_length": 229
} |
tSetup } from 'e2e-utils'
import path from 'path'
describe('mcp-server get_project_metadata tool', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
})
it('should return correct project metadata via get_project_metadata tool', async () => {
... | name: 'get_project_metadata',
arguments: {},
},
}),
})
const callToolText = await callToolResponse.text()
const callToolDataMatch = callToolText.match(/data: ({.*})/s)
expect(callToolDataMatch).toBeTruthy()
| ent-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 'call-tool-1',
method: 'tools/call',
params: {
| {
"filepath": "test/development/mcp-server/mcp-server-get-project-metadata.test.ts",
"language": "typescript",
"file_size": 1997,
"cut_index": 537,
"middle_length": 229
} |
om 'e2e-utils'
describe('get_routes MCP tool', () => {
const { next, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'dynamic-routes-app'),
})
if (skipped) {
return
}
async function callGetRoutes(
id: string,
args: Record<string, unknown> = {}
): Promise<string> {
... | match = text.match(/data: ({.*})/s)
const result = JSON.parse(match![1])
return result.result?.content?.[0]?.text
}
it('should return all routes via MCP get_routes tool without visiting pages', async () => {
// The tool should discover al | ,
},
body: JSON.stringify({
jsonrpc: '2.0',
id,
method: 'tools/call',
params: { name: 'get_routes', arguments: args },
}),
})
const text = await response.text()
const | {
"filepath": "test/development/mcp-server/mcp-server-get-routes.test.ts",
"language": "typescript",
"file_size": 2603,
"cut_index": 563,
"middle_length": 229
} |
=> {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'actions-app')),
})
it('should return action details via get_server_action_by_id tool', async () => {
const mcpEndpoint = `${next.url}/_next/mcp`
// Visit the page to trigger action registration
await next... | )[0]
expect(actionId).toBeTruthy()
// Call get_server_action_by_id tool
const callToolResponse = await fetch(mcpEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, t | n'
)
const manifestContent = await fs.readFile(manifestPath, 'utf-8')
const manifest = JSON.parse(manifestContent)
// Get the first action ID from the manifest
const actionId = Object.keys(manifest.node || {} | {
"filepath": "test/development/mcp-server/mcp-server-get-server-action-by-id.test.ts",
"language": "typescript",
"file_size": 5531,
"cut_index": 716,
"middle_length": 229
} |
import { findAllTelemetryEvents } from 'next-test-utils'
import path from 'path'
describe('mcp-server telemetry tracking', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
env: {
NEXT_TELEMETRY_DEBUG: '1',
},
})
async function c... | rams: { name: toolName, arguments: params },
}),
})
const text = await response.text()
const match = text.match(/data: ({.*})/s)
if (!match) {
throw new Error(`Failed to parse response for tool ${toolName}`)
}
return JS | -Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: `telemetry-test-${Date.now()}`,
method: 'tools/call',
pa | {
"filepath": "test/development/mcp-server/mcp-server-telemetry.test.ts",
"language": "typescript",
"file_size": 2453,
"cut_index": 563,
"middle_length": 229
} |
omium, firefox, webkit, type Browser } from 'playwright'
function getFullUrl(appPortOrUrl: string | number, url: string): string {
const appUrl =
typeof appPortOrUrl === 'string'
? appPortOrUrl
: `http://localhost:${appPortOrUrl}`
return url.startsWith('/') ? `${appUrl}${url}` : url
}
/**
* Minim... | erName = (process.env.BROWSER_NAME || 'chrome').toLowerCase()
let browser: Browser
if (browserName === 'safari') {
browser = await webkit.launch({ headless })
} else if (browserName === 'firefox') {
browser = await firefox.launch({ headless } | urrent tabs needed for testing errors across multiple browser sessions.
*/
export async function launchStandaloneSession(
appPortOrUrl: string | number,
url: string
) {
const headless = !!process.env.HEADLESS
const brows | {
"filepath": "test/development/mcp-server/test-utils.ts",
"language": "typescript",
"file_size": 1446,
"cut_index": 524,
"middle_length": 229
} |
ent'
import { useEffect } from 'react'
export default function ClientPage() {
useEffect(() => {
// Logging in client component useEffect
// Test complex partial circular object
const circularObj: any = {
name: 'test',
data: {
nested: {
value: 42,
items: [1, 2, 3],... | ', circularObj)
console.error('Client: This is an error message from client component')
console.warn('Client: This is a warning message from client component')
}, [])
console.error('globalThis', globalThis)
return <p>client page with loggin | bj
console.log('Client: Complex circular object: | {
"filepath": "test/development/mcp-server/fixtures/log-file-app/app/client/page.tsx",
"language": "tsx",
"file_size": 836,
"cut_index": 520,
"middle_length": 52
} |
sh app', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
skipStart: true,
})
test('can edit a component without losing state', async () => {
await using sandbox = await createSandbox(next)
const { session } = sandbox
await se... | )
}
`
)
await session.evaluate(() => document.querySelector('button').click())
expect(
await session.evaluate(() => document.querySelector('p').textContent)
).toBe('1')
await session.patch(
'index.js',
| const increment = useCallback(() => setCount(c => c + 1), [setCount])
return (
<main>
<p>{count}</p>
<button onClick={increment}>Increment</button>
</main>
| {
"filepath": "test/development/acceptance-app/ReactRefresh.test.ts",
"language": "typescript",
"file_size": 5420,
"cut_index": 716,
"middle_length": 229
} |
ble with webpack 5
test('Node.js builtins', async () => {
await using sandbox = await createSandbox(
next,
new Map([
[
'node_modules/my-package/index.js',
outdent`
const dns = require('dns')
module.exports = dns
`,
],
[
... | ded</h1> : <h1>Package did not load</h1>)
}
`
)
if (isTurbopack) {
await expect(browser).toDisplayRedbox(`
{
"description": "Module not found: Can't resolve 'dns'",
"environmentLabel": null,
"la | ])
)
const { browser, session } = sandbox
await session.patch(
'index.js',
outdent`
import pkg from 'my-package'
export default function Hello() {
return (pkg ? <h1>Package loa | {
"filepath": "test/development/acceptance-app/ReactRefreshLogBox-builtins.test.ts",
"language": "typescript",
"file_size": 9469,
"cut_index": 921,
"middle_length": 229
} |
'development-sandbox'
import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path'
import { outdent } from 'outdent'
// TODO: figure out why snapshots mismatch on GitHub actions
// specifically but work in docker and locally
describe.skip('ReactRefreshLogBox scss app', () => {
const { next } = nextTes... | nt`
import './index.module.scss';
export default () => {
return (
<div>
<p>Hello World</p>
</div>
)
}
`
)
await session.waitForNoRedbox()
// Syntax error
| async () => {
await using sandbox = await createSandbox(next)
const { session } = sandbox
await session.write('index.module.scss', `.button { font-size: 5px; }`)
await session.patch(
'index.js',
outde | {
"filepath": "test/development/acceptance-app/ReactRefreshLogBox-scss.test.ts",
"language": "typescript",
"file_size": 2217,
"cut_index": 563,
"middle_length": 229
} |
import * as React from 'react';
class ClassDefault extends React.Component {
render() {
return <h1>Default Export</h1>;
}
}
export default ClassDefault;
`
)
expect(
await session.evaluate(() => document.querySelector('h1').textContent)
... | )
if (isTurbopack) {
await expect(browser).toDisplayRedbox(`
{
"description": "no",
"environmentLabel": null,
"label": "Runtime Error",
"source": "index.js (3:7) @ module evaluation
> 3 | throw n | 'react';
throw new Error('no')
class ClassDefault extends React.Component {
render() {
return <h1>Default Export</h1>;
}
}
export default ClassDefault;
`
| {
"filepath": "test/development/acceptance-app/ReactRefreshLogBox.test.ts",
"language": "typescript",
"file_size": 49032,
"cut_index": 2151,
"middle_length": 229
} |
import path from 'path'
import { outdent } from 'outdent'
describe('ReactRefreshLogBox app', () => {
const { isTurbopack, next, isRspack } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
skipStart: true,
})
test('server-side only compilation errors', async ()... | unction Hello(props) {
return <h1>{props.result}</h1>
}
`
)
if (isTurbopack) {
await expect(browser).toDisplayRedbox(`
{
"description": ""getStaticProps" is not supported in app/. Read more: https://ne | port myLibrary from 'my-non-existent-library'
export async function getStaticProps() {
return {
props: {
result: myLibrary()
}
}
}
export default f | {
"filepath": "test/development/acceptance-app/ReactRefreshLogBoxMisc.test.ts",
"language": "typescript",
"file_size": 3544,
"cut_index": 614,
"middle_length": 229
} |
{ FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path'
import { createSandbox } from 'development-sandbox'
import { outdent } from 'outdent'
describe('ReactRefreshModule app', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
skip... | /page.js',
outdent`
'use client'
import { default as ${variable} } from 'next/link'
console.log({ ${variable} })
export default function Page() {
return null
}
`
)
aw | ForNoRedbox()
const variables = [
'_a',
'_b',
'currentExports',
'prevExports',
'isNoLongerABoundary',
]
for await (const variable of variables) {
await session.patch(
'app | {
"filepath": "test/development/acceptance-app/ReactRefreshModule.test.ts",
"language": "typescript",
"file_size": 1149,
"cut_index": 518,
"middle_length": 229
} |
'styled-components': '6.1.16',
'@next/mdx': 'canary',
'@mdx-js/loader': '2.2.1',
'@mdx-js/react': '2.2.1',
},
skipStart: true,
})
// https://github.com/vercel/next.js/issues/12422
// TODO-APP: port to app directory
test.skip('styled-components hydration mismatch', async () => {
c... | ctx.renderPage = () =>
originalRenderPage({
enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
| export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
| {
"filepath": "test/development/acceptance-app/ReactRefreshRegression.test.ts",
"language": "typescript",
"file_size": 10781,
"cut_index": 921,
"middle_length": 229
} |
w.log.push('init FooV1'); require('./bar');`
)
await session.write(
'./bar.js',
`window.log.push('init BarV1'); export default function Bar() { return null; };`
)
await session.evaluate(() => ((window as any).log = []))
await session.patch(
'index.js',
`require('./foo'); exp... | n Bar() { return null; };`
)
expect(await session.evaluate(() => (window as any).log)).toEqual([
'init BarV2',
])
// We only edited Bar, and it accepted.
// So we expect it to re-run alone.
await session.evaluate(() => ((wind | ed Bar, and it accepted.
// So we expect it to re-run alone.
await session.evaluate(() => ((window as any).log = []))
await session.patch(
'./bar.js',
`window.log.push('init BarV2'); export default functio | {
"filepath": "test/development/acceptance-app/ReactRefreshRequire.test.ts",
"language": "typescript",
"file_size": 17400,
"cut_index": 1331,
"middle_length": 229
} |
'path'
import crypto from 'crypto'
import { Buffer } from 'buffer'
import vm from 'vm'
import assert from 'assert'
import constants from 'constants'
import domain from 'domain'
import http from 'http'
import https from 'https'
import os from 'os'
import punycode from 'punycode'
import process from 'process'
import quer... |
callback()
},
})
writable.on('finish', () => {
closedStream = true
})
writable.end()
assert.ok(true)
assert.ok(!!domain)
assert.ok(!!http)
assert.ok(!!https)
assert.ok(!!punycode)
assert.ok(! | mport '_http_common'
import 'setimmediate'
async function getData() {
const result = await new Promise((resolve) => {
let closedStream = false
const writable = new Writable({
write(_chunk, _encoding, callback) { | {
"filepath": "test/development/basic/node-builtins/app/server-component/page.js",
"language": "javascript",
"file_size": 2188,
"cut_index": 563,
"middle_length": 229
} |
'path'
import crypto from 'crypto'
import { Buffer } from 'buffer'
import vm from 'vm'
import assert from 'assert'
import constants from 'constants'
import { useEffect, useState } from 'react'
import domain from 'domain'
import http from 'http'
import https from 'https'
import os from 'os'
import punycode from 'punycod... | new Writable({
write(_chunk, _encoding, callback) {
callback()
},
})
writable.on('finish', () => {
closedStream = true
})
writable.end()
assert.ok(true)
assert.ok(!!domain)
assert.ok(!!http)
ass | util from 'util'
import zlib from 'zlib'
import 'setimmediate'
export default function NodeBrowserPolyfillPage() {
const [state, setState] = useState({})
useEffect(() => {
let closedStream = false
const writable = | {
"filepath": "test/development/basic/node-builtins/pages/index.js",
"language": "javascript",
"file_size": 2231,
"cut_index": 563,
"middle_length": 229
} |
from 'node:path'
import crypto from 'node:crypto'
import { Buffer } from 'node:buffer'
import vm from 'node:vm'
import assert from 'node:assert'
import constants from 'node:constants'
import domain from 'node:domain'
import http from 'node:http'
import https from 'node:https'
import os from 'node:os'
import punycode fr... | onst writable = new Writable({
write(_chunk, _encoding, callback) {
callback()
},
})
writable.on('finish', () => {
closedStream = true
})
writable.end()
assert.ok(true)
assert.ok(!!domain)
assert.ok | node:timers'
import tty from 'node:tty'
import util from 'node:util'
import zlib from 'node:zlib'
export async function getServerSideProps() {
const result = await new Promise((resolve) => {
let closedStream = false
c | {
"filepath": "test/development/basic/node-builtins/pages/server-node-schema.js",
"language": "javascript",
"file_size": 2265,
"cut_index": 563,
"middle_length": 229
} |
sh', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
skipStart: true,
})
test('can edit a component without losing state', async () => {
await using sandbox = await createSandbox(next)
const { session } = sandbox
await sessio... | )
}
`
)
await session.evaluate(() => document.querySelector('button').click())
expect(
await session.evaluate(() => document.querySelector('p').textContent)
).toBe('1')
await session.patch(
'index.js',
| const increment = useCallback(() => setCount(c => c + 1), [setCount])
return (
<main>
<p>{count}</p>
<button onClick={increment}>Increment</button>
</main>
| {
"filepath": "test/development/acceptance/ReactRefresh.test.ts",
"language": "typescript",
"file_size": 5421,
"cut_index": 716,
"middle_length": 229
} |
ack 5
test('Node.js builtins', async () => {
await using sandbox = await createSandbox(
next,
new Map([
[
'node_modules/my-package/index.js',
outdent`
const dns = require('dns')
module.exports = dns
`,
],
[
'node_m... | Package did not load</h1>)
}
`
)
if (isTurbopack) {
await expect(browser).toDisplayRedbox(`
{
"description": "Module not found: Can't resolve 'dns'",
"environmentLabel": null,
"label": "Build E | const { browser, session } = sandbox
await session.patch(
'index.js',
outdent`
import pkg from 'my-package'
export default function Hello() {
return (pkg ? <h1>Package loaded</h1> : <h1> | {
"filepath": "test/development/acceptance/ReactRefreshLogBox-builtins.test.ts",
"language": "typescript",
"file_size": 9555,
"cut_index": 921,
"middle_length": 229
} |
"description": "idk",
"environmentLabel": null,
"label": "Runtime Error",
"source": "index.js (8:27) @ onClick
> 8 | throw new Error('idk')
| ^",
"stack": [
"onClick index.js (8:27)",
],
... | sDefault extends React.Component {
render() {
return <h1>Default Export</h1>;
}
}
export default ClassDefault;
`
)
expect(
await session.evaluate(() => document.querySelector('h1').textCo | await using sandbox = await createSandbox(next)
const { browser, session } = sandbox
// We start here.
await session.patch(
'index.js',
outdent`
import * as React from 'react';
class Clas | {
"filepath": "test/development/acceptance/ReactRefreshLogBox.test.ts",
"language": "typescript",
"file_size": 42024,
"cut_index": 2151,
"middle_length": 229
} |
9a6c3/packages/metro/src/lib/polyfills/__tests__/require-test.js#L989-L1048
test('re-runs accepted modules', async () => {
await using sandbox = await createSandbox(next)
const { session } = sandbox
await session.patch(
'index.js',
`export default function Noop() { return null; };`
)
... | )
expect(await session.evaluate(() => (window as any).log)).toEqual([
'init FooV1',
'init BarV1',
])
// We only edited Bar, and it accepted.
// So we expect it to re-run alone.
await session.evaluate(() => ((window as any | efault function Bar() { return null; };`
)
await session.evaluate(() => ((window as any).log = []))
await session.patch(
'index.js',
`require('./foo'); export default function Noop() { return null; };`
| {
"filepath": "test/development/acceptance/ReactRefreshRequire.test.ts",
"language": "typescript",
"file_size": 17215,
"cut_index": 921,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import fs from 'fs-extra'
import { waitForNoRedbox } from 'next-test-utils'
import path from 'path'
describe('repeated-dev-edits', () => {
const { next } = nextTestSetup({
files: __dirname,
})
// Recommended for tests that check HTML. Cheerio is a HTML parser that has a jQuery l... | it browser.waitForElementByCss('#version-2')
expect(await browser.elementByCss('p').text()).toBe('version-2')
// Verify no hydration mismatch:
await waitForNoRedbox(browser)
await next.patchFile(
pagePath,
pageContent.replaceA | ath = 'pages/index.tsx'
const pageContent = String(
await fs.readFile(path.join(__dirname, pagePath))
)
await next.patchFile(
pagePath,
pageContent.replaceAll('version-1', 'version-2')
)
awa | {
"filepath": "test/development/repeated-dev-edits/repeated-dev-edits.test.ts",
"language": "typescript",
"file_size": 1348,
"cut_index": 524,
"middle_length": 229
} |
waitFor } from 'next-test-utils'
// When `__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true` is set in CI, Next.js
// regenerates `next-env.d.ts` with additional `cache-life`/`validator`
// imports. The seed fixture must match that output so the very first read of
// `next-env.d.ts` (before any regeneration is observed) lin... | types/validator.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
`
: `/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next | // <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
import "./.next/dev/types/root-params.d.ts";
import "./.next/dev/types/cache-life.d.ts";
import "./.next/dev/ | {
"filepath": "test/development/typescript-app-type-declarations/typescript-app-type-declarations.test.ts",
"language": "typescript",
"file_size": 3818,
"cut_index": 614,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('empty-object-getInitialProps', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should show empty object warning on SSR', async () => {
await next.render('/')
await retry(() => {
expect(next.cliOut... | om `getInitialProps`/
)
})
})
it('should show empty object warning during client transition', async () => {
const browser = await next.browser('/static')
await browser.eval(`(function() {
window.gotWarn = false
const orig | onst outputIndex = next.cliOutput.length
await next.render('/static')
await retry(() => {
const newOutput = next.cliOutput.slice(outputIndex)
expect(newOutput).not.toMatch(
/returned an empty object fr | {
"filepath": "test/development/empty-object-getInitialProps/empty-object-getInitialProps.test.ts",
"language": "typescript",
"file_size": 1441,
"cut_index": 524,
"middle_length": 229
} |
ort { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import { join } from 'path'
describe('watch-config-file', () => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixture'),
})
it('should output config file change', async () => {
await check(async () => next.cliOutp... | },
]
},
}
module.exports = nextConfig`
)
return next.cliOutput
}, /Found a change in next\.config\.js\. Restarting the server to apply the changes\.\.\./)
aw | reactStrictMode: true,
async redirects() {
return [
{
source: '/about',
destination: '/',
permanent: false,
| {
"filepath": "test/development/watch-config-file/index.test.ts",
"language": "typescript",
"file_size": 1077,
"cut_index": 515,
"middle_length": 229
} |
const { next, isTurbopack } = nextTestSetup({
files: {
pages: new FileRef(join(__dirname, 'pages')),
},
env: {
// Disable the cooldown period for the dev indicator so that hiding the indicator in a test doesn't
// impact subsequent tests.
__NEXT_DEV_INDICATOR_COOLDOWN_MS: '0',
},... | nextjs-toast]',
popover: '[data-nextjs-dev-tools-button]',
indicator: '[data-next-badge-root]',
minimizeButton: 'body',
preferencesButton: '[data-preferences]',
hideButton: '[data-hide-dev-tools]',
}
function getToast(browser: Playw | ring
) {
return browser.eval(
`!!document.querySelector('nextjs-portal').shadowRoot.querySelector('${selector}')`
) as any
}
const selectors = {
fullScreenDialog: '[data-nextjs-dialog]',
toast: '[data- | {
"filepath": "test/development/client-dev-overlay/index.test.ts",
"language": "typescript",
"file_size": 6569,
"cut_index": 716,
"middle_length": 229
} |
from 'e2e-utils'
describe('MDX-rs Plugin support', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
'@next/mdx': 'canary',
'@mdx-js/loader': '*',
'@mdx-js/react': '*',
},
})
it('should render an MDX page correctly', async () => {
expect(await next.rend... | h mdx transform options', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
'@next/mdx': 'canary',
'@mdx-js/loader': '*',
'@mdx-js/react': '*',
},
skipStart: true,
})
beforeAll(async () => { | uld render an MDX page with globally provided components (from `mdx-components.js`) correctly', async () => {
expect(await next.render('/provider')).toMatch(/Marker was rendered!/)
})
})
describe('MDX-rs Plugin support wit | {
"filepath": "test/development/plugin-mdx-rs/plugin-mdx-rs.test.ts",
"language": "typescript",
"file_size": 1536,
"cut_index": 537,
"middle_length": 229
} |
e = await fetch(`${url}/_next/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: toolName + '-' + Date.now(),
method: 'tools/call',
params: { name: toolNam... | ,
() => {
const { next, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'dynamic-routes-app'),
})
if (skipped) {
return
}
describe('routeSpecifier input', () => {
it('should compile a valid app | rn JSON.parse(envelope.result?.content?.[0]?.text)
}
// compile_route is Turbopack-only; it is not registered on webpack dev servers.
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'mcp-server compile_route tool' | {
"filepath": "test/development/mcp-server/mcp-server-compile-route.test.ts",
"language": "typescript",
"file_size": 7602,
"cut_index": 716,
"middle_length": 229
} |
port { nextTestSetup } from 'e2e-utils'
import { renderViaHTTP } from 'next-test-utils'
// Skip on Turbopack because it's not supported
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'webpack-issuer-deprecation-warning',
() => {
const { next } = nextTestSetup({
files: {
'pages/index... | const html = await renderViaHTTP(next.url, '/')
expect(html).toContain('Syntax Error')
expect(next.cliOutput).not.toContain(
'[DEP_WEBPACK_MODULE_ISSUER] DeprecationWarning: Module.issuer: Use new ModuleGraph API'
)
})
}
| ning about webpack module issuer', async () => {
| {
"filepath": "test/development/webpack-issuer-deprecation-warning/index.test.ts",
"language": "typescript",
"file_size": 824,
"cut_index": 514,
"middle_length": 52
} |
'path'
import crypto from 'crypto'
import { Buffer } from 'buffer'
import vm from 'vm'
import assert from 'assert'
import constants from 'constants'
import domain from 'domain'
import http from 'http'
import https from 'https'
import os from 'os'
import punycode from 'punycode'
import process from 'process'
import quer... | callback()
},
})
writable.on('finish', () => {
closedStream = true
})
writable.end()
assert.ok(true)
assert.ok(!!domain)
assert.ok(!!http)
assert.ok(!!https)
assert.ok(!!punycode)
assert.ok(!!stri | port 'setimmediate'
export async function getServerSideProps() {
const result = await new Promise((resolve) => {
let closedStream = false
const writable = new Writable({
write(_chunk, _encoding, callback) {
| {
"filepath": "test/development/basic/node-builtins/pages/server.js",
"language": "javascript",
"file_size": 2187,
"cut_index": 563,
"middle_length": 229
} |
rt: true,
})
test('empty _app shows logbox', async () => {
await using sandbox = await createSandbox(
next,
new Map([['pages/_app.js', ``]])
)
const { browser, session } = sandbox
await expect(browser).toDisplayRedbox(`
{
"code": "E464",
"description": "The default ex... | )
})
test('empty _document shows logbox', async () => {
await using sandbox = await createSandbox(
next,
new Map([['pages/_document.js', ``]])
)
const { browser, session } = sandbox
await expect(browser).toDisplayRedbox(`
| atch(
'pages/_app.js',
outdent`
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp
`
)
await session.waitForNoRedbox( | {
"filepath": "test/development/acceptance/ReactRefreshLogBox-app-doc.test.ts",
"language": "typescript",
"file_size": 9633,
"cut_index": 921,
"middle_length": 229
} |
mport { FileRef, nextTestSetup } from 'e2e-utils'
import { createSandbox } from 'development-sandbox'
import path from 'path'
describe('ReactRefreshModule', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
skipStart: true,
})
it('should a... | ariable} } from 'next/link'
console.log({ ${variable} })
export default function Page() {
return null
}`
)
await session.waitForNoRedbox()
expect(next.cliOutput).not.toContain(
`'${variable}' has | _a',
'_b',
'currentExports',
'prevExports',
'isNoLongerABoundary',
]
for await (const variable of variables) {
await session.patch(
'pages/index.js',
`import { default as ${v | {
"filepath": "test/development/acceptance/ReactRefreshModule.test.ts",
"language": "typescript",
"file_size": 1043,
"cut_index": 513,
"middle_length": 229
} |
eState(0)
const increment = useCallback(() => setCount(c => c + 1), [setCount])
return (
<main>
<p>{count}</p>
<button onClick={increment}>Increment</button>
</main>
)
}
`
)
await session.evaluate(() => document.que... | ./index.js (1:27)
Expected '>', got '<eof>'
> 1 | export default () => <div/
| ^",
"stack": [],
}
`)
} else if (isRspack) {
await expect({ browser, next }).toDisplayRedbox(` | <div/`)
if (isTurbopack) {
await expect(browser).toDisplayRedbox(`
{
"description": "Expected '>', got '<eof>'",
"environmentLabel": null,
"label": "Build Error",
"source": " | {
"filepath": "test/development/acceptance/error-recovery.test.ts",
"language": "typescript",
"file_size": 26021,
"cut_index": 1331,
"middle_length": 229
} |
expect.stringContaining(
'https://react.dev/link/hydration-mismatch'
),
source: 'error',
},
])
)
})
it('should show correct hydration error when client and server render different text', async () => {
await using sandbox = await createSandbox(
... | `,
],
])
)
const { session, browser } = sandbox
// Pages Router uses React version without Owner Stacks hence the empty `stack`
if (isReact18) {
await expect(browser).toDisplayRedbox(`
[
{
| return (
<div className="parent">
<main className="child">{isClient ? "client" : "server"}</main>
</div>
);
}
| {
"filepath": "test/development/acceptance/hydration-error.test.ts",
"language": "typescript",
"file_size": 36980,
"cut_index": 2151,
"middle_length": 229
} |
xtTestSetup } from 'e2e-utils'
describe('Custom Document Head Warnings', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('warns when using a <title> in document/head', async () => {
await next.render('/')
expect(next.cliOutput).toMatch(
/.*Warning: <title> should not be used i... | ent.js's <Head>\..*/
)
})
it('warns when using a crossOrigin attribute on document/head', async () => {
await next.render('/')
expect(next.cliOutput).toMatch(
/.*Warning: `Head` attribute `crossOrigin` is deprecated\..*/
)
})
} | ing: viewport meta tags should not be used in _docum | {
"filepath": "test/development/document-head-warnings/document-head-warnings.test.ts",
"language": "typescript",
"file_size": 833,
"cut_index": 523,
"middle_length": 52
} |
'e2e-utils'
import { retry } from '../../lib/next-test-utils'
describe('Replaying internal errors', () => {
const { next } = nextTestSetup({ files: __dirname })
it('should not log the internal error thrown by redirect()', async () => {
const EXPECTED_REPLAYED_MESSAGE = 'This error should get replayed'
co... | heck for redbox here,
// but it seems to disappear the first time we navigate to /target.
// But checking console errors should be enough because they're closely tied
const logs = await browser.log()
expect(logs).toContainEqual(
exp | expect(await browser.elementByCss('h1').text()).toBe('Redirected')
})
expect(next.cliOutput).toContain(EXPECTED_REPLAYED_MESSAGE)
expect(next.cliOutput).not.toContain(OMITTED_ERROR_MESSAGE)
// It'd be good to c | {
"filepath": "test/development/replayed-internal-errors/index.test.ts",
"language": "typescript",
"file_size": 2507,
"cut_index": 563,
"middle_length": 229
} |
React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import 'firebase/firestore'
export async function getStaticPaths() {
return {
paths: [
'/blog/post-1',
{ params: { post: 'post-2' } },
'/blog/[post3]',
'/blog/post-4',
'/blog/post.1',
'/bl... | try again..')
}
}
return {
props: {
params,
post: params.post,
time: (await import('perf_hooks')).performance.now(),
},
revalidate: 10,
}
}
export default ({ post, time, params }) => {
return (
<>
<p>Po | (resolve) => {
setTimeout(() => resolve(), 1000)
})
}
if (params.post === 'post-100') {
throw new Error('such broken..')
}
if (params.post === 'post-999') {
if (++counter < 6) {
throw new Error(' | {
"filepath": "test/development/prerender/pages/blog/[post]/index.js",
"language": "javascript",
"file_size": 1244,
"cut_index": 518,
"middle_length": 229
} |
opack-only feature (requires NAPI project handle)
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'mcp-server get_compilation_issues tool',
() => {
const { next, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'compilation-errors-app'),
})
if (skipped) {
ret... | get_compilation_issues', arguments: {} },
}),
})
const text = await response.text()
const match = text.match(/data: ({.*})/s)
expect(match).toBeTruthy()
const result = JSON.parse(match![1])
return JSON.parse(res | on',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 'get-compilation-issues',
method: 'tools/call',
params: { name: ' | {
"filepath": "test/development/mcp-server/mcp-server-get-compilation-issues.test.ts",
"language": "typescript",
"file_size": 3193,
"cut_index": 614,
"middle_length": 229
} |
frames } from '@emotion/react'
import styled from '@emotion/styled'
export const globalStyles = (
<Global
styles={css`
html,
body {
padding: 3rem 1rem;
margin: 0;
background: papayawhip;
min-height: 100%;
font-family: Helvetica, Arial, sans-serif;
font-... | ckground-color: lightgray;
border-color: aqua;
box-shadow:
-15px -15px 0 0 aqua,
-30px -30px 0 0 cornflowerblue;
}
`
export const bounce = keyframes`
from {
transform: scale(1.01);
}
to {
transform: scale(0.99);
}
`
e | om: 'none',
boxShadow: '5px 5px 0 0 lightgreen, 10px 10px 0 0 lightyellow',
transition: 'all 0.1s linear',
margin: '3rem 0',
padding: '1rem 0.5rem',
})
export const hoverStyles = css`
&:hover {
color: white;
ba | {
"filepath": "test/development/basic/emotion-swc/fixture/shared/styles.js",
"language": "javascript",
"file_size": 1635,
"cut_index": 537,
"middle_length": 229
} |
export default function Page() { return <Comp /> }
`,
],
[
'components/Comp.js',
outdent`
export default function Comp() {
return <p>Hello world</p>
}
`,
],
])
describe('Error Overlay for server components compiler errors in pages', () => {
const { next } = nextTestS... | )
await session.waitForRedbox()
await expect(session.getRedboxSource()).resolves.toMatch(
/This API is only available in Server Components/
)
if (process.env.IS_TURBOPACK_TEST) {
expect(next.normalizeTestDirContent(await sessi | } = sandbox
await session.patch(
'components/Comp.js',
outdent`
import { cookies } from 'next/headers'
export default function Page() {
return <p>hello world</p>
}
`
| {
"filepath": "test/development/acceptance/server-component-compiler-errors-in-pages.test.ts",
"language": "typescript",
"file_size": 14821,
"cut_index": 921,
"middle_length": 229
} |
getRedboxHeader, retry } from 'next-test-utils'
describe('TypeScript HMR', () => {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
})
describe('delete a page and add it back', () => {
it('should detect the changes to typescript pages and display it', async () => {
const browser = a... | 'pages/hello.tsx', editedContent)
await retry(async () => {
expect(await browser.elementByCss('body').text()).toMatch(/COOL page/)
})
await next.patchFile('pages/hello.tsx', originalContent)
await retry(async () => {
| readFile('pages/hello.tsx')
const editedContent = originalContent.replace('Hello', 'COOL page')
if (isTurbopack) {
await new Promise((resolve) => setTimeout(resolve, 500))
}
await next.patchFile( | {
"filepath": "test/development/typescript-hmr/typescript-hmr.test.ts",
"language": "typescript",
"file_size": 2854,
"cut_index": 563,
"middle_length": 229
} |
from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('SSG Prerender', () => {
describe('development mode getStaticPaths', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
firebase: '7.14.5',
},
nextConfig: {
experimental: {
... | })
it('should not cache getStaticPaths errors', async () => {
const errMsg = /The `fallback` key must be returned from getStaticPaths/
await retry(async () => {
const html = await next.render('/blog/post-1')
expect(html).t | in('post-1')
expect(html).not.toContain('Error: Failed to load')
const html2 = await next.render('/blog/post-1')
expect(html2).toContain('post-1')
expect(html2).not.toContain('Error: Failed to load')
| {
"filepath": "test/development/prerender/prerender.test.ts",
"language": "typescript",
"file_size": 1548,
"cut_index": 537,
"middle_length": 229
} |
ort { createSandbox } from 'development-sandbox'
import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path'
// TODO: figure out why snapshots mismatch on GitHub actions
// specifically but work in docker and locally
describe.skip('ReactRefreshLogBox scss', () => {
const { next } = nextTestSetup({
... | './index.module.scss';
export default () => {
return (
<div>
<p>lol</p>
</div>
)
}
`
)
await session.waitForNoRedbox()
// Syntax error
await session.patch('in | {
await using sandbox = await createSandbox(next)
const { session } = sandbox
await session.write('index.module.scss', `.button { font-size: 5px; }`)
await session.patch(
'index.js',
`
import | {
"filepath": "test/development/acceptance/ReactRefreshLogBox-scss.test.ts",
"language": "typescript",
"file_size": 2012,
"cut_index": 537,
"middle_length": 229
} |
retry } from 'next-test-utils'
describe('_app/_document removal HMR', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should HMR when _app is removed', async () => {
const indexContent = await next.readFile('pages/index.js')
try {
const browser = await next.browser('/')
... | m _app')
})
await next.patchFile(
'pages/index.js',
`
export default function Page() {
return <p>index page updated</p>
}
`
)
await retry(async () => {
const html = await bro | ext.deleteFile('pages/_app.js')
await retry(async () => {
const html = await browser.eval('document.documentElement.innerHTML')
expect(html).toContain('index page')
expect(html).not.toContain('custo | {
"filepath": "test/development/app-document-remove-hmr/app-document-remove-hmr.test.ts",
"language": "typescript",
"file_size": 3001,
"cut_index": 563,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.