prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
tion getUnsupportedModuleWarning(name: string) { return `A Node.js module is loaded ('${name}'` } function escapeLF(s: string) { return s.replace(/\n/g, '\\n') } function expectUnsupportedModuleProdError(moduleName: string, output: string) { const moduleNotSupportedMessage = getUnsupportedModule(moduleName) e...
2e (isolated app). // TODO: Uncomment once codeframe is verified to point to user code // expect(stripAnsi(output)).toContain(importStatement) const moduleNotSupportedMessage = getUnsupportedModule(moduleName) expect(responseText).toContain(escape
rtedModuleDevError( moduleName: string, _importStatement: string, responseText: string, output: string ) { expectUnsupportedModuleProdError(moduleName, output) // Codeframe should now include the import statement in e
{ "filepath": "test/e2e/edge-runtime-module-errors/edge-runtime-module-errors.test.ts", "language": "typescript", "file_size": 33739, "cut_index": 1331, "middle_length": 229 }
ith src folder', appDir: 'app-with-src', shouldLog: false, }, { name: 'App Router', appDir: 'app-router', shouldLog: true, }, { name: 'Pages Router', appDir: 'pages-router', shouldLog: false, }, ])('$name', ({ name, appDir, shouldLog }) => { desc...
ationTime = await browser.eval(`window.__NEXT_HYDRATED_AT`) expect(instrumentationTime).toBeDefined() expect(hydrationTime).toBeDefined() expect(instrumentationTime).toBeLessThan(hydrationTime) expect( (await brow
ase()} before hydration`, async () => { const browser = await next.browser('/') const instrumentationTime = await browser.eval( `window.__INSTRUMENTATION_CLIENT_EXECUTED_AT` ) const hydr
{ "filepath": "test/e2e/instrumentation-client-hook/instrumentation-client-hook.test.ts", "language": "typescript", "file_size": 6810, "cut_index": 716, "middle_length": 229 }
'path' describe('cache-handlers-upstream-wiring', () => { describe('pages router non-edge', () => { const { next, skipped, isNextDev } = nextTestSetup({ files: join(__dirname, 'fixtures/pages-router-non-edge'), skipDeployment: true, }) if (skipped) { return } let outputIndex ...
atus).toBe(200) expect(await revalidateResponse.json()).toEqual({ revalidated: true }) if (!isNextDev) { await retry(async () => { const htmlAfterRevalidate = await next.render$('/isr') const valueAfterRevalidate =
= await next.render$('/isr') const initialValue = initialHtml('#now').text() outputIndex = next.cliOutput.length const revalidateResponse = await next.fetch('/api/revalidate') expect(revalidateResponse.st
{ "filepath": "test/e2e/cache-handlers-upstream-wiring/index.test.ts", "language": "typescript", "file_size": 4356, "cut_index": 614, "middle_length": 229 }
etup } from 'e2e-utils' describe('transpile packages', () => { if ((global as any).isNextDeploy) { it('should skip for deploy mode for now', () => {}) return } const { next } = nextTestSetup({ files: new FileRef(path.join(__dirname, './npm')), dependencies: { sass: 'latest', }, }) ...
uld handle global css imports inside transpiled modules', async () => { const browser = await next.browser('/global-css') expect( await browser.eval( `window.getComputedStyle(document.querySelector('body')).backgroundColor`
it.skip('should handle optional peer dependencies', async () => { const browser = await next.browser('/peer-deps') expect(await browser.elementByCss('h1').text()).toBe('world') }) describe('css', () => { it('sho
{ "filepath": "test/e2e/transpile-packages/index.test.ts", "language": "typescript", "file_size": 2518, "cut_index": 563, "middle_length": 229 }
('Link with legacyBehavior', () => { const { next, isNextDev } = nextTestSetup({ files: __dirname, }) describe('if the child is an <a> tag', () => { it('forwards the href attribute', async () => { const $ = await next.render$('/') const $a = $('a') expect($a.text()).toBe('About') ...
await browser.elementByCss('a').click() const title = await browser.elementByCss('h1').text() expect(title).toBe('About Page') }) it('works if the child is a string', async () => { const browser = await next.browser('/child-is-a-string
nst title = await browser.elementByCss('#about-page').text() expect(title).toBe('About Page') }) }) it('works if the child is a number', async () => { const browser = await next.browser('/child-is-a-number')
{ "filepath": "test/e2e/legacy-link-behavior-pages/index.test.ts", "language": "typescript", "file_size": 2458, "cut_index": 563, "middle_length": 229 }
retry } from 'next-test-utils' import stripAnsi from 'strip-ansi' const strictRouteTypes = process.env.__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES === 'true' describe('tsconfig module: preserve', () => { const { next, skipped } = nextTestSetup({ files: { 'tsconfig.json': JSON.stringify({ compilerOpti...
dule when using "module: preserve"', async () => { let output = '' await retry(() => { output = stripAnsi(next.cliOutput) expect(output).toContain( 'The following mandatory changes were made to your tsconfig.json' ) }
kipped because it relies on `next.readFile` skipDeployment: true, dependencies: { typescript: '5.4.4', }, }) if (skipped) return it('allows you to skip moduleResolution, esModuleInterop and resolveJsonMo
{ "filepath": "test/e2e/tsconfig-module-preserve/index.test.ts", "language": "typescript", "file_size": 2716, "cut_index": 563, "middle_length": 229 }
from 'path' import os from 'os' import { throwTurbopackInternalError, TurbopackInternalError, } from 'next/dist/shared/lib/turbopack/internal-error' import { Telemetry } from 'next/dist/telemetry/storage' import { setGlobal } from 'next/dist/trace' import { traceGlobals } from 'next/dist/trace/shared' describe('Tu...
'submitRecord') // @ts-ignore .mockImplementation(() => Promise.resolve()) let internalError = null try { throwTurbopackInternalError(null, { message: 'test error', anonymizedLocation: 'file.rs:120:
const distDir = path.join(os.tmpdir(), 'next-telemetry') const telemetry = new Telemetry({ distDir }) setGlobal('telemetry', telemetry) const submitRecord = jest // @ts-ignore .spyOn(telemetry,
{ "filepath": "test/unit/TurbopackInternalError.test.ts", "language": "typescript", "file_size": 1437, "cut_index": 524, "middle_length": 229 }
cept-header' describe('acceptLanguage', () => { it('parses the header', () => { const language = acceptLanguage('da, en-GB, en') expect(language).toEqual('da') }) it('respects weights', () => { const language = acceptLanguage('en;q=0.6, en-GB;q=0.8') expect(language).toEqual('en-gb') }) it(...
it('returns empty string if none of the preferences match', () => { const language = acceptLanguage('da, en-GB, en', ['es']) expect(language).toEqual('') }) it('returns first preference if header has * and is unmatched', () => { const lang
const language = acceptLanguage() expect(language).toEqual('') }) it('ignores an empty preferences array', () => { const language = acceptLanguage('da, en-GB, en', []) expect(language).toEqual('da') })
{ "filepath": "test/unit/accept-headers.test.ts", "language": "typescript", "file_size": 2722, "cut_index": 563, "middle_length": 229 }
t { warnOnce } from 'next/dist/build/output/log' describe('build/output/log', () => { it('warnOnce', () => { const original = console.warn try { const messages = [] console.warn = (m: any) => messages.push(m) warnOnce('test') expect(messages.length).toEqual(1) warnOnce('test aga...
in') expect(messages.length).toEqual(3) warnOnce('test', 'more') expect(messages.length).toEqual(3) warnOnce('test', 'should', 'add', 'another') expect(messages.length).toEqual(4) } finally { console.warn = original
Once('test aga
{ "filepath": "test/unit/build-output-log.test.ts", "language": "typescript", "file_size": 801, "cut_index": 517, "middle_length": 14 }
tSetup } from 'e2e-utils' import { renderViaHTTP } from 'next-test-utils' import cheerio from 'cheerio' import { join } from 'path' describe('next/head', () => { const { next } = nextTestSetup({ files: { pages: new FileRef(join(__dirname, 'app/pages')), components: new FileRef(join(__dirname, 'app/co...
a name="test-head-1" content="hello" data-next-head="">` ) }) it('should have correct head tags in initial document', async () => { const html = await renderViaHTTP(next.url, '/') const $ = cheerio.load(html) for (let i = 1; i < 5; i+
const head = document.querySelector('head') return head.innerHTML }) expect(html).toContain( `<meta charset="utf-8" data-next-head=""><meta name="viewport" content="width=device-width" data-next-head=""><met
{ "filepath": "test/e2e/next-head/index.test.ts", "language": "typescript", "file_size": 1941, "cut_index": 537, "middle_length": 229 }
ts = { onBuildComplete({ outputs }) { const pagesDataPathnames = outputs.pages .map((item) => item.pathname) .filter((item) => item.startsWith('/_next/data/')) const appPagesDataPathnames = outputs.appPages .map((item) => item.pathname) .filter((item) => item.startsWith('/_next/data/')...
if (!hasIndexData || !hasDynamicData || hasDoubleIndexData) { throw new Error( [ 'Unexpected edge pages data output from adapter build:', `pagesDataPathnames=${JSON.stringify(pagesDataPathnames)}`, `appPagesDat
\/_next\/data\/[^/]+\/\[id\]\.json$/.test(item) ) const hasDoubleIndexData = [ ...pagesDataPathnames, ...appPagesDataPathnames, ].some((item) => /^\/_next\/data\/[^/]+\/index\/index\.json$/.test(item))
{ "filepath": "test/e2e/edge-pages-support/app/my-adapter.js", "language": "javascript", "file_size": 1431, "cut_index": 524, "middle_length": 229 }
iction policy. * When the cache exceeds maxEntries, the least recently used entries are evicted. */ const MAX_IMAGE_ENTRIES = parseInt( process.env.MAX_IMAGE_CACHE_ENTRIES || '2', 10 ) class LRUCache { constructor(maxEntries) { this.maxEntries = maxEntries this.cache = new Map() } get(key) { ...
is.cache.size >= this.maxEntries) { const oldestKey = this.cache.keys().next().value console.log('cache-handler evicting', oldestKey) this.cache.delete(oldestKey) } this.cache.set(key, value) } has(key) { return this.cach
return value } set(key, value) { // If key exists, delete it first (will be re-added at end) if (this.cache.has(key)) { this.cache.delete(key) } // Evict oldest entries if at capacity while (th
{ "filepath": "test/e2e/custom-cache-handler-image/cache-handler.js", "language": "javascript", "file_size": 2461, "cut_index": 563, "middle_length": 229 }
fetchViaHTTP } from 'next-test-utils' describe('Middleware fetches with any HTTP method', () => { const { next } = nextTestSetup({ files: { 'pages/api/ping.js': ` export default (req, res) => { res.send(JSON.stringify({ method: req.method, headers: {...req.headers}...
l: HTTP_ECHO_URL, method: req.method}); const json = await response.text() const res = NextResponse.next(); res.headers.set('x-resolved', json ?? '{}'); return res } const handlers = { 'ne
ho-headers'; export default async (req) => { const kind = req.nextUrl.searchParams.get('kind') const handler = handlers[kind] ?? handlers['normal-fetch']; const response = await handler({ur
{ "filepath": "test/e2e/middleware-fetches-with-any-http-method/index.test.ts", "language": "typescript", "file_size": 2346, "cut_index": 563, "middle_length": 229 }
ort { nextTestSetup } from 'e2e-utils' describe('Async modules', () => { const { next, isNextDev: dev } = nextTestSetup({ files: __dirname, }) it('ssr async page modules', async () => { const $ = await next.render$('/') expect($('#app-value').text()).toBe('hello') expect($('#page-value').text())...
pi/hello') expect(res.status).toBe(200) const result = await res.json() expect(result).toHaveProperty('value', 42) }) it('works with getServerSideProps', async () => { const browser = await next.browser('/gssp') expect(await browse
await browser.elementByCss('#page-value').text()).toBe('42') expect(await browser.elementByCss('#doc-value').text()).toBe('doc value') }) it('works on async api routes', async () => { const res = await next.fetch('/a
{ "filepath": "test/e2e/async-modules/index.test.ts", "language": "typescript", "file_size": 1727, "cut_index": 537, "middle_length": 229 }
eslint-disable no-undef */ import { ClientValue, ClientExpr, ClientNumber, ClientBoolean, } from './client-component' export default function Page() { return ( <ul> <li> Server value:{' '} {typeof MY_MAGIC_VARIABLE === 'string' ? MY_MAGIC_VARIABLE : 'not set'} </li> <li>...
'} </li> <li> Client number: <ClientNumber /> </li> <li> Server boolean:{' '} {typeof MY_BOOLEAN_VARIABLE === 'boolean' ? String(MY_BOOLEAN_VARIABLE) : 'not set'} </li> <li>
'not set'} </li> <li> Client expr: <ClientExpr /> </li> <li> Server number:{' '} {typeof MY_NUMBER_VARIABLE === 'number' ? String(MY_NUMBER_VARIABLE) : 'not set
{ "filepath": "test/e2e/define/app/page.js", "language": "javascript", "file_size": 1068, "cut_index": 515, "middle_length": 229 }
from 'e2e-utils' import { retry } from 'next-test-utils' describe('socket-io', () => { const { next } = nextTestSetup({ files: __dirname, dependencies: { 'socket.io': '4.7.2', 'socket.io-client': '4.7.2', 'utf-8-validate': '6.0.3', bufferutil: '4.0.8', }, // the socket.io setu...
}, }) await Promise.all([ retry(async () => expect(await browser1.elementByCss('#status').text()).toBe('Connected') ), retry(async () => expect(await browser2.elementByCss('#status').text()).toBe('Connected
c () => { let requestsCount = 0 const browser1 = await next.browser('/') const browser2 = await next.browser('/', { beforePageLoad(page) { page.on('request', () => { requestsCount++ })
{ "filepath": "test/e2e/socket-io/index.test.ts", "language": "typescript", "file_size": 1687, "cut_index": 537, "middle_length": 229 }
// @ts-check const defaultCacheHandler = require('next/dist/server/lib/cache-handlers/default.external').default /** * @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler} */ const cacheHandler = { async get(cacheKey, softTags) { console.log('WiringModernCacheHandler::get', cacheKey, sof...
CacheHandler::getExpiration', JSON.stringify(tags)) return Infinity }, async updateTags(tags) { console.log('WiringModernCacheHandler::updateTags', JSON.stringify(tags)) return defaultCacheHandler.updateTags(tags) }, } module.exports =
ler.set(cacheKey, pendingEntry) }, async refreshTags() { console.log('WiringModernCacheHandler::refreshTags') return defaultCacheHandler.refreshTags() }, async getExpiration(tags) { console.log('WiringModern
{ "filepath": "test/e2e/cache-handlers-upstream-wiring/fixtures/non-edge-cache-components/modern-cache-handler.js", "language": "javascript", "file_size": 1010, "cut_index": 512, "middle_length": 229 }
etry } from 'next-test-utils' function makeIndexPage(runtime: string) { return `import ReactDOM from 'react-dom' import Image from 'next/image' export default function Index() { if (typeof window !== 'undefined') { window.didHydrate = true } console.log('__render__') return ( <div> <p id="reac...
it('should only render once in SSR', async () => { await next.render('/') expect([...next.cliOutput.matchAll(/__render__/g)].length).toBe(1) }) it('no warnings for image related link props', async () => { await next.render(
rt const config = { runtime: ${JSON.stringify(runtime)} } ` } describe('react-current-version', () => { describe('Basics', () => { const { next, isTurbopack } = nextTestSetup({ files: join(__dirname, 'app'), })
{ "filepath": "test/e2e/react-current-version/react-current-version.test.ts", "language": "typescript", "file_size": 4500, "cut_index": 614, "middle_length": 229 }
'/hello/world') const $ = cheerio.load(html) expect($('#route').text()).toBe('top level route param: [hello|world]') }) it('should render catch-all top-level route with single segment', async () => { const html = await next.render('/hello') const $ = cheerio.load(html) expect($('#route').text()...
const $ = cheerio.load(html) expect($('#route').text()).toBe('nested route param: [hello|world]') }) it('should render catch-all nested route with single segment', async () => { const html = await next.render('/nested/hello') const $ = che
(html) expect($('#route').text()).toBe('top level route param: undefined') }) it('should render catch-all nested route with multiple segments', async () => { const html = await next.render('/nested/hello/world')
{ "filepath": "test/e2e/dynamic-optional-routing/dynamic-optional-routing.test.ts", "language": "typescript", "file_size": 10246, "cut_index": 921, "middle_length": 229 }
tTestSetup, FileRef } from 'e2e-utils' import { join } from 'path' // x-ref: https://github.com/vercel/next.js/issues/45189 describe('edge render - custom _document with edge runtime', () => { const { next } = nextTestSetup({ files: { 'pages/index.js': new FileRef( join(__dirname, 'app', 'pages', '...
{ render() { return ( <Html> <Head /> <body> <Main /> <NextScript /> </body> </Html> ) } }
pter.js': new FileRef(join(__dirname, 'app', 'my-adapter.js')), 'pages/_document.js': ` import Document, { Html, Head, Main, NextScript } from 'next/document' export default class MyDocument extends Document
{ "filepath": "test/e2e/edge-pages-support/edge-document.test.ts", "language": "typescript", "file_size": 1255, "cut_index": 524, "middle_length": 229 }
eerio from 'cheerio' describe('fallback: false rewrite', () => { const { next, skipped } = nextTestSetup({ files: __dirname, // Assertions don't apply to deploy mode (output differs vs. local Next.js server). skipDeployment: true, }) if (skipped) return it('should rewrite correctly for path at sam...
async () => { const res = await next.fetch('/hello/world', { redirect: 'manual' }) expect(res.status).toBe(200) const html = await res.text() const $ = cheerio.load(html) expect($('#another').text()).toBe('another') expect(JSON.p
$ = cheerio.load(html) expect($('#another').text()).toBe('another') expect(JSON.parse($('#query').text())).toEqual({ path: ['hello'], }) }) it('should rewrite correctly for path above fallback: false SSR',
{ "filepath": "test/e2e/fallback-false-rewrite/fallback-false-rewrite.test.ts", "language": "typescript", "file_size": 2895, "cut_index": 563, "middle_length": 229 }
('compiler.define', () => { const { next } = nextTestSetup({ files: __dirname, }) describe('compiler.define', () => { let loadedText beforeEach(async () => { let browser = await next.browser('/') loadedText = await browser.elementByCss('body').text() }) it('should render the magi...
de', async () => { expect(loadedText).toContain('Server expr: barbaz') expect(loadedText).toContain('Client expr: barbaz') }) it('should render the magic expression on client side', async () => { expect(loadedText).toContain('Ser
e magic variable on client side', async () => { expect(loadedText).toContain('Server value: foobar') expect(loadedText).toContain('Client value: foobar') }) it('should render the magic expression on server si
{ "filepath": "test/e2e/define/define.test.ts", "language": "typescript", "file_size": 2359, "cut_index": 563, "middle_length": 229 }
{ nextTestSetup } from 'e2e-utils' describe('rewrites has condition', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should navigate to a simple rewrite without error', async () => { const browser = await next.browser('/') await browser.eval('window.beforeNav = 1') await bro...
('/') await browser.eval('window.beforeNav = 1') await browser .elementByCss('#to-has-rewrite') .click() .waitForElementByCss('#another') expect(await browser.elementByCss('#pathname').text()).toBe('/another') expect(JSON
wait browser.elementByCss('#query').text())).toEqual({}) expect(await browser.eval('window.beforeNav')).toBe(1) }) it('should navigate to a has rewrite without error', async () => { const browser = await next.browser
{ "filepath": "test/e2e/rewrites-has-condition/rewrites-has-condition.test.ts", "language": "typescript", "file_size": 1164, "cut_index": 518, "middle_length": 229 }
t cheerio from 'cheerio' describe('Fallback Dynamic Route Params', () => { const { next } = nextTestSetup({ files: __dirname, }) it('should have correct fallback query (skeleton)', async () => { const html = await next.render('/first') const $ = cheerio.load(html) const { query } = JSON.parse($(...
).initialSlug) expect(initialSlug).toBeFalsy() await browser.waitForElementByCss('#query') const hydratedQuery = JSON.parse( await browser.elementByCss('#query').text() ) expect(hydratedQuery).toEqual({ slug: 'second' }) }) })
nitialSlug = await browser.eval(() => (window as any
{ "filepath": "test/e2e/fallback-route-params/fallback-route-params.test.ts", "language": "typescript", "file_size": 868, "cut_index": 559, "middle_length": 52 }
de, esm = true, pluginOptions = {}) => transform(code, { filename: 'noop.js', presets: [['@babel/preset-react', { development: false, pragma: '__jsx' }]], plugins: [[plugin, pluginOptions]], babelrc: false, configFile: false, sourceType: 'module', compact: true, caller: { name: '...
`) expect(output).toMatchInlineSnapshot( `"export var __N_SSG=true;export default function Test(){return __jsx("div",null);}"` ) }) it('should remove combined named export specifiers', () => { const output = babel(t
export specifiers', () => { const output = babel(trim` export { getStaticPaths } from '.' export { a as getStaticProps } from '.' export default function Test() { return <div /> }
{ "filepath": "test/unit/babel-plugin-next-ssg-transform.test.ts", "language": "typescript", "file_size": 14915, "cut_index": 921, "middle_length": 229 }
che-handler-image', () => { const { next, skipped } = nextTestSetup({ files: __dirname, skipDeployment: true, env: { // Set max cache entries to 2 to easily test eviction MAX_IMAGE_CACHE_ENTRIES: '2', }, }) if (skipped) { return } it('should use custom cache handler for image...
// Verify cache handler was called for the image await retry(() => { expect(next.cliOutput).toContain('initialized custom cache-handler') expect(next.cliOutput).toContain('cache-handler set') expect(next.cliOutput).toMatch(/kind:.*
('#image-small').attr('src') expect(smallImgSrc).toContain('/_next/image') // Fetch the optimized image to trigger cache handler const imageRes = await next.fetch(smallImgSrc) expect(imageRes.status).toBe(200)
{ "filepath": "test/e2e/custom-cache-handler-image/custom-cache-handler-image.test.ts", "language": "typescript", "file_size": 3380, "cut_index": 614, "middle_length": 229 }
t-env jest */ import { transformSync } from '@babel/core' const babel = (code) => transformSync(code, { filename: 'page.tsx', presets: ['@babel/preset-typescript'], plugins: [require('next/dist/build/babel/plugins/next-page-config')], babelrc: false, configFile: false, sourceType: 'module', ...
nfig: PageConfig = {};') expect(output).toMatch(`export const config={};`) }) test('export config with AsExpression', () => { const output = babel('export const config = {} as PageConfig;') expect(output).toMatch('export const config={};
', () => { const output = babel('export const co
{ "filepath": "test/unit/babel-plugin-next-page-config.test.ts", "language": "typescript", "file_size": 839, "cut_index": 520, "middle_length": 52 }
e client' import { useEffect, useState } from 'react' import io from 'socket.io-client' let socket export default function Home() { const [connected, setConnected] = useState(false) const [value, setValue] = useState('') const socketInitializer = async () => { // We call this just to make sure we turn on ...
turn } const value = e.target.value setValue(value) socket.emit('createdMessage', value) } useEffect(() => { socketInitializer().then(() => { setConnected(true) }) }, []) return ( <> <span id="status">{con
socket.id) }) socket.on('newIncomingMessage', (msg) => { setValue(msg) }) } const sendMessageHandler = async (e) => { if (!socket) { console.error('No socket connection yet for message') re
{ "filepath": "test/e2e/socket-io/app/page.js", "language": "javascript", "file_size": 1120, "cut_index": 515, "middle_length": 229 }
ring-regexp' import fs from 'fs-extra' describe('edge-render-getserversideprops', () => { const { next } = nextTestSetup({ files: join(__dirname, 'app'), }) if ((global as any).isNextStart) { // Turbopack doesn't have entry chunks for edge routes like Webpack does, so there is no fixed // known path...
) ).toBe(true) expect( await fs.pathExists( join(next.testDir, '.next/server/pages/[id].js.nft.json') ) ).toBe(false) expect( await fs.pathExists(join(next.testDir, '.next/server/pag
le jest/no-standalone-expect */ expect(await fs.pathExists(join(next.testDir, '.next/pages'))).toBe( false ) expect( await fs.pathExists(join(next.testDir, '.next/server/pages/[id].js')
{ "filepath": "test/e2e/edge-pages-support/index.test.ts", "language": "typescript", "file_size": 5876, "cut_index": 716, "middle_length": 229 }
m 'eslint' import { rules } from '@next/eslint-plugin-next' const NextESLintRule = rules['no-title-in-document-head'] const tests = { valid: [ `import Head from "next/head"; class Test { render() { return ( <Head> <title>My page title</title> </Head> )...
return ( <Head> <title>My page title</title> </Head> ); } }`, errors: [ { message: 'Do not use `<title>` element with `<Head />` component from `next/d
</Head> </Html> ); } } export default MyDocument; `, ], invalid: [ { code: ` import { Head } from "next/document"; class Test { render() {
{ "filepath": "test/unit/eslint-plugin-next/no-title-in-document-head.test.ts", "language": "typescript", "file_size": 1552, "cut_index": 537, "middle_length": 229 }
erver/web/spec-extension/response' it('reflect .set into `set-cookie`', async () => { const response = new NextResponse() expect(response.cookies.get('foo')?.value).toBe(undefined) expect(response.cookies.get('foo')).toEqual(undefined) response.cookies .set('foo', 'bar', { path: '/test' }) .set('fooz'...
'foo=bar; Path=/test, fooz=barz; Path=/test2' ) expect( Array.from(response.headers.entries()).filter((entry) => { return entry[0] === 'set-cookie' }) ).toEqual([ ['set-cookie', 'foo=bar; Path=/test'], ['set-cookie', 'fooz=barz
l({ name: 'foo', path: '/test', value: 'bar', }) expect(response.cookies.get('fooz')).toEqual({ name: 'fooz', path: '/test2', value: 'barz', }) expect(response.headers.get('set-cookie')).toBe(
{ "filepath": "test/unit/web-runtime/next-response-cookies.test.ts", "language": "typescript", "file_size": 3278, "cut_index": 614, "middle_length": 229 }
eslint-env jest */ import { getBlurImage } from 'next/dist/build/webpack/loaders/next-image-loader/blur' import { readFile } from 'fs-extra' import { join } from 'path' const getImage = (filepath) => readFile(join(__dirname, filepath)) const tracing = () => ({ traceFn: (fn, ...args) => fn(...args), traceAsyncFn: ...
URL).toBeString() }) it('should return undefined for animated webp', async () => { const buffer = await getImage('./images/animated.webp') const result = await getBlurImage( buffer, 'webp', { width: 400, height: 400 }, c
const buffer = await getImage('./images/test.jpg') const result = await getBlurImage( buffer, 'jpeg', { width: 400, height: 400 }, context ) expect(result).toBeObject() expect(result.data
{ "filepath": "test/unit/next-image-loader/get-blur-image.test.ts", "language": "typescript", "file_size": 1096, "cut_index": 515, "middle_length": 229 }
@edge-runtime/jest-environment */ import { expectTypeOf } from 'expect-type' import { NextRequest } from 'next/dist/server/web/spec-extension/request' it('should have 1 required parameter for constructor', () => { expect(NextRequest.length).toBe(1) }) it('should allow the 2nd parameter to be undefined', () => { ...
omEntries(nextRequest.headers)).toEqual( Object.fromEntries(request.headers) ) // Second argument should override headers const headers = new Headers({ 'x-header': 'some header' }) const nextRequest2 = new NextRequest(request, { headers })
me', '/' ) }) it('should clone Request with headers', () => { const request = new Request('https://example.com', { headers: { 'x-foo': 'bar' }, }) const nextRequest = new NextRequest(request) expect(Object.fr
{ "filepath": "test/unit/web-runtime/next-request.test.ts", "language": "typescript", "file_size": 1679, "cut_index": 537, "middle_length": 229 }
lterModuleRules', () => { it('should filter module rules correctly', async () => { const input = { module: { rules: [{ test: 'babel-loader' }, { test: /.*\.css/ }] }, } const expected = [{ test: 'babel-loader' }] const output = storybookPlugin.filterModuleRules(input) expect(output).toEqual...
rules: [ { use: [ 'next/dist/compiled/@next/react-refresh-utils/dist/loader', 'rr', ], }, ], }, } const expected = { module: { rules: [
pected = { module: { rules: [{ use: 'a' }] } } attachReactRefresh(input, 'rr') expect(input).toEqual(expected) }) it('should skip adding when existing (shorthand)', () => { const input = { module: {
{ "filepath": "test/unit/webpack-config-overrides.test.ts", "language": "typescript", "file_size": 6235, "cut_index": 716, "middle_length": 229 }
ndexOfUint8Array, isEquivalentUint8Arrays, removeFromUint8Array, } from 'next/dist/server/stream-utils/uint8array-helpers' describe('uint8array-helpers', () => { it('finds the start index of a nested sequence', () => { const haystack = new Uint8Array([1, 2, 3, 4, 5, 6]) const needle = new Uint8Array([3, ...
(indexOfUint8Array(haystack, needle)).toBe(-1) }) it('removes a matching sequence from the middle', () => { const haystack = new Uint8Array([10, 20, 30, 40, 50]) const needle = new Uint8Array([30, 40]) const result = removeFromUint8Array(
new Uint8Array([7, 6]) expect(indexOfUint8Array(haystack, needle)).toBe(2) }) it('returns -1 when not found', () => { const haystack = new Uint8Array([1, 2, 3, 4]) const needle = new Uint8Array([4, 5]) expect
{ "filepath": "test/unit/stream-utils/uint8array-helpers.test.ts", "language": "typescript", "file_size": 1358, "cut_index": 524, "middle_length": 229 }
} from 'next/constants' import { normalizePagePath } from 'next/dist/shared/lib/page-path/normalize-page-path' import { requirePage, getPagePath } from 'next/dist/server/require' import { PageNotFoundError } from 'next/dist/shared/lib/utils' const sep = '/' const distDir = join(__dirname, '_resolvedata') const pathTo...
> { expect(normalizePagePath('/')).toBe(`${sep}index`) }) it('Should turn _error into /_error', () => { expect(normalizePagePath('_error')).toBe(`${sep}_error`) }) it('Should turn /abc into /abc', () => { expect(normalizePagePath('/ab
{ expect.assertions(1) try { throw new PageNotFoundError('test') } catch (err) { expect(err.code).toBe('ENOENT') } }) }) describe('normalizePagePath', () => { it('Should turn / into /index', () =
{ "filepath": "test/unit/isolated/require-page.test.ts", "language": "typescript", "file_size": 3221, "cut_index": 614, "middle_length": 229 }
m 'eslint' import { rules } from '@next/eslint-plugin-next' const NextESLintRule = rules['google-font-preconnect'] const tests = { valid: [ `export const Test = () => ( <div> <link rel="preconnect" href="https://fonts.gstatic.com"/> <link href={process.env.NEXT_PUBLIC_CAN...
ssage: '`rel="preconnect"` is missing from Google Font. See: https://nextjs.org/docs/messages/google-font-preconnect', type: 'JSXOpeningElement', }, ], }, { code: ` export const Test = () => (
</div> ) `, ], invalid: [ { code: ` export const Test = () => ( <div> <link href="https://fonts.gstatic.com"/> </div> ) `, errors: [ { me
{ "filepath": "test/unit/eslint-plugin-next/google-font-preconnect.test.ts", "language": "typescript", "file_size": 1668, "cut_index": 537, "middle_length": 229 }
Rule = rules['inline-script-id'] const errorMessage = '`next/script` components with inline content must specify an `id` attribute. See: https://nextjs.org/docs/messages/inline-script-id' const tests = { valid: [ { code: `import Script from 'next/script'; export default function TestPage() { ...
/> ) }`, }, { code: `import Script from 'next/script'; export default function TestPage() { return ( <Script src="https://example.com" /> ) }`, }, { code: `import MyScript fro
'; export default function TestPage() { return ( <Script id="test-script" dangerouslySetInnerHTML={{ __html: \`console.log('Hello world');\` }}
{ "filepath": "test/unit/eslint-plugin-next/inline-script-id.test.ts", "language": "typescript", "file_size": 4326, "cut_index": 614, "middle_length": 229 }
xtESLintRule = rules['no-assign-module-variable'] const tests = { valid: [ ` let myModule = {}; export default function MyComponent() { return <></> } `, ], invalid: [ { code: ` let module = {}; export default function MyComponent() { return <></>...
variable', () => { new RuleTester({ languageOptions: { ecmaVersion: 2018, sourceType: 'module', parserOptions: { ecmaFeatures: { modules: true, jsx: true, }, }, }, }).run('eslint', Nex
], }, ], } describe('no-assign-module-
{ "filepath": "test/unit/eslint-plugin-next/no-assign-module-variable.test.ts", "language": "typescript", "file_size": 937, "cut_index": 606, "middle_length": 52 }
} from '@next/eslint-plugin-next' const NextESLintRule = rules['no-async-client-component'] const message = 'Prevent Client Components from being async functions. See: https://nextjs.org/docs/messages/no-async-client-component' const tests = { valid: [ ` // single line export default async function M...
} export default myFunction `, ` // arrow function "use client" const myFunction = () => { return '' } export default myFunction `, ], invalid: [ { code: ` // single line "use client"
// multiple line async function MyComponent() { return <></> } export default MyComponent `, ` // multiple line capitalization "use client" async function myFunction() { return ''
{ "filepath": "test/unit/eslint-plugin-next/no-async-client-component.test.ts", "language": "typescript", "file_size": 2324, "cut_index": 563, "middle_length": 229 }
} from '@next/eslint-plugin-next' const NextESLintRule = rules['no-document-import-in-page'] const tests = { valid: [ { code: `import Document from "next/document" export default class MyDocument extends Document { render() { return ( <Html> </Html> ); ...
ds NDocument { render() { return ( <Html> </Html> ); } } `, filename: 'pages/_document/index.js', }, { code: `import NDocument from "next/document" export default class Docume
return ( <Html> </Html> ); } } `, filename: 'pages/_document.page.tsx', }, { code: `import NDocument from "next/document" export default class Document exten
{ "filepath": "test/unit/eslint-plugin-next/no-document-import-in-page.test.ts", "language": "typescript", "file_size": 2681, "cut_index": 563, "middle_length": 229 }
} from '@next/eslint-plugin-next' const NextESLintRule = rules['no-head-element'] const message = 'Do not use `<head>` element. Use `<Head />` from `next/head` instead. See: https://nextjs.org/docs/messages/no-head-element' const tests = { valid: [ { code: `import Head from 'next/head'; export c...
<title>My page title</title> </Head> </div> ); } } `, filename: 'pages/index.tsx', }, { code: ` export default function Layout({ children }) { return (
); } } `, filename: 'pages/index.js', }, { code: `import Head from 'next/head'; export class MyComponent { render() { return ( <div> <Head>
{ "filepath": "test/unit/eslint-plugin-next/no-head-element.test.ts", "language": "typescript", "file_size": 2488, "cut_index": 563, "middle_length": 229 }
ut-pages-dir') const withAppDir = path.join(__dirname, 'with-app-dir') const linters = { withoutPages: new Linter({ cwd: withoutPagesDir, configType: 'eslintrc', }), withApp: new Linter({ cwd: withAppDir, configType: 'eslintrc', }), withNestedPages: new Linter({ cwd: withNestedPagesDir, ...
es: { 'no-html-link-for-pages': [ 2, path.join(withCustomPagesDir, 'custom-pages'), ], }, } const linterConfigWithMultipleDirectories = { ...linterConfig, rules: { 'no-html-link-for-pages': [ 2, [ path.join
pages': [2], }, parserOptions: { ecmaVersion: 2018, sourceType: 'module', ecmaFeatures: { modules: true, jsx: true, }, }, } const linterConfigWithCustomDirectory: any = { ...linterConfig, rul
{ "filepath": "test/unit/eslint-plugin-next/no-html-link-for-pages.test.ts", "language": "typescript", "file_size": 13610, "cut_index": 921, "middle_length": 229 }
Rule = rules['no-location-assign-relative-destination'] const err = (expression: string) => ({ messageId: 'noLocationAssign', data: { expression }, }) describe('no-location-assign-relative-destination', () => { new RuleTester({ languageOptions: { ecmaVersion: 2018, sourceType: 'module', pa...
(with protocol) are allowed `location.href = 'https://example.com'`, `window.location.href = 'https://example.com/path'`, `globalThis.location.href = 'http://example.com'`, `location.assign('https://example.com')`, `window.lo
`const href = location.href`, `const url = window.location.href`, // location.replace is not covered by this rule `location.replace('/foo')`, `window.location.replace('/foo')`, // Absolute URLs
{ "filepath": "test/unit/eslint-plugin-next/no-location-assign-relative-destination.test.ts", "language": "typescript", "file_size": 3662, "cut_index": 614, "middle_length": 229 }
{ RuleTester } from 'eslint' import { rules } from '@next/eslint-plugin-next' const NextESLintRule = rules['no-script-component-in-head'] const message = '`next/script` should not be used in `next/head` component. Move `<Script />` outside of `<Head>` instead. See: https://nextjs.org/docs/messages/no-script-compon...
return ( <Head> <Script></Script> </Head> ); }`, filename: 'pages/index.js', errors: [{ message }], }, ], } describe('no-script-component-in-head', () => { new RuleTester({ langu
<Script></Script> </Head> ); } `, ], invalid: [ { code: ` import Head from "next/head"; import Script from "next/script"; export default function Index() {
{ "filepath": "test/unit/eslint-plugin-next/no-script-component-in-head.test.ts", "language": "typescript", "file_size": 1235, "cut_index": 518, "middle_length": 229 }
Rule = rules['no-styled-jsx-in-document'] const tests = { valid: [ { filename: 'pages/_document.js', code: `import Document, { Html, Head, Main, NextScript } from 'next/document' export class MyDocument extends Document { static async getInitialProps(ctx) { const initia...
t Document, { Html, Head, Main, NextScript } from 'next/document' export class MyDocument extends Document { static async getInitialProps(ctx) { const initialProps = await Document.getInitialProps(ctx) return { ..
<body> <Main /> <NextScript /> </body> </Html> ) } }`, }, { filename: 'pages/_document.js', code: `impor
{ "filepath": "test/unit/eslint-plugin-next/no-styled-jsx-in-document.test.ts", "language": "typescript", "file_size": 3311, "cut_index": 614, "middle_length": 229 }
Rule = rules['no-unwanted-polyfillio'] const tests = { valid: [ `import {Head} from 'next/document'; export class Blah extends Head { render() { return ( <div> <h1>Hello title</h1> <script src='https://polyfill.io/v3/polyfill.min.js?features=AbortC...
om 'next/script'; export function MyApp({ Component, pageProps }) { return ( <div> <Component {...pageProps} /> <Script src='https://polyfill.io/v3/polyfill.min.js?features=IntersectionObserver' />
<div> <h1>Hello title</h1> <script src='https://polyfill.io/v3/polyfill.min.js?features=IntersectionObserver'></script> </div> ); } }`, `import Script fr
{ "filepath": "test/unit/eslint-plugin-next/no-unwanted-polyfillio.test.ts", "language": "typescript", "file_size": 4378, "cut_index": 614, "middle_length": 229 }
the edge-runtime env setup // so that we test node runtime properly import { expectTypeOf } from 'expect-type' import { NextRequest } from 'next/dist/server/web/spec-extension/request' it('should have 1 required parameter for constructor', () => { expect(NextRequest.length).toBe(1) }) it('should allow the 2nd para...
uest(request) expect(Object.fromEntries(nextRequest.headers)).toEqual( Object.fromEntries(request.headers) ) // Second argument should override headers const headers = new Headers({ 'x-header': 'some header' }) const nextRequest2 = new Next
HaveProperty( 'nextUrl.pathname', '/' ) }) it('should clone Request with headers', () => { const request = new Request('https://example.com', { headers: { 'x-foo': 'bar' }, }) const nextRequest = new NextReq
{ "filepath": "test/unit/web-runtime/next-request-node.test.ts", "language": "typescript", "file_size": 1712, "cut_index": 537, "middle_length": 229 }
erver/config' import stripAnsi from 'strip-ansi' describe('warnOptionHasBeenMovedOutOfExperimental', () => { let spy: jest.SpyInstance beforeAll(() => { spy = jest.spyOn(console, 'warn').mockImplementation((...args) => { const [prefix, ...restArgs] = args const formattedFirstArg = stripAnsi(prefix)...
config.js', false ) warnOptionHasBeenMovedOutOfExperimental( { experimental: {}, }, 'skipTrailingSlashRedirect', 'skipTrailingSlashRedirect', 'next.config.js', false ) expect(spy).not.toHa
s]) }) }) it('should not log warning message without experimental config', () => { warnOptionHasBeenMovedOutOfExperimental( {}, 'skipTrailingSlashRedirect', 'skipTrailingSlashRedirect', 'next.
{ "filepath": "test/unit/warn-removed-experimental-config.test.ts", "language": "typescript", "file_size": 4188, "cut_index": 614, "middle_length": 229 }
Rule = rules['google-font-display'] const tests = { valid: [ `import Head from "next/head"; export default Test = () => { return ( <Head> <link href={test} rel="test" /> <link href={process.env.NEXT_PUBLIC_CANONICAL_URL} rel="canonical" />...
render() { return ( <Html> <Head> <link href="https://fonts.googleapis.com/css?family=Krona+One&display=swap" rel="stylesheet" /> </Head> <
com/css2?family=Krona+One&display=optional" rel="stylesheet" /> </Head> ); }; `, `import Document, { Html, Head } from "next/document"; class MyDocument extends Document {
{ "filepath": "test/unit/eslint-plugin-next/google-font-display.test.ts", "language": "typescript", "file_size": 4071, "cut_index": 614, "middle_length": 229 }
const ERROR_MSG_GOOGLE_ANALYTICS = `Prefer \`GoogleAnalytics\` component from \`@next/third-parties/google\` when using the inline script for Google Analytics. See: ${url}` const ERROR_MSG_GOOGLE_TAG_MANAGER = `Prefer \`GoogleTagManager\` component from \`@next/third-parties/google\` when using the inline script for Go...
-analytics"> {\` window.dataLayer = window.dataLayer || []; function gtag(){window.dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'GA_MEASUREMENT_I
<h1>Hello title</h1> <Script src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID" strategy="lazyOnload" /> <Script id="google
{ "filepath": "test/unit/eslint-plugin-next/next-script-for-ga.test.ts", "language": "typescript", "file_size": 6801, "cut_index": 716, "middle_length": 229 }
oreInteractive` strategy should not be used outside of `pages/_document.js`. See: https://nextjs.org/docs/messages/no-before-interactive-script-outside-document" const tests = { valid: [ { code: ` import Document, { Html, Main, NextScript } from 'next/document' import Script from 'next/script' ...
n.js?a=scriptBeforeInteractive" strategy="beforeInteractive" ></Script> </body> </Html> ) } } export default MyDocument `, filename: 'pages/_document.js'
<body> <Main /> <NextScript /> <Script id="scriptBeforeInteractive" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.mi
{ "filepath": "test/unit/eslint-plugin-next/no-before-interactive-script-outside-document.test.ts", "language": "typescript", "file_size": 8558, "cut_index": 716, "middle_length": 229 }
Rule = rules['no-head-import-in-document'] const tests = { valid: [ { code: `import Document, { Html, Head, Main, NextScript } from 'next/document' class MyDocument extends Document { static async getInitialProps(ctx) { //... } render() { return ( ...
width=device-width" /> </Head> ); } `, filename: 'pages/index.tsx', }, ], invalid: [ { code: ` import Document, { Html, Main, NextScript } from 'next/document' import Head from 'next/head'
{ code: `import Head from "next/head"; export default function IndexPage() { return ( <Head> <title>My page title</title> <meta name="viewport" content="initial-scale=1.0,
{ "filepath": "test/unit/eslint-plugin-next/no-head-import-in-document.test.ts", "language": "typescript", "file_size": 4412, "cut_index": 614, "middle_length": 229 }
Rule = rules['no-img-element'] const message = 'Using `<img>` could result in slower LCP and higher bandwidth. Consider using `<Image />` from `next/image` or a custom image loader to automatically optimize images. This may incur additional usage or cost from your provider. See: https://nextjs.org/docs/messages/no-i...
render() { return ( <picture> <img src="/test.png" alt="Test picture" width={500} height={500} /> </picture> );
src="/test.png" alt="Test picture" width={500} height={500} /> </div> ); } }`, `export class MyComponent {
{ "filepath": "test/unit/eslint-plugin-next/no-img-element.test.ts", "language": "typescript", "file_size": 3697, "cut_index": 614, "middle_length": 229 }
m 'eslint' import { rules } from '@next/eslint-plugin-next' const NextESLintRule = rules['no-sync-scripts'] const message = 'Synchronous scripts should not be used. See: https://nextjs.org/docs/messages/no-sync-scripts' const tests = { valid: [ `import {Head} from 'next/document'; export class Blah ex...
ps} ></script> </div> ); } }`, ], invalid: [ { code: ` import {Head} from 'next/document'; export class Blah extends Head { render() { return ( <div>
); } }`, `import {Head} from 'next/document'; export class Blah extends Head { render(props) { return ( <div> <h1>Hello title</h1> <script {...pro
{ "filepath": "test/unit/eslint-plugin-next/no-sync-scripts.test.ts", "language": "typescript", "file_size": 1914, "cut_index": 537, "middle_length": 229 }
Rule = rules['no-page-custom-font'] const filename = 'pages/_document.js' const tests = { valid: [ { code: `import Document, { Html, Head } from "next/document"; class MyDocument extends Document { render() { return ( <Html> <Head> <link ...
<Head> <link href="https://fonts.googleapis.com/css2?family=Krona+One&display=swap" rel="stylesheet" /> </Head> </Html> ); } } export default Documen
port default MyDocument;`, filename, }, { code: `import NextDocument, { Html, Head } from "next/document"; class Document extends NextDocument { render() { return ( <Html>
{ "filepath": "test/unit/eslint-plugin-next/no-page-custom-font.test.ts", "language": "typescript", "file_size": 4754, "cut_index": 614, "middle_length": 229 }
import glob from 'glob' import { nextTestSetup } from 'e2e-utils' import path from 'path' describe('terser-class-static-blocks', () => { const { next, isNextDeploy } = nextTestSetup({ files: __dirname, nextConfig: {}, }) it('should work using cheerio', async () => { const $ = await next.render$('/')...
await next.readFile(path.join('.next/static', chunk)) ).not.toContain('/*') expect( await next.readFile(path.join('.next/static', chunk)) ).not.toContain('My JSDoc comment that') }) ) }) } })
t/static') const chunks = glob.sync('**/*.js', { cwd: chunksDir, }) expect(chunks.length).toBeGreaterThan(0) await Promise.all( chunks.map(async (chunk) => { expect(
{ "filepath": "test/production/terser-class-static-blocks/terser-class-static-blocks.test.ts", "language": "typescript", "file_size": 997, "cut_index": 512, "middle_length": 229 }
('unstable-cache-foreground-revalidate', () => { const { next, isNextDev } = nextTestSetup({ files: __dirname, }) if (isNextDev) { it.skip('should not run in dev mode', () => {}) return } it('should block and wait for fresh data when ISR page revalidate time is greater than unstable_cache TTL', ...
evalidation to complete await new Promise((resolve) => setTimeout(resolve, 2000)) // Get logs since the initial render const logs = next.cliOutput.substring(initialLogLength) const cacheExecutions = [ ...logs.matchAll(/\[TEST\] unst
th ISR and unstable_cache to become stale await new Promise((resolve) => setTimeout(resolve, 11000)) // This request triggers ISR background revalidation await next.render('/isr-10') // Wait for ISR background r
{ "filepath": "test/production/app-dir/unstable-cache-foreground-revalidate/unstable-cache-foreground-revalidate.test.ts", "language": "typescript", "file_size": 2455, "cut_index": 563, "middle_length": 229 }
import { unstable_cache } from 'next/cache' export const revalidate = 10 const getCachedData = unstable_cache( async () => { const generatedAt = Date.now() // Log when this function is actually executed console.log('[TEST] unstable_cache callback executed at:', generatedAt) // Add a delay to simul...
age render completed with cache data from:', cachedData.generatedAt ) return ( <div> <div id="page-time">{pageRenderStart}</div> <div id="cache-generated-at">{cachedData.generatedAt}</div> <div id="random">{cachedData.random}
ate: 5, } ) export default async function Page() { const pageRenderStart = Date.now() console.log('[TEST] Page render started at:', pageRenderStart) const cachedData = await getCachedData() console.log( '[TEST] P
{ "filepath": "test/production/app-dir/unstable-cache-foreground-revalidate/app/isr-10/page.js", "language": "javascript", "file_size": 1021, "cut_index": 512, "middle_length": 229 }
findPort, initNextServerScript, killApp, retry } from 'next-test-utils' import path from 'node:path' import fs from 'fs-extra' import os from 'os' describe('app-dir action body finalize with nodejs middleware and output-standalone', () => { const { next } = nextTestSetup({ files: __dirname, skipStart: true, ...
ync finalize () { \nawait new Promise((resolve) => setTimeout(resolve, (Math.random() * 1000) + 1000));\n' ) } ) const distFolder = path.join(tmpFolder, 'test') await fs.move(path.join(next.testDir, '.next/standalone'), distFolde
Folder) await next.build() await next.patchFile( '.next/standalone/node_modules/next/dist/server/body-streams.js', (content) => { return content.replace( 'async finalize () {', 'as
{ "filepath": "test/production/app-dir/actions/app-action-body-finalize-output-standalone.test.ts", "language": "typescript", "file_size": 2316, "cut_index": 563, "middle_length": 229 }
from 'e2e-utils' ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)( 'next-types-plugin', () => { const { next, skipped } = nextTestSetup({ files: __dirname, }) if (skipped) return it('should have type for root page', async () => { expect(await next.hasFile('app/page.tsx')).to...
t(await next.hasFile('.next/types/app/nested/page.ts')).toBe(true) }) it('should have type for nested layout', async () => { expect(await next.hasFile('app/nested/layout.tsx')).toBe(true) expect(await next.hasFile('.next/types/app/neste
)).toBe(true) expect(await next.hasFile('.next/types/app/layout.ts')).toBe(true) }) it('should have type for nested page', async () => { expect(await next.hasFile('app/nested/page.tsx')).toBe(true) expec
{ "filepath": "test/production/app-dir/next-types-plugin/basic/index.test.ts", "language": "typescript", "file_size": 1515, "cut_index": 537, "middle_length": 229 }
{ nextTestSetup } from 'e2e-utils' const strictRouteTypes = process.env.__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES === 'true' // This next-types-plugin feature only works in webpack ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)( 'app-dir - sync-params-type-check', () => { const { next } = nextTes...
params }: { params: Params }) { return <p>slug:{params.slug}</p> } ` ) const { exitCode, cliOutput } = await next.build() expect(exitCode).toBe(1) expect(cliOutput).toMatch( strictRouteTypes ? /
e).toBe(0) }) it('should fail build with sync params', async () => { await next.patchFile( 'app/blog/[slug]/page.tsx', ` interface Params { slug: string } export default function Page({
{ "filepath": "test/production/app-dir/next-types-plugin/sync-params-type-check/sync-params-type-check.test.ts", "language": "typescript", "file_size": 1186, "cut_index": 518, "middle_length": 229 }
.env.IS_TURBOPACK_TEST ? describe.skip : describe)( 'next-types-plugin private-folder-convention', () => { const { next, skipped } = nextTestSetup({ files: __dirname, }) if (skipped) return it('should have type for root page', async () => { expect(await next.hasFile('app/page.tsx')).to...
t(await next.hasFile('.next/types/app/nested/page.ts')).toBe(true) }) it('should have type for nested layout', async () => { expect(await next.hasFile('app/nested/layout.tsx')).toBe(true) expect(await next.hasFile('.next/types/app/neste
)).toBe(true) expect(await next.hasFile('.next/types/app/layout.ts')).toBe(true) }) it('should have type for nested page', async () => { expect(await next.hasFile('app/nested/page.tsx')).toBe(true) expec
{ "filepath": "test/production/app-dir/next-types-plugin/private-folder-convention/index.test.ts", "language": "typescript", "file_size": 2116, "cut_index": 563, "middle_length": 229 }
@edge-runtime/jest-environment */ import { NextResponse } from 'next/dist/server/web/spec-extension/response' const toJSON = async (response: Response) => ({ body: await response.json(), contentType: response.headers.get('content-type'), status: response.status, }) it('automatically parses and formats JSON', ...
({ error: { code: 'bad_request' } }, { status: 400 }) ) ).toMatchObject({ contentType: 'application/json', body: { error: { code: 'bad_request' } }, status: 400, }) expect(await toJSON(NextResponse.json(null))).toMatchObject({ co
oJSON(NextResponse.json({ status: 'success' }, { status: 201 })) ).toMatchObject({ contentType: 'application/json', body: { status: 'success' }, status: 201, }) expect( await toJSON( NextResponse.json
{ "filepath": "test/unit/web-runtime/next-response.test.ts", "language": "typescript", "file_size": 1686, "cut_index": 537, "middle_length": 229 }
t css from '../noop-template' describe('basic test', () => { test('should minify css', async () => { const input = css` p { color: yellow; } ` const res = await postcss([mod()]).process(input, { from: 'input.css', to: 'output.css', }) expect(res.css).toBe('p{colo...
} @layer b; ` const res = await postcss([mod()]).process(input, { from: 'input.css', to: 'output.css', }) expect(res.css).toBe( '@layer b{._5-enzrfpb:lang(ar){font-family:myriad-arabic}}@layer b;' ) }) }
{ font-family: myriad-arabic; }
{ "filepath": "test/unit/cssnano-simple/cssnano-simple/basic.test.ts", "language": "typescript", "file_size": 916, "cut_index": 606, "middle_length": 52 }
css' import mod from 'next/dist/compiled/cssnano-simple/index' import css from '../noop-template' describe('exclude all test', () => { test('should not transform css', async () => { const input = css` p { /* test */ color: yellow; } ` const res = await postcss([mod({ exclude...
normalizeWhitespace: { exclude: false }, }), ]).process(input, { from: 'input.css', to: 'output.css', }) expect(res.css).toMatchInlineSnapshot(`"p{color:yellow}.empty{}"`) }) test('should enable rule with empty
const input = css` p { /* test */ color: yellow; } .empty { } ` const res = await postcss([ mod({ excludeAll: true, discardComments: { removeAll: true },
{ "filepath": "test/unit/cssnano-simple/cssnano-simple/exclude-all.test.ts", "language": "typescript", "file_size": 1511, "cut_index": 537, "middle_length": 229 }
ration', () => { const eslintConfigAfterSetupJSON = execSync( // Pass explicit absolute path to not get affected by the root eslint config. `pnpm eslint --config ${join(__dirname, 'eslint.config.mjs')} --print-config ${join(__dirname, 'test.js')}`, { cwd: __dirname, encoding: 'utf8...
ers': expect.any(Object), 'import/resolver': expect.any(Object), react: { version: 'detect', }, }, }) expect(getEslintConfigSnapshot(eslintConfigAfterSetup)) .toMatchInlineSnapshot(` { "lan
t({ parser: languageOptions.parser, settings, }).toEqual({ // parser: require.resolve('eslint-config-next') parser: expect.stringContaining('eslint-config-next'), settings: { 'import/pars
{ "filepath": "test/unit/eslint-config-next/default/eslint-config-next-default.test.ts", "language": "typescript", "file_size": 6072, "cut_index": 716, "middle_length": 229 }
resolved configuration', () => { const eslintConfigAfterSetupJSON = execSync( // Pass explicit absolute path to not get affected by the root eslint config. `pnpm eslint --config ${join(__dirname, 'eslint.config.mjs')} --print-config ${join(__dirname, 'test.js')}`, { cwd: __dirname, ...
rt/resolver': expect.any(Object), react: { version: 'detect', }, }, }) expect(getEslintConfigSnapshot(eslintConfigAfterSetup)) .toMatchInlineSnapshot(` { "language": "@/js", "linterOptions":
) expect({ parser: languageOptions.parser, settings, }).toEqual({ parser: expect.stringContaining('eslint-config-next'), settings: { 'import/parsers': expect.any(Object), 'impo
{ "filepath": "test/unit/eslint-config-next/core-web-vitals/eslint-config-next-core-web-vitals.test.ts", "language": "typescript", "file_size": 6033, "cut_index": 716, "middle_length": 229 }
adFile } from 'fs-extra' import { join } from 'path' const getImage = (filepath) => readFile(join(__dirname, filepath)) describe.each([false, true])( 'detectContentType with imgOptSkipMetadata: %s', (imgOptSkipMetadata) => { it('should return null for empty buffer', async () => { expect(await detectCont...
ctContentType(buffer, imgOptSkipMetadata)).toBe( 'image/jpeg' ) }) it('should return png', async () => { const buffer = await getImage('./images/test.png') expect(await detectContentType(buffer, imgOptSkipMetadata)).toBe(
( Buffer.from([0xa, 0xb, 0xc]), imgOptSkipMetadata ) ).toBe(null) }) it('should return jpg', async () => { const buffer = await getImage('./images/test.jpg') expect(await dete
{ "filepath": "test/unit/image-optimizer/detect-content-type.test.ts", "language": "typescript", "file_size": 4557, "cut_index": 614, "middle_length": 229 }
mizer' import type { IncomingMessage, ServerResponse } from 'http' describe('fetchInternalImage', () => { describe('response size limit', () => { it('should throw error when response has no buffers', async () => { const mockReq = {} as IncomingMessage const mockRes = {} as ServerResponse const ...
error).toBeInstanceOf(ImageError) expect((error as ImageError).statusCode).toBe(400) expect((error as ImageError).message).toBe( '"url" parameter is valid but internal response is invalid' ) }) it('should throw error when
eg') res.end() }) const error = await fetchInternalImage( '/test-image.jpg', mockReq, mockRes, maximumResponseBody, handleRequest ).catch((e) => e) expect(
{ "filepath": "test/unit/image-optimizer/fetch-internal-image.test.ts", "language": "typescript", "file_size": 4761, "cut_index": 614, "middle_length": 229 }
ort { getMaxAge } from 'next/dist/server/image-optimizer' describe('getMaxAge', () => { it('should return 0 when no cache-control provided', () => { expect(getMaxAge(undefined)).toBe(0) }) it('should return 0 when cache-control is null', () => { expect(getMaxAge(null)).toBe(0) }) it('should return 0 ...
Be(9999) }) it('should return cache-control MAX-AGE uppercase', () => { expect(getMaxAge('MAX-AGE=9999')).toBe(9999) }) it('should return cache-control s-maxage lowercase', () => { expect(getMaxAge('s-maxage=9999')).toBe(9999) }) it('sh
')).toBe(0) }) it('should return 0 when cache-control is no-cache', () => { expect(getMaxAge('no-cache')).toBe(0) }) it('should return cache-control max-age lowercase', () => { expect(getMaxAge('max-age=9999')).to
{ "filepath": "test/unit/image-optimizer/get-max-age.test.ts", "language": "typescript", "file_size": 1554, "cut_index": 537, "middle_length": 229 }
'next/dist/server/lib/disk-lru-cache.external' async function writeEntry( cacheDir: string, key: string, sizeInBytes: number, expireAt: number = Date.now() + 60_000 ) { const dir = join(cacheDir, key) const buffer = Buffer.alloc(sizeInBytes, 0x42) // Fill with dummy data await promises.mkdir(dir, { recu...
cheDir: string ): Promise<Array<{ key: string; size: number; expireAt: number }>> { const keys = await promises.readdir(cacheDir).catch(() => []) const entries: Array<{ key: string; size: number; expireAt: number }> = [] for (const key of keys) {
await promises.readdir(dir) const buffer = await promises.readFile(join(dir, file)) const [expireAtStr] = file.split('.') return { size: buffer.byteLength, expireAt: Number(expireAtStr) } } async function initEntries( ca
{ "filepath": "test/unit/image-optimizer/lru-disk-eviction.test.ts", "language": "typescript", "file_size": 5490, "cut_index": 716, "middle_length": 229 }
matchLocalPattern, hasLocalMatch as hasMatch, } from 'next/dist/shared/lib/match-local-pattern' const m = (p: LocalPattern, urlPathAndQuery: string) => matchLocalPattern(p, new URL(urlPathAndQuery, 'http://n')) describe('matchLocalPattern', () => { it('should match anything when no pattern is defined', () => {...
= { search: '', } as const expect(m(p, '/')).toBe(true) expect(m(p, '/path')).toBe(true) expect(m(p, '/path/to')).toBe(true) expect(m(p, '/path/to/file')).toBe(true) expect(m(p, '/path/to/file.txt')).toBe(true) expect(m(p,
(m(p, '/path/to/file.txt')).toBe(true) expect(m(p, '/path/to/file?q=1')).toBe(true) expect(m(p, '/path/to/file?q=1&a=two')).toBe(true) }) it('should match any path without a search query string', () => { const p
{ "filepath": "test/unit/image-optimizer/match-local-pattern.test.ts", "language": "typescript", "file_size": 3673, "cut_index": 614, "middle_length": 229 }
he from 'next/dist/server/lib/incremental-cache/file-system-cache' import { nodeFs } from 'next/dist/server/lib/node-fs-methods' import { CachedRouteKind, IncrementalCacheKind, } from 'next/dist/server/response-cache' const cacheDir = fileURLToPath(new URL('./cache', import.meta.url)) describe('FileSystemCache', ...
s: { 'Content-Type': 'image/png', }, status: 200, kind: CachedRouteKind.APP_ROUTE, }, {} ) expect( ( await fsCache.get('icon.png', { kind: IncrementalCacheKind.APP_ROUTE,
revalidatedTags: [], }) const binary = await fs.readFile( fileURLToPath(new URL('./images/icon.png', import.meta.url)) ) await fsCache.set( 'icon.png', { body: binary, header
{ "filepath": "test/unit/incremental-cache/file-system-cache.test.ts", "language": "typescript", "file_size": 3057, "cut_index": 614, "middle_length": 229 }
Setup } from 'e2e-utils' import { retry } from 'next-test-utils' describe.each(['edge', 'nodejs'])( 'dynamic-css-client-navigation react lazy %s', (runtime) => { const { next } = nextTestSetup({ files: __dirname, }) it(`should not remove style when navigating from static imported component to re...
aitForElementByCss('#red-button').text()).toBe( 'Red Button' ) const buttonBgColor = await browser .elementByCss('button') .getComputedCss('background-color') expect(buttonBgColor).toBe('rgb(255, 0, 0
t retry(async () => { expect(await browser.w
{ "filepath": "test/production/dynamic-css-client-navigation/react-lazy.test.ts", "language": "typescript", "file_size": 863, "cut_index": 529, "middle_length": 52 }
port { nextTestSetup } from 'e2e-utils' describe.each(['edge', 'nodejs'])( 'dynamic-css-client-navigation dynamic import %s', (runtime) => { const { next } = nextTestSetup({ files: __dirname, }) it(`should not remove style when navigating from static imported component to dynamic import at runti...
tton') .text() ).toBe('Red Button') const buttonBgColor = await browser.eval( `window.getComputedStyle(document.querySelector('button')).backgroundColor` ) expect(buttonBgColor).toBe('rgb(255, 0, 0)') }) }
.click() .waitForElementByCss('#red-bu
{ "filepath": "test/production/dynamic-css-client-navigation/dynamic-import/dynamic-import.test.ts", "language": "typescript", "file_size": 824, "cut_index": 514, "middle_length": 52 }
{ writeAppTypeDeclarations } from 'next/dist/lib/typescript/writeAppTypeDeclarations' const fixtureDir = join(__dirname, 'fixtures/app-declarations') const declarationFile = join(fixtureDir, 'next-env.d.ts') const imageImportsEnabled = false describe('find config', () => { beforeEach(async () => { await fs.ens...
ms.d.ts";` + eol + eol + '// NOTE: This file should not be edited' + eol + '// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.' + eol await fs.writeFile(declarationFile, conte
xt" />' + eol + (imageImportsEnabled ? '/// <reference types="next/image-types/global" />' + eol : '') + `import "./.next/types/routes.d.ts";` + eol + `import "./.next/types/root-para
{ "filepath": "test/unit/write-app-declarations.test.ts", "language": "typescript", "file_size": 3993, "cut_index": 614, "middle_length": 229 }
'path' import glob from 'glob' import index from '@next/eslint-plugin-next' const getRuleNameFromRulePath = (path) => basename(path, '.js') const rulePaths = glob.sync('packages/eslint-plugin-next/dist/rules/*js', { absolute: true, }) describe('@next/eslint-plugin-next index', () => { it('should include all defin...
fig = index.configs.recommended expect(config.name).toBe('next/recommended') expect(config.rules).toBeDefined() }) it('should have proper flat config structure for core-web-vitals', () => { const config = index.configs['core-web-vitals']
should have meta information', () => { expect(index.meta).toBeDefined() expect(index.meta.name).toBe('@next/eslint-plugin-next') }) it('should have proper flat config structure for recommended', () => { const con
{ "filepath": "test/unit/eslint-plugin-next/index.test.ts", "language": "typescript", "file_size": 2015, "cut_index": 537, "middle_length": 229 }
Rule = rules['no-duplicate-head'] const message = 'Do not include multiple instances of `<Head/>`. See: https://nextjs.org/docs/messages/no-duplicate-head' const tests = { valid: [ { code: `import Document, { Html, Head, Main, NextScript } from 'next/document' class MyDocument extends Document { ...
render() { return ( <Html> <Head> <meta charSet="utf-8" /> <link href="https://fonts.googleapis.com/css2?family=Sarabun:ital,wght@0,400;0,700;1,400;1,700&display=swa
} export default MyDocument `, filename: 'pages/_document.js', }, { code: `import Document, { Html, Head, Main, NextScript } from 'next/document' class MyDocument extends Document {
{ "filepath": "test/unit/eslint-plugin-next/no-duplicate-head.test.ts", "language": "typescript", "file_size": 3263, "cut_index": 614, "middle_length": 229 }
ment */ import { userAgentFromString, userAgent, NextRequest } from 'next/server' const UA_STRING = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36' it('parse an user agent', () => { const parser = userAgentFromString(UA_STRING) expect(p...
}) expect(parser.cpu).toStrictEqual({ architecture: undefined }) expect(parser.isBot).toBe(false) }) it('parse empty user agent', () => { expect.assertions(3) for (const input of [undefined, null, '']) { expect(userAgentFromString(input)).toSt
ame: 'Chrome', version: '89.0.4389.90', major: '89', }) expect(parser.engine).toStrictEqual({ name: 'Blink', version: '89.0.4389.90', }) expect(parser.os).toStrictEqual({ name: 'Mac OS', version: '11.2.3'
{ "filepath": "test/unit/web-runtime/user-agent.test.ts", "language": "typescript", "file_size": 2061, "cut_index": 563, "middle_length": 229 }
om 'postcss' import mod from 'next/dist/compiled/cssnano-simple' import css from '../noop-template' describe('accepts plugin configuration', () => { test('should not remove all comments', async () => { const input = css` p { /*! heading */ color: yellow; } ` const res = awai...
p { /*! heading */ color: yellow; } ` const res = await postcss([ mod({ discardComments: { removeAll: true } }), ]).process(input, { from: 'input.css', to: 'output.css', }) expect(res.css).t
l comments', async () => { const input = css`
{ "filepath": "test/unit/cssnano-simple/cssnano-simple/plugin-config.test.ts", "language": "typescript", "file_size": 866, "cut_index": 529, "middle_length": 52 }
v jest */ import { extractEtag, getImageEtag } from 'next/dist/server/image-optimizer' import { readFile } from 'fs-extra' import { join } from 'path' describe('extractEtag', () => { it('should return base64url encoded etag if etag is provided', () => { const etag = 'sample-etag' const result = extractEtag(e...
dirname, './images/test.jpg')) const res = extractEtag(null, buffer) expect(res).toBe(getImageEtag(buffer)) }) it('should call getImageEtag and return its result if etag is undefined', async () => { const buffer = await readFile(join(__dir
t result = extractEtag(etag, Buffer.from('')) expect(result).toEqual('Vy8ic2FtcGxlLWV0YWci') }) it('should call getImageEtag and return its result if etag is null', async () => { const buffer = await readFile(join(__
{ "filepath": "test/unit/image-optimizer/extract-etag.test.ts", "language": "typescript", "file_size": 1392, "cut_index": 524, "middle_length": 229 }
from 'next/dist/shared/lib/find-closest-quality' describe('findClosestQuality', () => { it.each<{ input: Parameters<typeof findClosestQuality>; output: number }>([ { input: [undefined, undefined], output: 75, }, { input: [50, undefined], output: 50, }, { input: [50,...
, output: 30, }, { input: [40, { qualities: [10, 30, 50] }], output: 30, // favor the lower number when halfway }, { input: [41, { qualities: [10, 30, 50] }], output: 50, }, { input: [75, { qualit
output: 30, }, { input: [31, { qualities: [10, 30, 50] }], output: 30, }, { input: [29, { qualities: [10, 30, 50] }], output: 30, }, { input: [39, { qualities: [10, 30, 50] }]
{ "filepath": "test/unit/image-optimizer/find-closest-quality.test.ts", "language": "typescript", "file_size": 2314, "cut_index": 563, "middle_length": 229 }
ver/image-optimizer' import { CachedRouteKind, IncrementalCacheEntry, } from 'next/dist/server/response-cache/types' import { readFile } from 'fs-extra' import { join } from 'path' const getImageUpstream = async (filepath, contentType = 'image/jpeg') => { const buffer = await readFile(join(__dirname, filepath)) ...
= async ( filepath, extension = 'jpeg', optimizedEtag = true ) => { const buffer = await readFile(join(__dirname, filepath)) const upstreamEtag = getImageEtag(buffer) const result: IncrementalCacheEntry = { ...baseCacheEntry, value: {
} const baseCacheEntry = { revalidateAfter: Date.now() + 1000, curRevalidate: Date.now() + 500, revalidate: Date.now() + 1000, isStale: false, isMiss: false, isFallback: false, } as const const getPreviousCacheEntry
{ "filepath": "test/unit/image-optimizer/get-previously-cached-image-or-null.test.ts", "language": "typescript", "file_size": 3482, "cut_index": 614, "middle_length": 229 }
tTestSetup } from 'e2e-utils' describe.each(['edge', 'nodejs'])( 'dynamic-css-client-navigation next/dynamic %s', (runtime) => { const { next } = nextTestSetup({ files: __dirname, }) it(`should not remove style when navigating from static imported component to next/dynamic at runtime ${runtime}`...
expect(buttonBgColor).toBe('rgb(255, 0, 0)') }) it(`should not remove style when navigating from static imported component to next/dynamic with ssr: false at runtime ${runtime}`, async () => { const browser = await next.browser(`/${ru
.waitForElementByCss('#red-button') .text() ).toBe('Red Button') const buttonBgColor = await browser.eval( `window.getComputedStyle(document.querySelector('button')).backgroundColor` )
{ "filepath": "test/production/dynamic-css-client-navigation/next-dynamic.test.ts", "language": "typescript", "file_size": 1442, "cut_index": 524, "middle_length": 229 }
Rule = rules['no-typos'] const tests = { valid: [ ` export default function Page() { return <div></div>; } export const getStaticPaths = async () => {}; export const getStaticProps = async () => {}; `, ` export default function Page() { return <div></div>; ...
hat is one operation away from the correct one ` export default function Page() { return <div></div>; } export async function getServerSidePropsss() {}; `, ` export default function Page() { return <div><
() {}; export async function getStaticProps() {}; `, ` export default function Page() { return <div></div>; } export async function getServerSideProps() {}; `, // detect only typo t
{ "filepath": "test/unit/eslint-plugin-next/no-typos.test.ts", "language": "typescript", "file_size": 3290, "cut_index": 614, "middle_length": 229 }
} from '@next/eslint-plugin-next' const NextESLintRule = rules['no-css-tags'] const message = 'Do not include stylesheets manually. See: https://nextjs.org/docs/messages/no-css-tags' const tests = { valid: [ `import {Head} from 'next/document'; export class Blah extends Head { render() { ...
); } }`, `import {Head} from 'next/document'; export class Blah extends Head { render(props) { return ( <div> <h1>Hello title</h1> <link {...props} /> </div
ead { render() { return ( <div> <h1>Hello title</h1> <link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet" /> </div>
{ "filepath": "test/unit/eslint-plugin-next/no-css-tags.test.ts", "language": "typescript", "file_size": 2352, "cut_index": 563, "middle_length": 229 }
', 'http://127.0.0.1:3000') expect(parsed.basePath).toEqual('') expect(parsed.hostname).toEqual('localhost') expect(parsed.host).toEqual('localhost:3000') expect(parsed.href).toEqual('http://localhost:3000/about?param1=value1') parsed.pathname = '/hihi' expect(parsed.href).toEqual('http://localhost:3000/hi...
(parsed.href).toEqual('http://foo.com/about?param1=value1') expect(parsed.toString()).toEqual('http://foo.com/about?param1=value1') }) it('does noop changing to an invalid hostname', () => { const url = new NextURL('https://foo.com/example') url.hos
parsed.host).toEqual('localhost') expect(parsed.href).toEqual('http://localhost/about?param1=value1') parsed.hostname = 'foo.com' expect(parsed.hostname).toEqual('foo.com') expect(parsed.host).toEqual('foo.com') expect
{ "filepath": "test/unit/web-runtime/next-url.test.ts", "language": "typescript", "file_size": 12587, "cut_index": 921, "middle_length": 229 }
hould reject a literal private IP hostname with a generic error message', async () => { const fetchMock = jest.fn() global.fetch = fetchMock const error = await fetchExternalImage( 'http://192.168.0.1/private.jpg', false, 50_000_000 ).catch((e) => e) expect(error)...
0, body: new ReadableStream({ start(controller) { controller.enqueue(new Uint8Array([1, 2, 3])) controller.close() }, }), headers: { get: jest.fn((header: string) => {
pect(fetchMock).not.toHaveBeenCalled() }) it('should allow a literal private IP when dangerouslyAllowLocalIP is true', async () => { global.fetch = jest.fn().mockResolvedValue({ ok: true, status: 20
{ "filepath": "test/unit/image-optimizer/fetch-external-image.test.ts", "language": "typescript", "file_size": 7045, "cut_index": 716, "middle_length": 229 }
xample.com:81/path/to/file'))).toBe(true) expect(m(p, new URL('https://example.com:81/path/to/file?q=1'))).toBe(true) expect(m(p, new URL('http://example.com:81/path/to/file'))).toBe(true) }) it('should match literal protocol and hostname', () => { const p = { protocol: 'https', hostname: 'example.com'...
ttps://example.com/path/to/file'))).toBe(true) expect(m(p, new URL('https://example.com:81/path/to/file'))).toBe(true) expect(m(p, new URL('https://example.com:81/path/to/file?q=1'))).toBe(true) expect(m(p, new URL('http://example.com:81/path/t
e(false) expect(m(p, new URL('https://com'))).toBe(false) expect(m(p, new URL('https://example.com/path/to'))).toBe(true) expect(m(p, new URL('https://example.com/path/to/file'))).toBe(true) expect(m(p, new URL('h
{ "filepath": "test/unit/image-optimizer/match-remote-pattern.test.ts", "language": "typescript", "file_size": 22470, "cut_index": 1331, "middle_length": 229 }
join(__dirname, '_resolvedata', 'with-function') // force require usage instead of dynamic import in jest // x-ref: https://github.com/nodejs/node/issues/35889 process.env.__NEXT_TEST_MODE = 'jest' describe('config', () => { let loadConfig: typeof import('next/dist/server/config').default beforeEach(async () =>...
t config = await loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfig) expect((config as any).customConfig).toBe(true) }) it('Should pass the phase correctly', async () => { const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, pathToConfigFn
mically import the module after reset to get a fresh instance const configModule = await import('next/dist/server/config') loadConfig = configModule.default }) it('Should get the configuration', async () => { cons
{ "filepath": "test/unit/isolated/config.test.ts", "language": "typescript", "file_size": 8092, "cut_index": 716, "middle_length": 229 }
} from '../utils' describe('eslint-config-next/typescript', () => { it('should match expected resolved configuration', () => { const eslintConfigAfterSetupJSON = execSync( // Pass explicit absolute path to not get affected by the root eslint config. `pnpm eslint --config ${join(__dirname, 'eslint.con...
expect(getEslintConfigSnapshot(eslintConfigAfterSetup)) .toMatchInlineSnapshot(` { "language": "@/js", "linterOptions": { "reportUnusedDisableDirectives": 1, }, "plugins": [ "@", "@typ
uageOptions, ...eslintConfigAfterSetup } = JSON.parse( eslintConfigAfterSetupJSON ) expect({ parser: languageOptions.parser, }).toEqual({ parser: expect.stringContaining('typescript-eslint'), })
{ "filepath": "test/unit/eslint-config-next/typescript/eslint-config-next-typescript.test.ts", "language": "typescript", "file_size": 3300, "cut_index": 614, "middle_length": 229 }
expect(m(p, new URL('https://example.com:81/path/to/file'))).toBe(false) expect(m(p, new URL('https://example.com:81/path/to/file?q=1'))).toBe(false) expect(m(p, new URL('http://example.com:81/path/to/file'))).toBe(false) }) it('should match literal protocol, hostname, port 42', () => { const p = new...
ile?q=1'))).toBe(false) expect(m(p, new URL('http://example.com:42/path/to/file'))).toBe(false) expect(m(p, new URL('ftp://example.com:42/path/to/file'))).toBe(false) expect(m(p, new URL('https://example.com'))).toBe(false) expect(m(p, new
ps://sub.example.com:42'))).toBe(false) expect(m(p, new URL('https://com:42'))).toBe(false) expect(m(p, new URL('https://example.com:42/path/to/file'))).toBe(true) expect(m(p, new URL('https://example.com:42/path/to/f
{ "filepath": "test/unit/image-optimizer/match-remote-pattern-with-url.test.ts", "language": "typescript", "file_size": 17630, "cut_index": 1331, "middle_length": 229 }
tTestSetup } from 'e2e-utils' import { retry } from 'next-test-utils' describe('ssg-single-pass', () => { const { next, skipped } = nextTestSetup({ files: __dirname, }) if (skipped) { return } it('should only render the page once during build', async () => { expect(next.cliOutput).toIncludeRepe...
mber).toMatch(/\d+/) // grab the index of the last log message so we can start // parsing future logs from there const outputIndex = next.cliOutput.length // trigger a revalidation const response = await (await next.fetch('/revalidate'
- 1 expect(logOccurrences).toBe(1) logOccurrences = 0 const browser = await next.browser('/') const initialRandomNumber = await browser .elementById('random-number') .text() expect(initialRandomNu
{ "filepath": "test/production/app-dir/ssg-single-pass/ssg-single-pass.test.ts", "language": "typescript", "file_size": 1482, "cut_index": 524, "middle_length": 229 }
tion } from 'next/server' async function Random({ cached }: { cached?: boolean }) { const data = await fetch( 'https://next-data-api-endpoint.vercel.app/api/random' ).then((res) => res.text()) return ( <> <p>now: {Date.now()}</p> <p> {cached ? 'cached ' : ''}random: {data} </p>...
<Random /> </Suspense> <Suspense fallback={<p>Loading...</p>}> <CachedRandom /> </Suspense> <form action={revalidate}> <button id="revalidate-tag" type="submit"> Revalidate tag </button>
/p> <Suspense fallback={<p>Loading...</p>}>
{ "filepath": "test/production/app-dir/global-default-cache-handler/app/page.tsx", "language": "tsx", "file_size": 937, "cut_index": 606, "middle_length": 52 }
const { next, skipped } = nextTestSetup({ files: __dirname, }) if (skipped) return it('should only include imported components 3rd party package in browser bundle with direct imports', async () => { const $ = await next.render$('/third-party-dep') const chunkContents = await Promise.all( $('s...
oBe(false) expect( chunkContents.every((content) => content.includes('client-dep-default:esm') ) ).toBe(false) }) it('should only include the imported identifier of CJS module in browser bundle', async () => { const $ =
file }) ) expect( chunkContents.some((content) => content.includes('client-dep-bar:esm')) ).toBe(true) expect( chunkContents.every((content) => content.includes('client-dep-foo:esm')) ).t
{ "filepath": "test/production/app-dir/client-components-tree-shaking/index.test.ts", "language": "typescript", "file_size": 3224, "cut_index": 614, "middle_length": 229 }
() => { // TODO(NAR-423): Migrate to Cache Components. describe.skip('with mixed static and dynamic pages and app router routes', () => { const { next } = nextTestSetup({ files: path.join(__dirname, 'fixtures/mixed'), skipStart: true, env: { __NEXT_PRIVATE_DETERMINISTIC_BUILD_OUTPUT: '...
che-life-hours 1h 1d β”œ Ζ’ /dynamic β”œ /ppr/[slug] 1w 30d β”‚ β”œ ◐ /ppr/[slug] 1w 30d β”‚ β”œ ◐ /ppr/days 1d 1w β”‚ β”” ◐ /ppr/weeks 1w 30d
oMatchInlineSnapshot(` "Route (app) Revalidate Expire β”Œ β—‹ /_not-found β”œ Ζ’ /api β”œ β—‹ /api/force-static β”œ β—‹ /app-static β”œ β—‹ /cache-life-custom β‰ˆ7m β‰ˆ2h β”œ β—‹ /ca
{ "filepath": "test/production/app-dir/build-output-tree-view/build-output-tree-view.test.ts", "language": "typescript", "file_size": 3390, "cut_index": 614, "middle_length": 229 }
import { nextTestSetupActionTreeShaking, getActionsRoutesStateByRuntime, } from '../_testing/utils' // TODO: revisit when we have a better side-effect free transform approach for server action ;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)( 'actions-tree-shaking - basic', () => { const { next ...
pp/inline/page.js#$$RSC_SERVER_ACTION_0", ], "app/server/page": [ "app/actions.js#clientComponentAction", "app/actions.js#serverComponentAction", "app/actions.js#unusedExportedAction", ], }
RoutesStateByRuntime(next) expect(actionsRoutesState).toMatchInlineSnapshot(` { "app/client/page": [ "app/actions.js#clientComponentAction", ], "app/inline/page": [ "a
{ "filepath": "test/production/app-dir/actions-tree-shaking/basic/basic.test.ts", "language": "typescript", "file_size": 1020, "cut_index": 512, "middle_length": 229 }
{ nextTestSetupActionTreeShaking, getActionsRoutesStateByRuntime, } from '../_testing/utils' // TODO: revisit when we have a better side-effect free transform approach for server action ;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)( 'actions-tree-shaking - mixed-module-actions', () => { cons...
"app/mixed-module/cjs/actions.js#esmModuleTypeAction", "app/mixed-module/cjs/actions.js#unusedModuleTypeAction1", ], "app/mixed-module/esm/page": [ "app/mixed-module/esm/actions.js#cjsModuleTypeAction",
esState = await getActionsRoutesStateByRuntime(next) expect(actionsRoutesState).toMatchInlineSnapshot(` { "app/mixed-module/cjs/page": [ "app/mixed-module/cjs/actions.js#cjsModuleTypeAction",
{ "filepath": "test/production/app-dir/actions-tree-shaking/mixed-module-actions/mixed-module-actions.test.ts", "language": "typescript", "file_size": 1176, "cut_index": 518, "middle_length": 229 }
est, retry } from 'next-test-utils' import { parseRelativeUrl } from 'next/dist/shared/lib/router/utils/parse-relative-url' function getServerReferenceIdsFromBundle(source: string): string[] { // Reference IDs are strings with [0-9a-f] that are at least 32 characters long. // We use RegExp to find them in the bund...
}) afterEach(async () => { logs.length = 0 }) /** * Parses the client reference manifest for a given route and returns the client chunks */ function getClientChunks(route: string): Array<string> { const clientManifest = getClientRe
t } = nextTestSetup({ files: __dirname, }) const logs: string[] = [] beforeAll(() => { const onLog = (log: string) => { logs.push(log.trim()) } next.on('stdout', onLog) next.on('stderr', onLog)
{ "filepath": "test/production/app-dir/actions-tree-shaking/client-actions-tree-shaking/client-actions-tree-shaking.test.ts", "language": "typescript", "file_size": 4232, "cut_index": 614, "middle_length": 229 }