prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
() => {
return (
<div class="container">
<Script id="inline-script">
{`const newDiv = document.createElement('div')
newDiv.id = 'onload-div'
document.querySelector('body').appendChild(newDiv)
`}
</Script>
<Script
id="scriptLazyOnload"
src="http... | /Script>
<Script
src="https://example.com/doesntexist"
strategy="lazyOnload"
onError={(e) => {
console.log('error')
console.log(e)
}}
/>
<div>page3</div>
</div>
)
}
export default | 3.0/dist/css/bootstrap.min.css',
]}
>< | {
"filepath": "test/e2e/script-loader/pages/page3.js",
"language": "javascript",
"file_size": 873,
"cut_index": 559,
"middle_length": 52
} |
d>((r) => {
resolveReady = () => {
if (!ready) {
ready = true
r()
}
}
})
const exit = next
.runCommand(args, {
env: opts.env,
cwd: opts.cwd,
onStdout: (msg) => {
opts.onStdout?.(msg)
if (readyPattern.test(stripAns... | let stdout = ''
let stderr = ''
let app = http.createServer((_, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('OK')
})
await new Promise<void>((resolve, reject) => {
app.on('error', reject)
| => {
child = p
},
})
.finally(() => {
resolveReady()
})
await readyPromise
return { child, exit }
}
const runAndCaptureOutput = async ({ port }: { port: number }) => {
| {
"filepath": "test/e2e/cli/cli.test.ts",
"language": "typescript",
"file_size": 37267,
"cut_index": 2151,
"middle_length": 229
} |
rts swcPlugins', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
dependencies: {
'@swc/plugin-react-remove-properties': '11.1.0',
},
})
if (skipped) return
it('basic case', async () => {
const html = await next.render('/')
... | rn
it('shows a redbox in dev', async () => {
const browser = await next.browser('/')
if (isTurbopack) {
await expect(browser).toDisplayRedbox(`
{
"description": "Failed to execute SWC plugin",
"envir | {
const { next, skipped, isTurbopack } = nextTestSetup({
files: __dirname,
skipDeployment: true,
dependencies: {
'@swc/plugin-react-remove-properties': '7.0.2',
},
})
if (skipped) retu | {
"filepath": "test/e2e/swc-plugins/index.test.ts",
"language": "typescript",
"file_size": 3125,
"cut_index": 614,
"middle_length": 229
} |
fetchViaHTTP, renderViaHTTP } from 'next-test-utils'
import path from 'path'
import fs from 'fs-extra'
const locales = ['', '/en', '/sv', '/nl']
describe('i18n-ignore-rewrite-source-locale', () => {
const { next } = nextTestSetup({
files: {
'pages/api/hello.js': `
export default function handler(req... | locale: false,
},
{
source: '/:locale/rewrite-api/:path*',
destination: '/api/:path*',
locale: false,
},
],
afterFiles: [],
fallback: [],
| 'nl'],
defaultLocale: 'en',
},
async rewrites() {
return {
beforeFiles: [
{
source: '/:locale/rewrite-files/:path*',
destination: '/:path*',
| {
"filepath": "test/e2e/i18n-ignore-rewrite-source-locale/rewrites.test.ts",
"language": "typescript",
"file_size": 2455,
"cut_index": 563,
"middle_length": 229
} |
<Html>
<Head>
<Script
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"
strategy="beforeInteractive"
></Script>
</Head>
<body>
<Main />
<Nex... | script = await browser.eval(
`document.querySelector('script[data-nscript="beforeInteractive"]')`
)
expect(script).not.toBeNull()
} finally {
if (browser) await browser.close()
}
})
})
describe('beforeInteractive in doc | <p>Home page</p>
</>
)
}
`,
},
})
it('Script is injected server-side', async () => {
let browser: Playwright
try {
browser = await next.browser('/')
const | {
"filepath": "test/e2e/next-script/index.test.ts",
"language": "typescript",
"file_size": 13754,
"cut_index": 921,
"middle_length": 229
} |
, () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
sass: 'latest',
},
})
it('should load a Pages Router page correctly', async () => {
const browser = await next.browser('/')
expect(
await browser
.elementByCss('#__next div:nth-child(2)')
... | async () => {
const browser = await next.browser('/test-app')
expect(
await browser
.elementByCss('body div:nth-child(3)')
.getComputedCss('background-color')
).toContain('221, 221, 221')
expect(await browser.eval('d | })
it('should load a App Router page correctly', | {
"filepath": "test/e2e/next-dynamic-css/next-dynamic-css.test.ts",
"language": "typescript",
"file_size": 985,
"cut_index": 582,
"middle_length": 52
} |
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/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/src/Content.jsx",
"language": "jsx",
"file_size": 1511,
"cut_index": 537,
"middle_length": 229
} |
h'
import { FileRef, nextTestSetup } from 'e2e-utils'
describe('i18-preferred-locale-redirect', () => {
const { next } = nextTestSetup({
files: new FileRef(join(__dirname, './app/')),
})
it('should request a path prefixed with my preferred detected locale when accessing index', async () => {
const brows... | IRECTS/)
await browser.waitForElementByCss('#index')
expect(await browser.elementByCss('#index').text()).toBe('Index')
expect(await browser.elementByCss('#current-locale').text()).toBe('id')
expect(requestedPreferredLocalePathCount).toBe | ).pathname === '/id') {
requestedPreferredLocalePathCount++
}
})
const goToIndex = async () => {
await browser.get(next.url)
}
await expect(goToIndex()).resolves.not.toThrow(/ERR_TOO_MANY_RED | {
"filepath": "test/e2e/i18n-preferred-locale-detection/i18n-preferred-locale-detection.test.ts",
"language": "typescript",
"file_size": 2011,
"cut_index": 537,
"middle_length": 229
} |
t */
import { join } from 'path'
import { nextTestSetup, FileRef } from 'e2e-utils'
describe('Custom TypeScript Config', () => {
const { next, skipped } = nextTestSetup({
files: new FileRef(join(__dirname, '..')),
dependencies: {
typescript: '5.4.4',
},
})
if (skipped) {
return
}
it(... | () => {
const html = await next.render('/page')
expect(html).toContain('bar123')
})
it('middleware: allows a user-specific tsconfig via the next config', async () => {
const html = await next.render('/middleware')
expect(html).toContai | user-specific tsconfig via the next config', async | {
"filepath": "test/e2e/typescript-custom-tsconfig/test/index.test.ts",
"language": "typescript",
"file_size": 857,
"cut_index": 529,
"middle_length": 52
} |
check, waitFor } from 'next-test-utils'
import path from 'path'
describe('multi-zone', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: path.join(__dirname, 'app'),
skipDeployment: true,
buildCommand: 'pnpm build',
startCommand: (global as any).isNextDev ? 'pnpm dev' : 'pnpm start'... | thname: '/', content: ['hello from host app'] },
{ pathname: '/guest', content: ['hello from guest app'] },
{
pathname: '/blog/post-1',
content: ['hello from host app /blog/[slug]'],
},
{
pathname: '/guest/blog/post-1',
| t',
start: 'NODE_ENV=production node server.js',
'post-build': 'echo done',
},
},
dependencies: require('./app/package.json').dependencies,
})
if (skipped) {
return
}
it.each([
{ pa | {
"filepath": "test/e2e/multi-zone/multi-zone.test.ts",
"language": "typescript",
"file_size": 2842,
"cut_index": 563,
"middle_length": 229
} |
require('next')
const path = require('path')
const { parse } = require('url')
const http = require('http')
;(async () => {
const requestHandlers = new Map()
const dev = process.env.NODE_ENV !== 'production'
for (const appName of ['host', 'guest']) {
const appDir = path.join(__dirname, 'apps', appName)
... | s.end('not found')
}
try {
await handler(req, res, parse(req.url, true))
} catch (err) {
console.error(err)
res.statusCode = 500
res.end('internal error')
}
})
const parsedPort = Number(process.env.PORT)
const | server = http.createServer(async (req, res) => {
const appName = req.url.startsWith('/guest') ? 'guest' : 'host'
const handler = requestHandlers.get(appName)
if (!handler) {
res.statusCode = 404
return re | {
"filepath": "test/e2e/multi-zone/app/server.js",
"language": "javascript",
"file_size": 1294,
"cut_index": 524,
"middle_length": 229
} |
th'
const dir = path.join(path.dirname(new URL(import.meta.url).pathname), '../..')
const logPath = path.join(dir, 'output-log.json')
export async function POST(req) {
let payloadString = ''
const decoder = new TextDecoder()
const reader = req.clone().body.getReader()
while (true) {
const { done, value } ... | : {}
if (!json[payload.message]) {
json[payload.message] = {
payload,
count: 1,
}
} else {
json[payload.message].count++
}
await fsp.writeFile(logPath, JSON.stringify(json, null, 2), 'utf8')
console.log(`[instrumentat | ? JSON.parse(await fsp.readFile(logPath, 'utf8'))
| {
"filepath": "test/e2e/on-request-error/basic/app/write-log/route.js",
"language": "javascript",
"file_size": 973,
"cut_index": 582,
"middle_length": 52
} |
waitFor } from 'next-test-utils'
describe('@next/third-parties basic usage', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
'@next/third-parties': 'canary',
},
})
it('renders YoutubeEmbed', async () => {
const $ = await next.render$('/youtube-embed')
const ... | bed/v1/place?key=XYZ"]'
)
expect(baseContainer.length).toBe(1)
expect(mapContainer.length).toBe(1)
})
it('renders GTM', async () => {
const browser = await next.browser('/gtm')
await browser.waitForElementByCss('script#_next-gtm') | renders GoogleMapsEmbed', async () => {
const $ = await next.render$('/google-maps-embed')
const baseContainer = $('[data-ntpc="GoogleMapsEmbed"]')
const mapContainer = $(
'[src^="https://www.google.com/maps/em | {
"filepath": "test/e2e/third-parties/index.test.ts",
"language": "typescript",
"file_size": 2313,
"cut_index": 563,
"middle_length": 229
} |
sNextDev, isNextStart } from 'e2e-utils'
describe('CSS Module client-side navigation', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
// Calls `next.build()` and uses an in-test proxy in front of the Next
// server; both rely on the local-process model and are no... | proxyServer = http.createServer(async (req, res) => {
if (
stallCss &&
req.url &&
new URL(req.url, next.url).pathname.endsWith('.css')
) {
console.log('stalling request for', req.url)
await | {
if (!isNextDev) {
await next.build()
}
await next.start()
if (!isNextDev) {
proxyPort = await findPort()
const proxy = httpProxy.createProxyServer({
target: next.url,
})
| {
"filepath": "test/e2e/css-client-nav/css-client-nav.test.ts",
"language": "typescript",
"file_size": 6413,
"cut_index": 716,
"middle_length": 229
} |
rip-ansi'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
describe('next.config.js schema validating - defaultConfig', () => {
const { next, skipped } = nextTestSetup({
files: {
'pages/index.js': `
export default function Page() {
return <p>hello world</p>
}
... | validating - invalid config', () => {
const { next, isNextStart, skipped } = nextTestSetup({
files: {
'pages/index.js': `
export default function Page() {
return <p>hello world</p>
}
`,
'next.config.js': `
module.exp |
}
it('should validate against defaultConfig', async () => {
const output = stripAnsi(next.cliOutput)
expect(output).not.toContain('Invalid next.config.js options detected')
})
})
describe('next.config.js schema | {
"filepath": "test/e2e/config-schema-check/index.test.ts",
"language": "typescript",
"file_size": 1618,
"cut_index": 537,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
describe('twoslash', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
twoslash: '0.3.4',
'twoslash-protocol': '0.3.4',
typescript: '5.9.2',
},
})
it.each(['default', 'esnext'])(
'should annotate twoslash types %s',
asy... | "text": "type X = Promise<number>",
"type": "hover",
},
{
"character": 9,
"docs": "Represents the completion of an asynchronous operation",
"length": 7,
"line": 0,
"start | ise<number>;
'hello'.toUpperCase()",
"error": undefined,
"nodes": [
{
"character": 5,
"length": 1,
"line": 0,
"start": 5,
"target": "X",
| {
"filepath": "test/e2e/twoslash/index.test.ts",
"language": "typescript",
"file_size": 1499,
"cut_index": 524,
"middle_length": 229
} |
om 'path'
import {
findPort,
initNextServerScript,
killApp,
fetchViaHTTP,
} from 'next-test-utils'
if (!(globalThis as any).isNextStart) {
it('should skip for non-next start', () => {})
} else {
describe('output: standalone with twoslash', () => {
const { next, skipped } = nextTestSetup({
files: ... | tput', 'output')
)
await next.build()
tmpFolder = path.join(os.tmpdir(), 'next-standalone-' + Date.now())
await fs.mkdirp(tmpFolder)
const distFolder = path.join(tmpFolder, 'test')
await fs.move(path.join(next.testDir, | return
}
let server: any
let appPort: number
let tmpFolder: string
beforeAll(async () => {
await next.patchFile(
'next.config.js',
(await next.readFile('next.config.js')).replace('// ou | {
"filepath": "test/e2e/twoslash/standalone.test.ts",
"language": "typescript",
"file_size": 3185,
"cut_index": 614,
"middle_length": 229
} |
('Dynamic Route Interpolation', () => {
const { next, isNextStart } = nextTestSetup({
files: __dirname,
})
it('should work', async () => {
const $ = await next.render$('/blog/a')
expect($('#slug').text()).toBe('a')
})
it('should work with parameter itself', async () => {
const $ = await next... | kets in API routes', async () => {
const text = await next.render('/api/dynamic/[abc]')
expect(text).toBe('slug: [abc]')
})
it('should bust data cache', async () => {
const browser = await next.browser('/blog/login')
await browser.elem | ).text()).toBe('[abc]')
})
it('should work with parameter itself in API routes', async () => {
const text = await next.render('/api/dynamic/[slug]')
expect(text).toBe('slug: [slug]')
})
it('should work with brac | {
"filepath": "test/e2e/dynamic-route-interpolation/index.test.ts",
"language": "typescript",
"file_size": 2847,
"cut_index": 563,
"middle_length": 229
} |
|
// |---------|-------------------------|-------------------------|--------------------------------|
// | new URL | /_next/static/media/... | /_next/static/media/... | /server/assets/... |
// | import | /_next/static/media/... | /_next/static/media/... | /_next/static/media/... |
// |---------|---... | skew protection when deployed
NEXT_DEPLOYMENT_ID: isNextStart ? 'test-deployment-id' : undefined,
__NEXT_SUPPORTS_IMMUTABLE_ASSETS: isNextStart ? '1' : undefined,
},
skipDeployment: true,
})
if (skipped) {
return
}
const | // - a bug where Edge Page routes return client assets for `new URL`s.
describe(`Handle new URL asset references`, () => {
const { next, skipped, isTurbopack } = nextTestSetup({
files: __dirname,
env: {
// rely on | {
"filepath": "test/e2e/url/url.test.ts",
"language": "typescript",
"file_size": 6331,
"cut_index": 716,
"middle_length": 229
} |
ld inject propagation data for a dynamically server-side-rendered page', async () => {
const $ = await next.render$('/app-router/dynamic-page')
const headHtml = $.html('head')
expect(headHtml).toContain(
'<meta name="my-test-key-1" content="my-test-value-1">'
)
expect(headHtml).toC... |
const firstLoadSpanIdContent = await browser1
.elementByCss('meta[name="my-parent-span-id"]')
.getAttribute('content')
const browser2 = await next.browser('/app-router/dynamic-page')
const secondLoadSpanIdContent = await | xpect(headHtml).not.toContain('non-metadata-key-3')
})
it('hard loading a dynamic page twice should yield different dynamic trace data', async () => {
const browser1 = await next.browser('/app-router/dynamic-page') | {
"filepath": "test/e2e/opentelemetry/client-trace-metadata/client-trace-metadata.test.ts",
"language": "typescript",
"file_size": 13407,
"cut_index": 921,
"middle_length": 229
} |
ort { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'
import { trace } from '@opentelemetry/api'
export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs') {
const provider = new NodeTracerProvider()
provider.register({
propagator: {
inject(context, carrier, setter)... | ariant'
)
},
extract(context) {
// This is a noop because we don't extract in this test
return context
},
fields() {
return [
'my-parent-span-id',
'my-test-key- | njected into the page
setter.set(carrier, 'non-metadata-key-3', 'non-metadata-key-3')
setter.set(
carrier,
'my-parent-span-id',
trace.getSpanContext(context)?.spanId ?? 'inv | {
"filepath": "test/e2e/opentelemetry/client-trace-metadata/instrumentation.ts",
"language": "typescript",
"file_size": 1112,
"cut_index": 515,
"middle_length": 229
} |
rver } from 'node:http'
import { SavedSpan } from './constants'
export interface Collector {
getSpans: () => SavedSpan[]
shutdown: () => Promise<void>
}
export async function connectCollector({
port,
}: {
port: number
}): Promise<Collector> {
const spans: SavedSpan[] = []
const server = new HttpServer(as... | N.parse(body.toString('utf-8')) as SavedSpan[]
const filteredSpans = newSpans.filter((span) => {
if (span.attributes?.['next.bubble'] === true) {
return false
}
return true
})
spans.push(...filteredSpans)
res.statu | acc: Buffer[] = []
req.on('data', (chunk: Buffer) => {
acc.push(chunk)
})
req.on('end', () => {
resolve(Buffer.concat(acc))
})
req.on('error', reject)
})
const newSpans = JSO | {
"filepath": "test/e2e/opentelemetry/instrumentation/collector.ts",
"language": "typescript",
"file_size": 1542,
"cut_index": 537,
"middle_length": 229
} |
erverResponse } from 'http'
import path from 'path'
import { parse } from 'url'
import getPort from 'get-port'
import { trace } from '@opentelemetry/api'
import { register } from './instrumentation-custom-server'
register()
type EntrypointHandler = (
req: IncomingMessage,
res: ServerResponse,
ctx: {
waitUn... | ndler
}
async function main() {
const port = await getPort()
const hostname = 'localhost'
require('next/dist/server/node-environment')
const appPageHandler = loadEntrypointHandler([
'app',
'app',
'[param]',
'rsc-fetch',
'page | server', ...pathParts)
const mod = require(entrypointPath) as { handler?: EntrypointHandler }
if (typeof mod.handler !== 'function') {
throw new Error(`Entrypoint handler missing at ${entrypointPath}`)
}
return mod.ha | {
"filepath": "test/e2e/opentelemetry/instrumentation/custom-entrypoint-server.ts",
"language": "typescript",
"file_size": 2763,
"cut_index": 563,
"middle_length": 229
} |
{ createServer } from 'http'
import { parse } from 'url'
import next from 'next'
import getPort from 'get-port'
import { trace } from '@opentelemetry/api'
import { register } from './instrumentation-custom-server'
register()
async function main() {
const port = await getPort()
const hostname = 'localhost'
con... | const parsedUrl = parse(req.url!, true)
await handle(req, res, parsedUrl)
span.end()
} catch (err) {
span.recordException(err as Error)
span.end()
res.statusCode = 500
res.end('Internal Server E | r = trace.getTracer('custom-server', '1.0.0')
createServer((req, res) => {
// Create a local parent span to simulate custom server behavior
tracer.startActiveSpan('custom-server-request', async (span) => {
try {
| {
"filepath": "test/e2e/opentelemetry/instrumentation/custom-server.ts",
"language": "typescript",
"file_size": 1225,
"cut_index": 518,
"middle_length": 229
} |
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'
import {
ExportResult,
ExportResultCode,
hrTimeToMicroseconds,
} from '@opentelemetry/core'
impor... | ReadableSpan['links']
}
const serializeSpan = (span: ReadableSpan): SerializedSpan => ({
runtime: process.env.NEXT_RUNTIME,
traceId: span.spanContext().traceId,
parentId: span.parentSpanId,
traceState: span.spanContext().traceState?.serialize(),
| te: string | undefined
name: string
id: string
kind: number
timestamp: number
duration: number
attributes: Record<string, unknown>
status: { code: number; message?: string }
events: ReadableSpan['events']
links: | {
"filepath": "test/e2e/opentelemetry/instrumentation/instrumentation-custom-server.ts",
"language": "typescript",
"file_size": 2898,
"cut_index": 563,
"middle_length": 229
} |
ces'
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'
// You can use http exporter instead
import { OTLPTraceExporter } from '@opentelemetry/exporter-tr... | racerProvider({
resource: new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: 'next-app',
}),
})
provider.addSpanProcessor(new SimpleSpanProcessor(new OTLPTraceExporter({})))
// Make sure to register you provider
provider.regi | e of Next.js internals.
const provider = new NodeT | {
"filepath": "test/e2e/opentelemetry/instrumentation/instrumentation-node.ts",
"language": "typescript",
"file_size": 876,
"cut_index": 559,
"middle_length": 52
} |
from 'e2e-utils'
import { retry } from 'next-test-utils'
for (const { app, src, pathname, text } of [
{
pages: true,
src: false,
pathname: '/pages/param/getServerSideProps',
text: 'Page',
},
{
pages: true,
src: true,
pathname: '/pages/param/getServerSideProps',
text: 'Page',
},
... | les: __dirname,
env: {
NEXT_PUBLIC_SIMPLE_INSTRUMENT: '1',
},
skipDeployment: true,
packageJson: {
scripts: {
'setup-dir': `mv instrumentation-minimal.ts instrumentation.ts; rm -rf ${oppositeDir}${
| ) {
describe(`instrumentation ${app ? 'app' : 'pages'}${
src ? ' src/' : ''
}`, () => {
const curDir = app ? 'app' : 'pages'
const oppositeDir = app ? 'pages' : 'app'
const { next } = nextTestSetup({
fi | {
"filepath": "test/e2e/opentelemetry/instrumentation/instrumentation-pages-app-only.test.ts",
"language": "typescript",
"file_size": 1708,
"cut_index": 537,
"middle_length": 229
} |
MapPropagator,
} from '@opentelemetry/api'
import { Resource } from '@opentelemetry/resources'
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
import { BasicTracerProvider } from '@opentelemetry/sdk-trace-base'
import { AsyncLocalStorageContextManager } from '@opentelemetry/context-asyn... | : ReadableSpan): SavedSpan => ({
runtime: process.env.NEXT_RUNTIME,
traceId: span.spanContext().traceId,
parentId: span.parentSpanId,
traceState: span.spanContext().traceState?.serialize(),
name: span.name,
id: span.spanContext().spanId,
kind | ExportResultCode,
W3CTraceContextPropagator,
hrTimeToMicroseconds,
} from '@opentelemetry/core'
import { SavedSpan } from './constants'
const customKey = Symbol.for('opentelemetry.test/custom')
const serializeSpan = (span | {
"filepath": "test/e2e/opentelemetry/instrumentation/instrumentation-test.ts",
"language": "typescript",
"file_size": 3823,
"cut_index": 614,
"middle_length": 229
} |
() => {
describe('app router', () => {
it('should handle RSC with fetch', async () => {
await next.fetch('/app/param/rsc-fetch', env.fetchInit)
await expectTrace(getCollector(), [
{
name: 'GET /app/[param]/rsc-fetch',
attrib... | Request',
},
kind: 1,
status: { code: 0 },
traceId: env.span.traceId,
parentId: env.span.rootParentId,
spans: [
{
name: 'r | m/rsc-fetch',
'next.route': '/app/[param]/rsc-fetch',
'next.rsc': false,
'next.span_name': 'GET /app/[param]/rsc-fetch',
'next.span_type': 'BaseServer.handle | {
"filepath": "test/e2e/opentelemetry/instrumentation/opentelemetry.test.ts",
"language": "typescript",
"file_size": 64729,
"cut_index": 2151,
"middle_length": 229
} |
alid multi-match', () => {
const { next, isNextDeploy, skipped } = nextTestSetup({
files: __dirname,
disableAutoSkewProtection: true,
// The test asserts on `next.cliOutput`, expecting the local
// `next build` failure message ("To use a multi-match in the
// destination..."). In deploy mode `next... |
it('should show error for invalid multi-match', async () => {
await next.render('/random')
expect(next.cliOutput).toContain(
'To use a multi-match in the destination you must add'
)
expect(next.cliOutput).toContain(
'https:/ | })
if (skipped) return
if (isNextDeploy) return | {
"filepath": "test/e2e/invalid-multi-match/invalid-multi-match.test.ts",
"language": "typescript",
"file_size": 951,
"cut_index": 582,
"middle_length": 52
} |
ndalone-expect */
import { join } from 'path'
import { fetchViaHTTP } from 'next-test-utils'
import { FileRef, isNextDeploy, nextTestSetup } from 'e2e-utils'
const itif = (condition: boolean) => (condition ? it : it.skip)
describe('Middleware custom matchers i18n', () => {
const { next } = nextTestSetup({
file... | ut'])(
'should not match %s',
async (path) => {
const res = await fetchViaHTTP(next.url, path)
expect(res.status).toBe(404)
}
)
// FIXME:
// See https://linear.app/vercel/issue/EC-160/header-value-set-on-middleware-is-not-pro | iaHTTP(next.url, path)
console.log(res.status)
expect(res.status).toBe(200)
expect(res.headers.get('x-from-middleware')).toBeDefined()
}
)
it.each(['/invalid/hello', '/hello/invalid', '/about', '/en/abo | {
"filepath": "test/e2e/middleware-custom-matchers-i18n/test/index.test.ts",
"language": "typescript",
"file_size": 2687,
"cut_index": 563,
"middle_length": 229
} |
{ FileRef, nextTestSetup } from 'e2e-utils'
describe('specified tsconfig', () => {
const { next, skipped } = nextTestSetup({
files: new FileRef(__dirname),
dependencies: {
typescript: '5.4.4',
},
})
if (skipped) {
return
}
it('app router: allows a user-specific tsconfig via the next ... | ml = await next.render('/page')
expect(html).toContain('bar123')
})
it('middleware: allows a user-specific tsconfig via the next config', async () => {
const html = await next.render('/middleware')
expect(html).toContain('bar123')
})
})
| {
const ht | {
"filepath": "test/e2e/tsconfig-path/index.test.ts",
"language": "typescript",
"file_size": 788,
"cut_index": 518,
"middle_length": 14
} |
import { nextTestSetup, isNextDev } from 'e2e-utils'
import { readFileSync, writeFileSync } from 'fs'
describe('TypeScript Features', () => {
describe.each([
{ label: '', testBaseUrl: true },
{ label: ' without baseUrl', testBaseUrl: false },
])('default behavior$label', ({ testBaseUrl }) => {
const ts... | 'packages/www/types/unfetch.d.ts'
)
.replace('./packages/www/components/*', 'packages/www/components/*')
.replace('./packages/lib/a/*', 'packages/lib/a/*')
.replace('./packages/lib/b/*', 'packages/lib/b/*') | readFileSync(tsConfigPath, 'utf-8')
const nextTsConfigJsonc = previousTsConfigJsonc
.replace('// baseUrl will go here', '"baseUrl": ".",')
.replace(
'./packages/www/types/unfetch.d.ts',
| {
"filepath": "test/e2e/typescript-workspaces-paths/packages/www/test/index.test.ts",
"language": "typescript",
"file_size": 2995,
"cut_index": 563,
"middle_length": 229
} |
ort { FileRef, nextTestSetup } from 'e2e-utils'
import { join } from 'path'
import { check } from 'next-test-utils'
describe('browser-shallow-navigation', () => {
const { next } = nextTestSetup({
files: {
pages: new FileRef(join(__dirname, 'app/pages')),
'middleware.js': new FileRef(join(__dirname, '... | llow-replace]')
// do shadow replace
await browser.elementByCss('[data-next-shallow-replace]').click()
await browser.waitForElementByCss('[data-go-back]')
// go back using history api
await browser.elementByCss('[data-go-back]').click | ta-next-shallow-push]').click()
await browser.waitForElementByCss('[data-next-page]')
// go to another page
await browser.elementByCss('[data-next-page]').click()
await browser.waitForElementByCss('[data-next-sha | {
"filepath": "test/e2e/middleware-shallow-link/index.test.ts",
"language": "typescript",
"file_size": 1110,
"cut_index": 515,
"middle_length": 229
} |
retry } from 'next-test-utils'
import cheerio from 'cheerio'
describe('gip identifiers', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
const getNextData = async () => {
const html = await next.render('/')
const $ = c... | 'pages/index.js',
`
const Page = () => 'hi'
Page.getInitialProps = () => ({ hello: 'world' })
export default Page
`
)
await retry(async () => {
const data = await getNextData()
expec | t getNextData()
expect(data.gip).toBe(undefined)
expect(data.appGip).toBe(undefined)
})
if (isNextDev) {
it('should have gip in NEXT_DATA for page with getInitialProps', async () => {
await next.patchFile(
| {
"filepath": "test/e2e/gip-identifier/gip-identifier.test.ts",
"language": "typescript",
"file_size": 2183,
"cut_index": 563,
"middle_length": 229
} |
ort { nextTestSetup } from 'e2e-utils'
describe('import-meta', () => {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
})
describe('import.meta.url', () => {
it('should work on the server', async () => {
const $ = await next.render$('/')
const testData = $('#test-data').text(... | = await browser.elementByCss('#test-data').text()
const data = JSON.parse(testData)
if (isTurbopack) {
expect(data.url).toBe('file:///ROOT/pages/index.tsx')
} else {
expect(data.url).toStartWith('file:///')
expect | expect(data.url).toStartWith('file:///')
expect(data.url).toEndWith('/pages/index.tsx')
}
})
it('should work in browser', async () => {
const browser = await next.browser('/')
const testData | {
"filepath": "test/e2e/import-meta/import-meta.test.ts",
"language": "typescript",
"file_size": 1064,
"cut_index": 515,
"middle_length": 229
} |
'e2e-utils'
import { retry } from 'next-test-utils'
describe('i18n Support Fallback Rewrite', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should not rewrite for index page', async () => {
for (const [pathname, query] of [
['/', {}],
['/en', {}],
['/fr', {}],
... | )
await retry(async () => {
expect(
JSON.parse(await browser.elementByCss('#router').text())
).toEqual({
index: true,
pathname: '/',
asPath: url.format({ pathname: '/', query }),
quer | await next.browser(asPath)
expect(JSON.parse(await browser.elementByCss('#router').text())).toEqual({
index: true,
pathname: '/',
asPath: url.format({ pathname: '/', query }),
query,
} | {
"filepath": "test/e2e/i18n-support-fallback-rewrite/i18n-support-fallback-rewrite.test.ts",
"language": "typescript",
"file_size": 2214,
"cut_index": 563,
"middle_length": 229
} |
tTestSetup } from 'e2e-utils'
import { listClientChunks, retry } from 'next-test-utils'
import fs from 'fs'
import path from 'path'
describe('swc-auto-polyfill-disabled', () => {
const { next, isNextDev, isNextDeploy } = nextTestSetup({
files: __dirname,
})
it('should render the page correctly without swcEn... | Dir))
).filter((f) => f.endsWith('.js'))
for (const file of jsFiles) {
const content = fs.readFileSync(
path.join(next.testDir, next.distDir, file),
'utf-8'
)
// Skip the built-in polyfill-nomodule c | c')
})
})
if (!isNextDev && !isNextDeploy) {
it('should not include replaceAll polyfill in non-framework chunks', async () => {
const jsFiles = (
await listClientChunks(path.join(next.testDir, next.dist | {
"filepath": "test/e2e/swc-auto-polyfill-disabled/swc-auto-polyfill-disabled.test.ts",
"language": "typescript",
"file_size": 1264,
"cut_index": 524,
"middle_length": 229
} |
t { FileRef, nextTestSetup, isNextDev } from 'e2e-utils'
import { join } from 'path'
// experimental.urlImports is not implemented in Turbopack
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
`Handle url imports`,
() => {
let staticServer
let staticServerPort
beforeAll(async () => {
... | s': new FileRef(join(__dirname, 'next.config.js')),
pages: new FileRef(join(__dirname, 'pages')),
public: new FileRef(join(__dirname, 'public')),
}
: __dirname,
// The staticServer above doesn't work when dep | await stopApp(staticServer)
})
const { next, skipped } = nextTestSetup({
files: isNextDev
? {
// exclude next.lock here, should be generated automatically in dev
'next.config.j | {
"filepath": "test/e2e/url-imports/url-imports.test.ts",
"language": "typescript",
"file_size": 3094,
"cut_index": 614,
"middle_length": 229
} |
gJson } from '../_testing/utils'
describe('on-request-error - basic', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
const outputLogPath = 'output-log.json'
async function validateErrorRecord({
errorMessage,
url,
... | age)])
)
// TODO: remove custom duration in case we increase the default.
}, 5000)
const json = await getOutputLogJson(next, outputLogPath)
const record = json[errorMessage]
const { payload } = record
const { request } = p | st recordLogLines = next.cliOutput
.split('\n')
.filter((log) => log.includes('[instrumentation] write-log'))
expect(recordLogLines).toEqual(
expect.arrayContaining([expect.stringContaining(errorMess | {
"filepath": "test/e2e/on-request-error/basic/basic.test.ts",
"language": "typescript",
"file_size": 4673,
"cut_index": 614,
"middle_length": 229
} |
retry } from 'next-test-utils'
import { getOutputLogJson } from '../_testing/utils'
describe('on-request-error - otel', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
packageJson: {
dependencies: {
'@vercel/otel': '^1.13.0',
},
},
})
... | cludes('[instrumentation] write-log'))
expect(recordLogLines).toEqual(
expect.arrayContaining([expect.stringContaining(errorMessage)])
)
// TODO: remove custom duration in case we increase the default.
}, 5000)
const json | url: string
renderSource: string | undefined
}) {
// Assert the instrumentation is called
await retry(async () => {
const recordLogLines = next.cliOutput
.split('\n')
.filter((log) => log.in | {
"filepath": "test/e2e/on-request-error/otel/otel.test.ts",
"language": "typescript",
"file_size": 2164,
"cut_index": 563,
"middle_length": 229
} |
ort path from 'path'
const dir = path.dirname(new URL(import.meta.url).pathname)
const logPath = path.join(dir, 'output-log.json')
export async function register() {
fs.writeFileSync(logPath, '{}', 'utf8')
}
// Since only Node.js runtime support ISR, we can just write the error state to a file here.
// `onRequestE... | arse(fs.readFileSync(logPath, 'utf8'))
: {}
json[payload.message] = payload
console.log(
`[instrumentation] write-log:${payload.message} ${payload.context.revalidateReason}`
)
fs.writeFileSync(logPath, JSON.stringify(json, null, 2), 'utf8 |
const json = fs.existsSync(logPath)
? JSON.p | {
"filepath": "test/e2e/on-request-error/isr/instrumentation.js",
"language": "javascript",
"file_size": 848,
"cut_index": 535,
"middle_length": 52
} |
('on-request-error - skip-next-internal-error', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
async function assertNoNextjsInternalErrors() {
const output = next.cliOutput
// No navigation errors
expect(output).no... | tion errors
it('should not catch server component not-found errors', async () => {
await next.fetch('/server/not-found')
await assertNoNextjsInternalErrors()
})
it('should not catch server component redirect errors', async () => {
| utput).not.toContain('DYNAMIC_SERVER_USAGE')
// No react postpone errors
// TODO: cover PPR errors later
expect(output).not.toContain('react.postpone')
}
describe('app router render', () => {
// Server naviga | {
"filepath": "test/e2e/on-request-error/skip-next-internal-error/skip-next-internal-error.test.ts",
"language": "typescript",
"file_size": 2857,
"cut_index": 563,
"middle_length": 229
} |
gJson } from '../_testing/utils'
describe('on-request-error - dynamic-routes', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
const outputLogPath = 'output-log.json'
async function getErrorRecord({ errorMessage }: { errorM... | }, 5000)
const json = await getOutputLogJson(next, outputLogPath)
const record = json[errorMessage]
return record
}
beforeAll(async () => {
await next.patchFile(outputLogPath, '{}')
})
describe('app router', () => {
it('sho | udes('[instrumentation] write-log'))
expect(recordLogLines).toEqual(
expect.arrayContaining([expect.stringContaining(errorMessage)])
)
// TODO: remove custom duration in case we increase the default.
| {
"filepath": "test/e2e/on-request-error/dynamic-routes/dynamic-routes.test.ts",
"language": "typescript",
"file_size": 4241,
"cut_index": 614,
"middle_length": 229
} |
th'
const dir = path.join(path.dirname(new URL(import.meta.url).pathname), '../..')
const logPath = path.join(dir, 'output-log.json')
export async function POST(req) {
let payloadString = ''
const decoder = new TextDecoder()
const reader = req.clone().body.getReader()
while (true) {
const { done, value } ... | : {}
if (!json[payload.message]) {
json[payload.message] = {
payload,
count: 1,
}
} else {
json[payload.message].count++
}
await fsp.writeFile(logPath, JSON.stringify(json, null, 2), 'utf8')
console.log(`[instrumentat | ? JSON.parse(await fsp.readFile(logPath, 'utf8'))
| {
"filepath": "test/e2e/on-request-error/server-action-error/app/write-log/route.js",
"language": "javascript",
"file_size": 973,
"cut_index": 582,
"middle_length": 52
} |
from './data.txt' with { type: 'text' }
import jsAsText from './some.js' with { type: 'text' }
import bytes from './data.bin' with { type: 'bytes' }
import jsAsBytes from './some.js' with { type: 'bytes' }
import configuredAsJsAsBytes from './configured-as-ecmascript.txt' with { type: 'bytes' }
import json from './data... | rray: bytes instanceof Uint8Array,
length: bytes.length,
content: new TextDecoder().decode(bytes),
},
jsAsBytes: {
instanceofUint8Array: jsAsBytes instanceof Uint8Array,
content: new TextDecoder().decode(jsAsByte | eof text === 'string',
length: text.length,
content: text,
},
jsAsText: {
typeofString: typeof jsAsText === 'string',
content: jsAsText,
},
bytes: {
instanceofUint8A | {
"filepath": "test/e2e/turbopack-import-with-type/app/api/route.js",
"language": "javascript",
"file_size": 1442,
"cut_index": 524,
"middle_length": 229
} |
import { nextTestSetup } from 'e2e-utils'
describe('next/dynamic', () => {
const { next } = nextTestSetup({ files: __dirname })
it('should render server value', async () => {
const html = await next.render('/')
expect(html).toMatch(/the-server-value/i)
})
it('should render dynamic server rendered val... | // should not print "invalid-dynamic-suspense" warning in browser's console
const logs = (await browser.log()).map((log) => log.message).join('\n')
expect(logs).not.toContain(
'https://nextjs.org/docs/messages/invalid-dynamic-suspense'
| --><!-- -->'
expect(text).toMatch(
/^Index<!--\/?(\$|\s)-->1(<!--\/?(\$|\s)-->)+2(<!--\/?(\$|\s)-->)+3(<!--\/?(\$|\s)-->)+4(<!--\/?(\$|\s)-->)+4$/
)
expect(await browser.eval('window.caughtErrors')).toBe('')
| {
"filepath": "test/e2e/next-dynamic/next-dynamic.test.ts",
"language": "typescript",
"file_size": 1007,
"cut_index": 512,
"middle_length": 229
} |
= [
{
name: 'should error when domains length exceeds 50',
config: JSON.stringify({
images: { domains: new Array(51).fill('google.com') },
}),
expected:
'Array must contain at most 50 element(s) at "images.domains"',
},
{
name: 'should error ... | config: JSON.stringify({
images: {
localPatterns: [{ pathname: '/foo/**', foo: 'bar' }],
},
}),
expected: `Unrecognized key(s) in object: 'foo' at "images.localPatterns[0]"`,
},
{
name | ,
})),
},
}),
expected:
'Array must contain at most 25 element(s) at "images.localPatterns"',
},
{
name: 'should error when localPatterns has invalid prop',
| {
"filepath": "test/e2e/image-optimizer/image-optimizer.test.ts",
"language": "typescript",
"file_size": 17638,
"cut_index": 1331,
"middle_length": 229
} |
retry } from 'next-test-utils'
describe('Link with legacyBehavior', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return it('should skip', () => {})
}
describe('if the child is an <a> tag', () => {
it('forwards the hre... | Page')
})
})
it('works if the child is a number', async () => {
const browser = await next.browser('/child-is-a-number')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('h1').text()
expect(title). | navigates correctly', async () => {
const browser = await next.browser('/')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('#about-page').text()
expect(title).toBe('About | {
"filepath": "test/e2e/legacy-link-behavior/index.test.ts",
"language": "typescript",
"file_size": 2953,
"cut_index": 563,
"middle_length": 229
} |
st { next } = nextTestSetup({
files: {
pages: new FileRef(join(__dirname, 'pages')),
'next.config.js': new FileRef(join(__dirname, 'next.config.js')),
},
dependencies: {},
})
it('should restore the scroll position on navigating back', async () => {
const browser = await next.browser('/0... | window.scrollX)),
y: Math.floor(await browser.eval(() => window.scrollY)),
})
// check initial value
expect(scrollPositionMemories[0].x).not.toBe(0)
expect(scrollPositionMemories[0].y).not.toBe(0)
await browser.eval(`window.next | .history.scrollRestoration
)
expect(scrollRestoration).toBe('manual')
const scrollPositionMemories: Array<{ x: number; y: number }> = []
scrollPositionMemories.push({
x: Math.floor(await browser.eval(() => | {
"filepath": "test/e2e/reload-scroll-backforward-restoration/index.test.ts",
"language": "typescript",
"file_size": 5395,
"cut_index": 716,
"middle_length": 229
} |
k'
import { useRouter } from 'next/router'
const Page = ({ id }) => {
const router = useRouter()
const [ready, setReady] = useState(false)
useEffect(() => {
router.events.on('routeChangeComplete', () => {
setReady(true)
})
}, [router, ready, setReady])
return (
<>
<div
style=... | marginLeft: 5000,
width: 95000,
display: 'block',
}}
>
next page
</Link>
<div id="end-el">hello, world</div>
</>
)
}
export default Page
export const getServerSideProps = (context) => {
const | + 1}`}
id="link"
style={{
| {
"filepath": "test/e2e/reload-scroll-backforward-restoration/pages/[id].js",
"language": "javascript",
"file_size": 964,
"cut_index": 582,
"middle_length": 52
} |
('react version', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should use react-server condition for app router server components pages', async () => {
const rscPagesRoutes = ['/app/server', '/app/server-edge']
for (const route of rscPagesRoutes) {
const $ = await next.ren... | pect($('#react-export-condition').text()).toBe('default')
expect($('#react-dom-export-condition').text()).toBe('default')
}
})
it('should use react-server condition for app router custom routes', async () => {
const customRoutes = ['/app | -server condition for app router client components pages', async () => {
const rscPagesRoutes = ['/app/client', '/app/client-edge']
for (const route of rscPagesRoutes) {
const $ = await next.render$(route)
ex | {
"filepath": "test/e2e/react-version/react-version.test.ts",
"language": "typescript",
"file_size": 2088,
"cut_index": 563,
"middle_length": 229
} |
v jest */
import { join } from 'path'
import { fetchViaHTTP } from 'next-test-utils'
import { FileRef, nextTestSetup } from 'e2e-utils'
describe('Requests not effected when middleware used', () => {
const { next } = nextTestSetup({
files: {
pages: new FileRef(join(__dirname, '../app/pages')),
'middl... | = {
'content-type': 'application/json',
'x-custom-header': 'some value',
}
const res = await fetchViaHTTP(next.url, `api`, '', {
method: method.toUpperCase(),
headers,
body: method.toLowerCase() !== 'get' | ead'].includes(method.toLowerCase())
? JSON.stringify({
key: 'value',
})
: undefined
it(`should proxy ${method} request ${
body ? 'with body' : ''
}`, async () => {
const headers | {
"filepath": "test/e2e/proxy-request-with-middleware/test/index.test.ts",
"language": "typescript",
"file_size": 1389,
"cut_index": 524,
"middle_length": 229
} |
th'
import { nextTestSetup } from 'e2e-utils'
describe('chrome-devtools-workspace default', () => {
const { isNextDev, next } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'default'),
})
it('should be able to connect to Chrome DevTools in dev', async () => {
const devtoolsResponse = await ne... | table across reloads.
// Otherwise you'd have to reconnect every-time.
expect(await pageReload.json()).toEqual(json)
} else {
expect({ status: devtoolsResponse.status }).toEqual({ status: 404 })
}
})
})
describe('chrome-devtool | {
uuid: expect.any(String),
root: next.testDir,
},
})
const pageReload = await next.fetch(
'/.well-known/appspecific/com.chrome.devtools.json'
)
// The UUID should be s | {
"filepath": "test/e2e/chrome-devtools-workspace/chrome-devtools-workspace.test.ts",
"language": "typescript",
"file_size": 1919,
"cut_index": 537,
"middle_length": 229
} |
th'
const dir = path.join(path.dirname(new URL(import.meta.url).pathname), '../..')
const logPath = path.join(dir, 'output-log.json')
export async function POST(req) {
let payloadString = ''
const decoder = new TextDecoder()
const reader = req.clone().body.getReader()
while (true) {
const { done, value } ... | : {}
if (!json[payload.message]) {
json[payload.message] = {
payload,
count: 1,
}
} else {
json[payload.message].count++
}
await fsp.writeFile(logPath, JSON.stringify(json, null, 2), 'utf8')
console.log(`[instrumentat | ? JSON.parse(await fsp.readFile(logPath, 'utf8'))
| {
"filepath": "test/e2e/on-request-error/dynamic-routes/app/write-log/route.js",
"language": "javascript",
"file_size": 973,
"cut_index": 582,
"middle_length": 52
} |
mport { nextTestSetup } from 'e2e-utils'
describe('invalid-static-asset-404-app', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should return correct output with status 200 on valid asset path', async () => {
const buildManifestPath = `/_next/static/${next.buildId}/_buildManifest.js$... | text).toContain('Custom Not Found')
})
it('should return 404 with plain text when fetching invalid asset path', async () => {
const res = await next.fetch('/_next/static/invalid-path')
expect(res.status).toBe(404)
const text = await res.te | EST')
})
it('should return custom 404 page when fetching invalid non-asset path', async () => {
const res = await next.fetch('/invalid-path')
expect(res.status).toBe(404)
const text = await res.text()
expect( | {
"filepath": "test/e2e/invalid-static-asset-404-app/invalid-static-asset-404-app.test.ts",
"language": "typescript",
"file_size": 1046,
"cut_index": 513,
"middle_length": 229
} |
Buffer.from(await res.arrayBuffer())
const d = sizeOf(buffer)
expect(d.width).toBe(w)
const lengthStr = res.headers.get('Content-Length')
expect(lengthStr).toBe(Buffer.byteLength(buffer).toString())
expect(isAnimated(buffer)).toBe(expectAnimated)
}
export const cleanImagesDir = async (imagesDir) => {
conso... | etDirSize(entryPath)
} else {
totalSize += stat.size
}
}
return totalSize
}
async function expectAvifSmallerThanWebp(
next: NextInstance,
w: number,
q: number
) {
const qs = toQueryString({ url: '/mountains.jpg', w, q })
const | [] as string[])
for (const entry of entries) {
const entryPath = join(dir, entry)
const stat = await fs.stat(entryPath).catch(() => null)
if (!stat) continue
if (stat.isDirectory()) {
totalSize += await g | {
"filepath": "test/e2e/image-optimizer/util.ts",
"language": "typescript",
"file_size": 68898,
"cut_index": 3790,
"middle_length": 229
} |
lEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==',
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAEBgIApD5fRAAAAABJRU5ErkJggg==',
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPj/HwADBwIAMCbHYQAAAABJRU5ErkJggg==',
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5/h... | 0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=',
]
let state = 0
export default function handler(_req, res) {
state++
const index = state % images.length
const buffer = Buffer.from(images[index], 'base64')
| QVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
'iVBORw | {
"filepath": "test/e2e/image-optimizer/app/pages/api/stateful/test.png.js",
"language": "javascript",
"file_size": 960,
"cut_index": 582,
"middle_length": 52
} |
t * as path from 'path'
import { nextTestSetup } from 'e2e-utils'
describe('chrome-devtools-workspace basePath', () => {
const { isNextDev, next } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'base-path'),
})
it('should be able to connect to Chrome DevTools in dev with a configured basePath', a... | n = await devtoolsResponse.json()
expect(json).toEqual({
workspace: {
uuid: expect.any(String),
root: next.testDir,
},
})
} else {
expect({ status: devtoolsResponse.status }).toEqual({ status: 404 } | const jso | {
"filepath": "test/e2e/chrome-devtools-workspace/chrome-devtools-workspace-base-path.test.ts",
"language": "typescript",
"file_size": 803,
"cut_index": 517,
"middle_length": 14
} |
retry, waitFor } from 'next-test-utils'
import { getOutputLogJson } from '../_testing/utils'
const outputLogPath = 'output-log.json'
describe('on-request-error - isr', () => {
const { next, skipped, isNextDev } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
... | revalidateReason,
},
})
})
}
describe('app router ISR', () => {
it('should capture correct reason for stale errored page', async () => {
await next.fetch('/app/stale')
await waitFor(2 * 1000) // wait for revalida | (
errorMessage: string,
revalidateReason: string
) {
await retry(async () => {
const json = await getOutputLogJson(next, outputLogPath)
expect(json[errorMessage]).toMatchObject({
context: {
| {
"filepath": "test/e2e/on-request-error/isr/isr.test.ts",
"language": "typescript",
"file_size": 2850,
"cut_index": 563,
"middle_length": 229
} |
retry } from 'next-test-utils'
import { getOutputLogJson } from '../_testing/utils'
describe('on-request-error - server-action-error', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
const outputLogPath = 'output-log.json'
... | g(errorMessage)])
)
// TODO: remove custom duration in case we increase the default.
}, 5000)
const json = await getOutputLogJson(next, outputLogPath)
const record = json[errorMessage]
// Assert error is recorded in the output |
const recordLogLines = next.cliOutput
.split('\n')
.filter((log) => log.includes('[instrumentation] write-log'))
expect(recordLogLines).toEqual(
expect.arrayContaining([expect.stringContainin | {
"filepath": "test/e2e/on-request-error/server-action-error/server-action-error.test.ts",
"language": "typescript",
"file_size": 2867,
"cut_index": 563,
"middle_length": 229
} |
from 'e2e-utils'
import { fetchViaHTTP, renderViaHTTP } from 'next-test-utils'
import path from 'path'
import fs from 'fs-extra'
const locales = ['', '/en', '/sv', '/nl']
describe('i18n-ignore-rewrite-source-locale with basepath', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeplo... |
async (locale) => {
const res = await renderViaHTTP(
next.url,
`/basepath${locale}/rewrite-api/hello`
)
expect(res).toContain('hello from api')
}
)
// build artifacts aren't available on deploy
if (!(global | rViaHTTP(
next.url,
`/basepath${locale}/rewrite-files/file.txt`
)
expect(res).toContain('hello from file.txt')
}
)
test.each(locales)(
'call api by skipping locale in rewrite, locale: %s', | {
"filepath": "test/e2e/i18n-ignore-rewrite-source-locale/rewrites-with-basepath.test.ts",
"language": "typescript",
"file_size": 1828,
"cut_index": 537,
"middle_length": 229
} |
th'
const dir = path.join(path.dirname(new URL(import.meta.url).pathname), '../..')
const logPath = path.join(dir, 'output-log.json')
export async function POST(req) {
let payloadString = ''
const decoder = new TextDecoder()
const reader = req.clone().body.getReader()
while (true) {
const { done, value } ... | : {}
if (!json[payload.message]) {
json[payload.message] = {
payload,
count: 1,
}
} else {
json[payload.message].count++
}
await fsp.writeFile(logPath, JSON.stringify(json, null, 2), 'utf8')
console.log(`[instrumentat | ? JSON.parse(await fsp.readFile(logPath, 'utf8'))
| {
"filepath": "test/e2e/on-request-error/otel/app/write-log/route.js",
"language": "javascript",
"file_size": 973,
"cut_index": 582,
"middle_length": 52
} |
t() {
return next.cliOutput.slice(previousOutputIndex)
}
describe('When rendering from a Server Component', () => {
describe('Rendering <Link> directly', () => {
it('warns if the child is a synchronous server component', async () => {
const browser = await next.browser(
'/validation... | tag.",
"environmentLabel": "Prerender",
"label": "Console Error",
"source": "app/validations/rsc-that-renders-link/synchronous/page.tsx (7:7) @ Page
> 7 | <Link href="/about" legacyBehavior>
| "description": "Using a Server Component as a direct child of \`<Link legacyBehavior>\` is not supported. If you need legacyBehavior, wrap your Server Component in a Client Component that renders the Link's \`<a>\` | {
"filepath": "test/e2e/legacy-link-behavior/validations.console.test.ts",
"language": "typescript",
"file_size": 16096,
"cut_index": 921,
"middle_length": 229
} |
Image from 'next/image'
import img1 from '../public/animated2.png'
import img2 from '../public/äöüščří.png'
import img3 from '../public/test.avif'
import img4 from '../public/test.jpg'
import img5 from '../public/test.webp'
import img6 from '../public/animated.gif'
import img7 from '../public/grayscale.png'
import im... | img1} />
<Image src={img2} />
<Image src={img3} />
<Image src={img4} />
<Image src={img5} />
<Image src={img6} />
<Image src={img7} />
<Image src={img8} />
<Image src={img9} />
<Image src={img11} />
|
import img14 from '../public/test.svg'
import img15 from '../public/animated.webp'
import img17 from '../public/test.ico'
export default function Home() {
return (
<>
<h1>Image Optimizer Home</h1>
<Image src={ | {
"filepath": "test/e2e/image-optimizer/app/pages/index.js",
"language": "javascript",
"file_size": 1161,
"cut_index": 518,
"middle_length": 229
} |
import { nextTestSetup } from 'e2e-utils'
describe('hello-world', () => {
const { next } = nextTestSetup({
files: __dirname,
})
// Recommended for tests that check HTML. Cheerio is a HTML parser that has a jQuery like API.
it('should work using cheerio', async () => {
const $ = await next.render$('/')... | nder('/')
expect(html).toContain('hello world')
})
// In case you need to test the response object
it('should work with fetch', async () => {
const res = await next.fetch('/')
const html = await res.text()
expect(html).toContain('hel | '/')
expect(await browser.elementByCss('p').text()).toBe('hello world')
})
// In case you need the full HTML. Can also use $.html() with cheerio.
it('should work with html', async () => {
const html = await next.re | {
"filepath": "test/e2e/hello-world/hello-world.test.ts",
"language": "typescript",
"file_size": 1016,
"cut_index": 512,
"middle_length": 229
} |
/* eslint-env jest */
import { createClientRouterFilter } from 'next/dist/lib/create-client-router-filter'
import { BloomFilter } from 'next/dist/shared/lib/bloom-filter'
describe('createClientRouterFilter', () => {
it('creates a filter that does not collide with wildly different path names', () => {
const { sta... | lter.numItems,
dynamicFilter.errorRate
)
dynamicFilterInstance.import(dynamicFilter)
expect(
staticFilterInstance.contains(
'/all-hardcovers/no-one-can-know-1511?category=current-features'
)
).toBe(false)
})
})
| )
const staticFilterInstance = new BloomFilter(
staticFilter.numItems,
staticFilter.errorRate
)
staticFilterInstance.import(staticFilter)
const dynamicFilterInstance = new BloomFilter(
dynamicFi | {
"filepath": "test/unit/create-client-router-filter.test.ts",
"language": "typescript",
"file_size": 997,
"cut_index": 512,
"middle_length": 229
} |
v jest */
import { findConfig } from 'next/dist/lib/find-config'
import { join } from 'path'
const fixtureDir = join(__dirname, 'fixtures')
describe('find config', () => {
it('should resolve rc.json', async () => {
const config = await findConfig(join(fixtureDir, 'config-json'), 'test')
expect(config).toEqu... | s', async () => {
const config = await findConfig(join(fixtureDir, 'config-long-js'), 'test')
expect(config).toEqual({ foo: 'bar' })
})
it('should resolve .config.cjs', async () => {
const config = await findConfig(join(fixtureDir, 'config | it('should resolve .config.json', async () => {
const config = await findConfig(
join(fixtureDir, 'config-long-json'),
'test'
)
expect(config).toEqual({ foo: 'bar' })
})
it('should resolve .config.j | {
"filepath": "test/unit/find-config.test.ts",
"language": "typescript",
"file_size": 1484,
"cut_index": 524,
"middle_length": 229
} |
find-page-file'
import { normalizePagePath } from 'next/dist/shared/lib/page-path/normalize-page-path'
import { join } from 'path'
const resolveDataDir = join(__dirname, 'isolated', '_resolvedata')
const dirWithPages = join(resolveDataDir, 'readdir', 'pages')
describe('findPageFile', () => {
it('should work', async... | ['jsx', 'js'],
false
)
expect(result).toMatch(/^[\\/]nested[\\/]index\.js/)
})
it('should prefer prefered.js before preferred/index.js', async () => {
const pagePath = normalizePagePath('/prefered')
const result = await findPage | t).toMatch(/^[\\/]nav[\\/]about\.js/)
})
it('should work with nested index.js', async () => {
const pagePath = normalizePagePath('/nested')
const result = await findPageFile(
dirWithPages,
pagePath,
| {
"filepath": "test/unit/find-page-file.test.ts",
"language": "typescript",
"file_size": 3282,
"cut_index": 614,
"middle_length": 229
} |
v jest */
import { getFilesInDir } from 'next/dist/lib/get-files-in-dir'
import { join } from 'path'
import fs from 'fs-extra'
const testDir = join(__dirname, 'get-files-in-dir-test')
const srcDir = join(testDir, 'src')
const setupTestDir = async () => {
const paths = [
'.hidden',
'file',
'folder1/fil... | join(srcDir, 'file'), join(srcDir, 'link'))
await fs.ensureSymlink(join(srcDir, 'link'), join(srcDir, 'link-level-2'))
await fs.ensureSymlink(
join(srcDir, 'link-level-2'),
join(srcDir, 'link-level-3')
)
await fs.ensureSymlink(join(srcDir, | '.hidden'), 'hidden')
await fs.outputFile(join(srcDir, 'file'), 'file')
await fs.outputFile(join(srcDir, 'folder1', 'file1'), 'file1')
await fs.outputFile(join(srcDir, 'folder1', 'file2'), 'file2')
await fs.ensureSymlink( | {
"filepath": "test/unit/get-files-in-dir.test.ts",
"language": "typescript",
"file_size": 1486,
"cut_index": 524,
"middle_length": 229
} |
nv jest */
import { Component } from 'react'
import { getDisplayName } from 'next/dist/shared/lib/utils'
describe('getDisplayName', () => {
it('gets the proper display name of a component', () => {
class ComponentOne extends Component {
render() {
return null
}
}
class ComponentTwo e... | expect(getDisplayName(ComponentTwo)).toBe('CustomDisplayName')
expect(getDisplayName(FunctionalComponent)).toBe('FunctionalComponent')
expect(getDisplayName(() => null)).toBe('Unknown')
expect(getDisplayName('div' as any)).toBe('div')
})
}) | etDisplayName(ComponentOne)).toBe('ComponentOne')
| {
"filepath": "test/unit/getDisplayName.test.ts",
"language": "typescript",
"file_size": 832,
"cut_index": 523,
"middle_length": 52
} |
These tests are based on https://github.com/zertosh/htmlescape/blob/3e6cf0614dd0f778fd0131e69070b77282150c15/test/htmlescape-test.js
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
import { htmlEscapeJsonString } from 'next/dist/shared/lib/htmlescape'
import vm fr... | apeJsonString(JSON.stringify(evilObj)))
).toMatchObject(evilObj)
})
test('with ampersands should escape', () => {
const evilObj = { evil: '&' }
expect(htmlEscapeJsonString(JSON.stringify(evilObj))).toBe(
'{"evil":"\\u0026"}'
)
| lObj))).toBe(
'{"evil":"\\u003cscript\\u003e\\u003c/script\\u003e"}'
)
})
test('with angle brackets should parse back', () => {
const evilObj = { evil: '<script></script>' }
expect(
JSON.parse(htmlEsc | {
"filepath": "test/unit/htmlescape.test.ts",
"language": "typescript",
"file_size": 1938,
"cut_index": 537,
"middle_length": 229
} |
v jest */
import { ImageResponse } from 'next/og'
import React from 'react'
describe('new ImageResponse()', () => {
const exactHeader = 'public, max-age=3600, s-maxage=3600'
it('should merge object literal headers correctly', () => {
const res = new ImageResponse(
React.createElement(
'div',
... |
React.createElement(
'div',
{ style: { width: 10, height: 10 } },
'ImageResponse'
),
{
width: 10,
height: 10,
headers: new Headers({
'Cache-Control': exactHeader,
}),
| }
)
expect(res.headers.get('Content-Type')).toBeTruthy()
expect(res.headers.get('Cache-Control')).toBe(exactHeader)
})
it('should merge Headers instance correctly', () => {
const res = new ImageResponse( | {
"filepath": "test/unit/image-response-header.test.ts",
"language": "typescript",
"file_size": 1484,
"cut_index": 524,
"middle_length": 229
} |
erverSidePropsType,
GetServerSidePropsContext,
} from 'next'
import { expectTypeOf } from 'expect-type'
describe('InferGetServerSidePropsType', () => {
it('should work with sync functions', async () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function getServerSideProps(context: GetS... | isable-next-line @typescript-eslint/no-unused-vars
async function getServerSideProps(context: GetServerSidePropsContext) {
if (context.params?.notFound) {
return {
notFound: true,
}
}
if (context.params?.red | }
}
type PageProps = InferGetServerSidePropsType<typeof getServerSideProps>
expectTypeOf<PageProps>().toEqualTypeOf<{ foo: string }>()
})
it('should work with async functions', async () => {
// eslint-d | {
"filepath": "test/unit/infer-get-server-side-props-type.test.ts",
"language": "typescript",
"file_size": 1765,
"cut_index": 537,
"middle_length": 229
} |
{ InferGetStaticPropsType, GetStaticPropsContext } from 'next'
import { expectTypeOf } from 'expect-type'
describe('InferGetServerSidePropsType', () => {
it('should work with sync functions', async () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function getStaticProps(context: GetStati... | @typescript-eslint/no-unused-vars
async function getStaticProps(context: GetStaticPropsContext) {
if (context.params?.notFound) {
return {
notFound: true,
}
}
if (context.params?.redirect) {
return | }
type PageProps = InferGetStaticPropsType<typeof getStaticProps>
expectTypeOf<PageProps>().toEqualTypeOf<{ foo: string }>()
})
it('should work with async functions', async () => {
// eslint-disable-next-line | {
"filepath": "test/unit/infer-get-static-props.test.ts",
"language": "typescript",
"file_size": 1315,
"cut_index": 524,
"middle_length": 229
} |
t/dist/server/config'
import { PHASE_PRODUCTION_SERVER } from 'next/constants'
// `loadConfig` caches its result keyed on `dir` + a boolean "hasCustomConfig".
// Each test uses a unique subdirectory so the cache doesn't bleed between
// cases. The subdirectory doesn't need to exist — only the string matters
// for the... | onLevel normalization', () => {
it('defaults to manual-warning when the instantInsights config is absent', async () => {
const config = await loadConfig(
PHASE_PRODUCTION_SERVER,
uniqueDir('absent'),
{
customConfig: {},
| ep in loadConfig: resolving
// `experimental.instantInsights.validationLevel` to a concrete value in
// one place so consumers don't each need to know the current framework default.
describe('experimental.instantInsights validati | {
"filepath": "test/unit/instant-config-normalization.test.ts",
"language": "typescript",
"file_size": 2086,
"cut_index": 563,
"middle_length": 229
} |
jsdom
*/
/* eslint-env jest */
import { isEqualNode } from 'next/dist/client/head-manager'
const createScriptElement = (attrs = {}) => {
const el = document.createElement('script')
for (const k in attrs) el.setAttribute(k, attrs[k])
return el
}
describe('isEqualNode', () => {
it('should equal itself', () => ... | t el1 = createScriptElement({ nonce: 'abc123' })
// Simulate Chrome/FF browser behavior of stripping off nonce value when adding element to the document
el1.setAttribute('nonce', '')
el1.nonce = 'abc123'
const el2 = createScriptElement({ no | const el2 = createScriptElement()
expect(isEqualNode(el1, el2)).toBe(true)
})
it('should equal equivalent node that has same nonce property, even if the original node has no html nonce attribute value', () => {
cons | {
"filepath": "test/unit/is-equal-node.unit.test.ts",
"language": "typescript",
"file_size": 1719,
"cut_index": 537,
"middle_length": 229
} |
test: \`{ props: { ... } }\` (received: \`[object Null]\`)."
`)
expect(() => isSerializableProps('/', 'test', undefined))
.toThrowErrorMatchingInlineSnapshot(`
"Error serializing props returned from \`test\` in "/".
Reason: Props must be returned as a plain object from test: \`{ props: { ... ... | ableProps('/', 'test', class Foobar {}))
.toThrowErrorMatchingInlineSnapshot(`
"Error serializing props returned from \`test\` in "/".
Reason: Props must be returned as a plain object from test: \`{ props: { ... } }\` (received: \`[object | napshot(`
"Error serializing props returned from \`test\` in "/".
Reason: Props must be returned as a plain object from test: \`{ props: { ... } }\` (received: \`[object Array]\`)."
`)
expect(() => isSerializ | {
"filepath": "test/unit/is-serializable-props.test.ts",
"language": "typescript",
"file_size": 10936,
"cut_index": 921,
"middle_length": 229
} |
st-environment jsdom
*/
import { act, render } from '@testing-library/react'
import '@testing-library/jest-dom'
import Link from 'next/link'
import React from 'react'
describe('<Link/>', () => {
let spy
let expectedErrors
beforeAll(async () => {
spy = jest.spyOn(console, 'error').mockImplementation((...args... | })
expect(spy).toHaveBeenCalledTimes(expectedErrors)
})
it('test link without unmount', () => {
act(() => {
render(<Link href="/">hello</Link>)
})
expect(spy).toHaveBeenCalledTimes(expectedErrors)
})
afterAll(() => {
| unmount()
| {
"filepath": "test/unit/link-warnings.test.tsx",
"language": "tsx",
"file_size": 819,
"cut_index": 522,
"middle_length": 14
} |
ort { loadGetInitialProps } from 'next/dist/shared/lib/utils'
describe('loadGetInitialProps', () => {
it('should throw if getInitialProps is defined as an instance method', () => {
class TestComponent {
getInitialProps() {}
}
const rejectPromise = loadGetInitialProps(TestComponent as any, {})
c... | })
expect(result).toEqual({})
})
it('should resolve getInitialProps', async () => {
class TestComponent {
static async getInitialProps() {
return { foo: 1 }
}
}
const result = await loadGetInitialProps(TestComponent | rmation.'
)
return expect(rejectPromise).rejects.toEqual(error)
})
it('should resolve to an empty object if getInitialProps is missing', async () => {
const result = await loadGetInitialProps((() => {}) as any, { | {
"filepath": "test/unit/loadGetInitialProps.test.ts",
"language": "typescript",
"file_size": 1895,
"cut_index": 537,
"middle_length": 229
} |
vedMetadata properties can be assigned to
* Metadata input types. This is important because users often want to
* extend parent metadata in generateMetadata:
*
* ```ts
* export async function generateMetadata(_, parent: ResolvingMetadata) {
* const resolved = await parent
* return {
* openGraph: {
* ... | esolvedOpenGraphUrl = NonNullable<ResolvedMetadata['openGraph']>['url']
type MetadataOpenGraphUrl = NonNullable<Metadata['openGraph']>['url']
type ResolvedTwitterSite = NonNullable<ResolvedMetadata['twitter']>['site']
type MetadataTwitterSite = NonNullabl | * that are not assignable to Metadata (e.g., `null` vs `undefined` mismatch).
*/
import type { Metadata, ResolvedMetadata } from 'next'
import { expectTypeOf } from 'expect-type'
// Extract property types for comparison
type R | {
"filepath": "test/unit/metadata-types-compatibility.test.ts",
"language": "typescript",
"file_size": 4087,
"cut_index": 614,
"middle_length": 229
} |
ort mitt from 'next/dist/shared/lib/mitt'
describe('mitt', () => {
describe('With listeners', () => {
it('should listen to an event', () => {
return new Promise((resolve) => {
const ev = mitt()
ev.on('sample', resolve)
ev.emit('sample')
})
})
it('should listen to mult... | cb)
ev.on('sample2', cb)
ev.emit('sample1', 'one')
ev.emit('sample2', 'two')
expect(data).toEqual(['one', 'two'])
})
it('should support multiple arguments', () => {
const ev = mitt()
let data
ev.on('sa | it('sample')
expect(cnt).toBe(2)
})
it('should listen to multiple events', () => {
const ev = mitt()
const data = []
const cb = (name) => {
data.push(name)
}
ev.on('sample1', | {
"filepath": "test/unit/mitt.test.ts",
"language": "typescript",
"file_size": 1638,
"cut_index": 537,
"middle_length": 229
} |
e'
import loader from 'next/dist/build/babel/loader'
const dir = path.resolve(os.tmpdir())
const babel = async (code: string, queryOpts = {} as any) => {
const { isServer = false, resourcePath = `index.js` } = queryOpts
let isAsync = false
const options = {
// loader opts
cwd: dir,
isServer,
d... | ))
}
}
const res = loader.bind({
resourcePath,
async() {
isAsync = true
return callback
},
callback,
emitWarning() {},
query: options,
getOptions: function () {
return options | !isServer,
transformMode: 'default',
}
return new Promise<string>((resolve, reject) => {
function callback(err, content) {
if (err) {
reject(err)
} else {
resolve(content.replace(/\n/g, '' | {
"filepath": "test/unit/next-babel-loader-dev.test.ts",
"language": "typescript",
"file_size": 3147,
"cut_index": 614,
"middle_length": 229
} |
tion callback(err, content) {
if (err) {
reject(err)
} else {
resolve(content.replace(/\n/g, ''))
}
}
const options = {
// loader opts
cwd: dir,
isServer,
distDir: path.resolve(dir, '.next'),
pagesDir:
'pagesDir' in queryOpts
? q... | w Span({ name: 'test' }),
})(code, null)
if (!isAsync) {
resolve(res)
}
})
}
describe('next-babel-loader', () => {
describe('replace constants', () => {
it('should replace typeof window expression nested', async () => {
co | ath,
async() {
isAsync = true
return callback
},
callback,
emitWarning() {},
query: options,
getOptions: function () {
return options
},
currentTraceSpan: ne | {
"filepath": "test/unit/next-babel-loader-prod.test.ts",
"language": "typescript",
"file_size": 12397,
"cut_index": 921,
"middle_length": 229
} |
) =>
transformSync(code, {
filename,
presets: [[require('next/dist/build/babel/preset'), presetOptions]],
babelrc: false,
configFile: false,
sourceType: 'module',
compact: true,
caller: {
name: 'tests',
supportsStaticESM: esm,
isDev: false,
},
} as any).code
descri... | reateElement`)
// it should use that factory for all JSX:
expect(output).toMatch(`__jsx("a",{href:"/"`)
expect(
babel(`const a = ()=><a href="/">home</a>`, true)
).toMatchInlineSnapshot(
`"import React from"react";v | ">home</a>;`, true)
// it should add a React import:
expect(output).toMatch(`import React from"react"`)
// it should hoist JSX factory to a module level variable:
expect(output).toMatch(`var __jsx=React.c | {
"filepath": "test/unit/next-babel.test.ts",
"language": "typescript",
"file_size": 6421,
"cut_index": 716,
"middle_length": 229
} |
', '/_next/image?url=%2Ftest.png&w=256&q=75'],
])
})
it('should have correct type for props', async () => {
const { props } = getImageProps({
alt: 'a nice desc',
id: 'my-image',
src: '/test.png',
width: 100,
height: 200,
})
expect(props.alt).toBeString()
expect(pr... | alt: 'a nice desc',
id: 'my-image',
src: '/test.png',
width: 100,
height: 200,
preload: true,
})
expect(warningMessages).toStrictEqual([])
expect(Object.entries(props)).toStrictEqual([
['alt', 'a nice desc | s.style).toBeObject()
expect(props.style.color).toBeString()
expect(props.src).toBeString()
expect(props.srcSet).toBeString()
})
it('should handle preload', async () => {
const { props } = getImageProps({
| {
"filepath": "test/unit/next-image-get-img-props.test.ts",
"language": "typescript",
"file_size": 34766,
"cut_index": 2151,
"middle_length": 229
} |
'next/dist/shared/lib/deployment-id.js', () => {
return {
__esModule: true,
getDeploymentId() {
return deploymentId
},
getDeploymentIdQuery(ampersand = false): string {
let id = deploymentId
if (id) {
return `${ampersand ? '&' : '?'}dpl=${id}`
}
return ''
},
... | ,
height: 100,
loading: 'eager',
})
const html = ReactDOM.renderToString(element)
const $ = cheerio.load(html)
const img = $('#unit-image')
expect(img.attr('id')).toBe('unit-image')
expect(img.attr('src')).toContain('tes | d ")
},
}
})
describe('Image Legacy Rendering', () => {
it('should render Image on its own', async () => {
const element = React.createElement(Image, {
id: 'unit-image',
src: '/test.png',
width: 100 | {
"filepath": "test/unit/next-image-legacy.test.ts",
"language": "typescript",
"file_size": 7213,
"cut_index": 716,
"middle_length": 229
} |
ort ReactDOMServer from 'react-dom/server'
import Image from 'next/image'
import cheerio from 'cheerio'
describe('Image rendering', () => {
it('should render Image on its own', async () => {
const element = React.createElement(Image, {
alt: 'a nice image',
id: 'unit-image',
src: '/test.png',
... | style: 'color:transparent',
srcset:
'/_next/image?url=%2Ftest.png&w=128&q=75 1x, /_next/image?url=%2Ftest.png&w=256&q=75 2x',
src: '/_next/image?url=%2Ftest.png&w=256&q=75',
})
})
it('should only render noscript element when | // order matters here
expect(img.attr()).toStrictEqual({
alt: 'a nice image',
id: 'unit-image',
loading: 'eager',
width: '100',
height: '100',
decoding: 'async',
'data-nimg': '1',
| {
"filepath": "test/unit/next-image-new.test.ts",
"language": "typescript",
"file_size": 2966,
"cut_index": 563,
"middle_length": 229
} |
c = async (code) => {
let output = await transform(code)
return output.code
}
const trim = (s) => s.join('\n').trim().replace(/^\s+/gm, '')
describe('next/swc', () => {
beforeAll(async () => {
await installBindings()
})
describe('hook_optimizer', () => {
it('should leave alone array destructuring of... | return arr2;
}
function _array_with_holes(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterable_to_array_limit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" | ut).toMatchInlineSnapshot(`
"function _array_like_to_array(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
| {
"filepath": "test/unit/next-swc.test.ts",
"language": "typescript",
"file_size": 5436,
"cut_index": 716,
"middle_length": 229
} |
/* eslint-env jest */
import { getOxfordCommaList } from 'next/dist/lib/oxford-comma-list'
describe('oxford-comma-list', () => {
test('empty array', () => {
expect(getOxfordCommaList([])).toMatchInlineSnapshot(`""`)
})
test('single item array', () => {
expect(getOxfordCommaList(['apples'])).toMatchInlin... | pect(getOxfordCommaList(['1', '2', '3', '4'])).toMatchInlineSnapshot(
`"1, 2, 3, and 4"`
)
})
test('five item array', () => {
expect(getOxfordCommaList(['1', '2', '3', '4', '5'])).toMatchInlineSnapshot(
`"1, 2, 3, 4, and 5"`
)
| est('three item array', () => {
expect(
getOxfordCommaList(['apples', 'strawberries', 'blueberries'])
).toMatchInlineSnapshot(`"apples, strawberries, and blueberries"`)
})
test('four item array', () => {
ex | {
"filepath": "test/unit/oxford-comma.test.ts",
"language": "typescript",
"file_size": 1005,
"cut_index": 512,
"middle_length": 229
} |
outes(['/posts'])).toEqual(['/posts'])
expect(getSortedRoutes(['/posts/[id]'])).toEqual(['/posts/[id]'])
expect(getSortedRoutes(['/posts/[id]/foo'])).toEqual(['/posts/[id]/foo'])
expect(getSortedRoutes(['/posts/[id]/[foo]/bar'])).toEqual([
'/posts/[id]/[foo]/bar',
])
expect(getSortedRoutes([... | [...rest]',
'/p2/[...rest]',
'/p2/[id]',
'/p2/[id]/abc',
'/p3/[[...rest]]',
'/p3/[id]',
'/p3/[id]/abc',
'/blog/[id]',
'/foo/[d]/bar/baz/[f]',
'/apples/[ab]/[cd]/ef',
])
).toM | '/[root-slug]',
'/',
'/posts/[id]',
'/blog/[id]/comments/[cid]',
'/blog/abc/[id]',
'/[...rest]',
'/blog/abc/post',
'/blog/abc',
'/p1/[[...incl]]',
'/p/ | {
"filepath": "test/unit/page-route-sorter.test.ts",
"language": "typescript",
"file_size": 6849,
"cut_index": 716,
"middle_length": 229
} |
uild/analysis/get-page-static-info'
import { installBindings } from 'next/dist/build/swc/install-bindings'
import { PAGE_TYPES } from 'next/dist/lib/page-types'
import { join } from 'path'
const fixtureDir = join(__dirname, 'fixtures')
function createNextConfig() {
return {}
}
describe('parse page static info', ()... | })
expect(runtime).toBe('nodejs')
expect(getServerSideProps).toBe(true)
expect(getStaticProps).toBe(false)
})
it('should parse static runtime correctly', async () => {
const { runtime, getServerSideProps, getStaticProps } =
aw | wait getPagesPageStaticInfo({
page: 'nodejs-ssr',
pageFilePath: join(fixtureDir, 'page-runtime/nodejs-ssr.js'),
nextConfig: createNextConfig(),
pageType: PAGE_TYPES.PAGES,
isDev: false,
| {
"filepath": "test/unit/parse-page-static-info.test.ts",
"language": "typescript",
"file_size": 2582,
"cut_index": 563,
"middle_length": 229
} |
ve-url'
// convenience function so tests can be aligned neatly
// and easy to eyeball
const check = (windowUrl, targetUrl, expected) => {
window.location = new URL(windowUrl) as any
if (typeof expected === 'string') {
expect(() => parseRelativeUrl(targetUrl)).toThrow(expected)
} else {
const parsedUrl = ... | 'http://example.com:3210/someA/pathB?fooC=barD#hashE',
'/someF/pathG?fooH=barI#hashJ',
{
pathname: '/someF/pathG',
search: '?fooH=barI',
hash: '#hashJ',
}
)
})
it('should parse relative url when star | ribe('parseRelativeUrl', () => {
beforeAll(() => {
;(global as any).window = {
location: {},
}
})
afterAll(() => {
delete (global as any).window
})
it('should parse relative url', () => {
check(
| {
"filepath": "test/unit/parse-relative-url.test.ts",
"language": "typescript",
"file_size": 3319,
"cut_index": 614,
"middle_length": 229
} |
m 'next/dist/lib/recursive-copy'
import { join } from 'path'
import fs from 'fs-extra'
import { readFileSync } from 'fs'
const testDir = join(__dirname, 'recursive-folder-test')
const srcDir = join(testDir, 'src')
const destDir = join(testDir, 'dest')
const setupTestDir = async (numFiles = 100) => {
const paths = ... | 'file2'), 'file2')
await fs.ensureSymlink(join(srcDir, 'file'), join(srcDir, 'link'))
await fs.ensureSymlink(join(srcDir, 'folder1'), join(srcDir, 'linkfolder'))
for (let i = 0; i < numFiles - 6; i++) {
const path = join(`folder-${i}`, `file-${ | r(srcDir)
await fs.outputFile(join(srcDir, '.hidden'), 'hidden')
await fs.outputFile(join(srcDir, 'file'), 'file')
await fs.outputFile(join(srcDir, 'folder1', 'file1'), 'file1')
await fs.outputFile(join(srcDir, 'folder1', | {
"filepath": "test/unit/recursive-copy.test.ts",
"language": "typescript",
"file_size": 2977,
"cut_index": 563,
"middle_length": 229
} |
ort {
recursiveDeleteSyncWithAsyncRetries,
calcBackoffMs,
} from 'next/dist/lib/recursive-delete'
import { recursiveReadDir } from 'next/dist/lib/recursive-readdir'
import { recursiveCopy } from 'next/dist/lib/recursive-copy'
import { join } from 'path'
const resolveDataDir = join(__dirname, 'isolated', '_resolved... | eCopy(resolveDataDir, testResolveDataDir)
await fs.symlink('./aa', join(testResolveDataDir, 'symlink'))
await recursiveDeleteSyncWithAsyncRetries(testResolveDataDir)
const result = await recursiveReadDir(testResolveDataDir)
expect(r | cRetries', () => {
if (process.platform === 'win32') {
it('should skip on windows to avoid symlink issues', () => {})
return
}
it('should work', async () => {
expect.assertions(1)
try {
await recursiv | {
"filepath": "test/unit/recursive-delete.test.ts",
"language": "typescript",
"file_size": 2037,
"cut_index": 563,
"middle_length": 229
} |
rt { join } from 'path'
const resolveDataDir = join(__dirname, 'isolated', '_resolvedata')
const dirWithPages = join(resolveDataDir, 'readdir', 'pages')
describe('recursiveReadDir', () => {
it('should work', async () => {
const result = await recursiveReadDir(dirWithPages, {
pathnameFilter: (f) => /\.js/.... | v[\\/]products[\\/]product\.js/,
]
expect(
result.filter((item) => {
for (const page of pages) {
if (page.test(item)) {
return false
}
}
return true
}).length
).toBe(0)
})
} | /^[\\/]prefered[\\/]index\.js/,
/^[\\/]na | {
"filepath": "test/unit/recursive-readdir.test.ts",
"language": "typescript",
"file_size": 916,
"cut_index": 606,
"middle_length": 52
} |
ver/web/utils'
import cookie from 'next/dist/compiled/cookie'
function generateCookies(
...cookieOptions: (CookieSerializeOptions & { name: string; value: string })[]
) {
const cookies = cookieOptions.map((opts) =>
cookie.serialize(opts.name, opts.value, opts)
)
return {
joined: cookies.join(', '),
... | ed } = generateCookies({
name: 'foo',
value: 'bar',
expires: new Date(),
})
const result = splitCookiesString(joined)
expect(result).toEqual(expected)
})
it('should parse max-age', () => {
const { jo | erateCookies({
name: 'foo',
value: 'bar',
})
const result = splitCookiesString(joined)
expect(result).toEqual(expected)
})
it('should parse expires', () => {
const { joined, expect | {
"filepath": "test/unit/split-cookies-string.test.ts",
"language": "typescript",
"file_size": 4296,
"cut_index": 614,
"middle_length": 229
} |
d/swc/options'
describe('swcEnvOptions', () => {
const baseArgs = {
filename: '/app/page.tsx',
development: false,
isServer: false,
pagesDir: '/pages',
appDir: '/app',
isPageFile: false,
hasReactRefresh: false,
modularizeImports: undefined,
swcPlugins: undefined,
compilerOptio... | Browsers: ['chrome 80'],
})
expect(options.env).toEqual({ targets: ['chrome 80'] })
})
it('should include mode and coreJs when configured', () => {
const options = getLoaderSWCOptions({
...baseArgs,
supportedBrowsers: ['chrome | er: undefined,
cacheHandlers: undefined,
configDir: '/',
}
it('should not include extra env options when swcEnvOptions is not set', () => {
const options = getLoaderSWCOptions({
...baseArgs,
supported | {
"filepath": "test/unit/swc-auto-polyfill-options.test.ts",
"language": "typescript",
"file_size": 2898,
"cut_index": 563,
"middle_length": 229
} |
import { nextTestSetup } from 'e2e-utils'
describe('next-image-legacy-src-with-query-without-local-patterns', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
it('should throw error for relative ... | liOutput } = await next.build()
expect(cliOutput).toContain(
'Image with src "/test.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpa | 'Image with src "/test.png?v=1" is using a query string which is not configured in images.localPatterns.\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns'
)
} else {
const { c | {
"filepath": "test/e2e/next-image-legacy-src-with-query-without-local-patterns/next-image-legacy-src-with-query-without-local-patterns.test.ts",
"language": "typescript",
"file_size": 1027,
"cut_index": 512,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.