Unverified Commit fd2bd295 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Move Ready in time before handler initialization (#88235)

## Move "Ready in X" log before config loading and eliminate duplicate
`loadConfig` calls

### What?

Reorder the dev server startup flow so the "Ready in X" log appears
before loading the user's `next.config.js`, and eliminate duplicate
`loadConfig` calls in both dev and build paths.

### Why?

Previously, the "Ready in X" time included the time spent loading and
evaluating the user's `next.config.js` file. This made the framework
appear slower than it actually is, especially for projects with complex
config files or slow config evaluation.

Additionally, config was being loaded twice:
- **Dev server**: Once in `getStartServerInfo()` just for logging, then
again in `getRequestHandlers()`
- **Build**: Once for the main build, then again in
`getStartServerInfo()` just for logging

### How?

**Before:**
```
1. getStartServerInfo() → loadConfig #1 (slow - blocks on next.config.js)
2. logStartInfo() → logs version, URLs, experimental features
3. "Ready in X" ← time includes config loading
4. getRequestHandlers() → loadConfig #2
```

**After:**
```
1. logStartInfo() → logs version, URLs, envInfo (no config needed)
2. "Ready in X" ← reflects actual framework startup time
3. getRequestHandlers() → loadConfig (once)
4. logExperimentalInfo() → logs experimental features
```

**Changes:**

- Split `logStartInfo` into two functions:
- `logStartInfo()` - basic info (version, URLs, env) - no config needed
  - `logExperimentalInfo()` - experimental features and cacheComponents
- Removed `getStartServerInfo()` which was loading config unnecessarily
- Added `experimentalFeatures` and `cacheComponents` to
`ServerInitResult` so they can be passed back after config loads
- In build, added `reportExperimentalFeatures` callback to the existing
`loadConfig` call instead of loading config twice

---------
Co-authored-by: 's avatarVercel <vercel[bot]@users.noreply.github.com>
parent 586c1ed7
...@@ -49,8 +49,7 @@ if ( ...@@ -49,8 +49,7 @@ if (
process.exit(1) process.exit(1)
} }
// Start performance profiling after Node.js version is checked process.env.NEXT_PRIVATE_START_TIME = Date.now().toString()
performance.mark('next-start')
for (const dependency of ['react', 'react-dom']) { for (const dependency of ['react', 'react-dom']) {
try { try {
......
...@@ -187,7 +187,12 @@ import { ...@@ -187,7 +187,12 @@ import {
updateBuildDiagnostics, updateBuildDiagnostics,
recordFetchMetrics, recordFetchMetrics,
} from '../diagnostics/build-diagnostics' } from '../diagnostics/build-diagnostics'
import { getStartServerInfo, logStartInfo } from '../server/lib/app-info-log' import {
getEnvInfo,
logExperimentalInfo,
logStartInfo,
type ConfiguredExperimentalFeature,
} from '../server/lib/app-info-log'
import type { NextEnabledDirectories } from '../server/base-server' import type { NextEnabledDirectories } from '../server/base-server'
import { hasCustomExportOutput } from '../export/utils' import { hasCustomExportOutput } from '../export/utils'
import { traceMemoryUsage } from '../lib/memory/trace' import { traceMemoryUsage } from '../lib/memory/trace'
...@@ -931,6 +936,7 @@ export default async function build( ...@@ -931,6 +936,7 @@ export default async function build(
NextBuildContext.loadedEnvFiles = loadedEnvFiles NextBuildContext.loadedEnvFiles = loadedEnvFiles
const turborepoAccessTraceResult = new TurborepoAccessTraceResult() const turborepoAccessTraceResult = new TurborepoAccessTraceResult()
let experimentalFeatures: ConfiguredExperimentalFeature[] = []
const config: NextConfigComplete = await nextBuildSpan const config: NextConfigComplete = await nextBuildSpan
.traceChild('load-next-config') .traceChild('load-next-config')
.traceAsyncFn(() => .traceAsyncFn(() =>
...@@ -941,6 +947,11 @@ export default async function build( ...@@ -941,6 +947,11 @@ export default async function build(
silent: false, silent: false,
reactProductionProfiling, reactProductionProfiling,
debugPrerender, debugPrerender,
reportExperimentalFeatures(features) {
experimentalFeatures = features.toSorted(
({ key: a }, { key: b }) => a.localeCompare(b)
)
},
}), }),
turborepoAccessTraceResult turborepoAccessTraceResult
) )
...@@ -1117,20 +1128,18 @@ export default async function build( ...@@ -1117,20 +1128,18 @@ export default async function build(
) )
// Always log next version first then start rest jobs // Always log next version first then start rest jobs
const { envInfo, experimentalFeatures, cacheComponents } = const envInfo = getEnvInfo(dir)
await getStartServerInfo({
dir,
dev: false,
debugPrerender,
})
logStartInfo({ logStartInfo({
networkUrl: null, networkUrl: null,
appUrl: null, appUrl: null,
envInfo, envInfo,
experimentalFeatures,
logBundler: true, logBundler: true,
cacheComponents, })
logExperimentalInfo({
experimentalFeatures,
cacheComponents: !!config.cacheComponents,
}) })
const typeCheckingOptions: Parameters<typeof startTypeChecking>[0] = { const typeCheckingOptions: Parameters<typeof startTypeChecking>[0] = {
......
...@@ -305,6 +305,7 @@ const nextDev = async ( ...@@ -305,6 +305,7 @@ const nextDev = async (
env: { env: {
...defaultEnv, ...defaultEnv,
...(isTurbopack ? { TURBOPACK: process.env.TURBOPACK } : undefined), ...(isTurbopack ? { TURBOPACK: process.env.TURBOPACK } : undefined),
NEXT_PRIVATE_START_TIME: process.env.NEXT_PRIVATE_START_TIME,
NEXT_PRIVATE_WORKER: '1', NEXT_PRIVATE_WORKER: '1',
NEXT_PRIVATE_TRACE_ID: traceId, NEXT_PRIVATE_TRACE_ID: traceId,
NODE_EXTRA_CA_CERTS: startServerOptions.selfSignedCertificate NODE_EXTRA_CA_CERTS: startServerOptions.selfSignedCertificate
......
...@@ -2,27 +2,26 @@ import { loadEnvConfig } from '@next/env' ...@@ -2,27 +2,26 @@ import { loadEnvConfig } from '@next/env'
import * as inspector from 'inspector' import * as inspector from 'inspector'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import { bold, purple, strikethrough } from '../../lib/picocolors' import { bold, purple, strikethrough } from '../../lib/picocolors'
import { import type { ConfiguredExperimentalFeature } from '../config'
PHASE_DEVELOPMENT_SERVER,
PHASE_PRODUCTION_BUILD,
} from '../../shared/lib/constants'
import loadConfig, { type ConfiguredExperimentalFeature } from '../config'
import { experimentalSchema } from '../config-schema' import { experimentalSchema } from '../config-schema'
// Re-export the type for consumers
export type { ConfiguredExperimentalFeature }
/**
* Logs basic startup info that doesn't require config.
* Called before "Ready in X" to show immediate feedback.
*/
export function logStartInfo({ export function logStartInfo({
networkUrl, networkUrl,
appUrl, appUrl,
envInfo, envInfo,
experimentalFeatures,
logBundler, logBundler,
cacheComponents,
}: { }: {
networkUrl: string | null networkUrl: string | null
appUrl: string | null appUrl: string | null
envInfo?: string[] envInfo?: string[]
experimentalFeatures?: ConfiguredExperimentalFeature[]
logBundler: boolean logBundler: boolean
cacheComponents?: boolean
}) { }) {
let versionSuffix = '' let versionSuffix = ''
const parts = [] const parts = []
...@@ -37,10 +36,6 @@ export function logStartInfo({ ...@@ -37,10 +36,6 @@ export function logStartInfo({
} }
} }
if (cacheComponents) {
parts.push('Cache Components')
}
if (parts.length > 0) { if (parts.length > 0) {
versionSuffix = ` (${parts.join(', ')})` versionSuffix = ` (${parts.join(', ')})`
} }
...@@ -66,6 +61,22 @@ export function logStartInfo({ ...@@ -66,6 +61,22 @@ export function logStartInfo({
Log.bootstrap(`- Debugger port: ${debugPort}`) Log.bootstrap(`- Debugger port: ${debugPort}`)
} }
if (envInfo?.length) Log.bootstrap(`- Environments: ${envInfo.join(', ')}`) if (envInfo?.length) Log.bootstrap(`- Environments: ${envInfo.join(', ')}`)
}
/**
* Logs experimental features and config-dependent info.
* Called after getRequestHandlers completes.
*/
export function logExperimentalInfo({
experimentalFeatures,
cacheComponents,
}: {
experimentalFeatures?: ConfiguredExperimentalFeature[]
cacheComponents?: boolean
}) {
if (cacheComponents) {
Log.bootstrap(`- Cache Components enabled`)
}
if (experimentalFeatures?.length) { if (experimentalFeatures?.length) {
Log.bootstrap(`- Experiments (use with caution):`) Log.bootstrap(`- Experiments (use with caution):`)
...@@ -102,49 +113,10 @@ export function logStartInfo({ ...@@ -102,49 +113,10 @@ export function logStartInfo({
Log.info('') Log.info('')
} }
export async function getStartServerInfo({ /**
dir, * Gets environment info for logging. Fast operation that doesn't require config.
dev, */
debugPrerender, export function getEnvInfo(dir: string): string[] {
}: {
dir: string
dev: boolean
debugPrerender?: boolean
}): Promise<{
envInfo?: string[]
experimentalFeatures?: ConfiguredExperimentalFeature[]
cacheComponents?: boolean
}> {
let experimentalFeatures: ConfiguredExperimentalFeature[] = []
let cacheComponents = false
const config = await loadConfig(
dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_BUILD,
dir,
{
reportExperimentalFeatures(features) {
experimentalFeatures = features.sort(({ key: a }, { key: b }) =>
a.localeCompare(b)
)
},
debugPrerender,
silent: false,
}
)
cacheComponents = !!config.cacheComponents
// we need to reset env if we are going to create
// the worker process with the esm loader so that the
// initial env state is correct
let envInfo: string[] = []
const { loadedEnvFiles } = loadEnvConfig(dir, true, console, false) const { loadedEnvFiles } = loadEnvConfig(dir, true, console, false)
if (loadedEnvFiles.length > 0) { return loadedEnvFiles.map((f) => f.path)
envInfo = loadedEnvFiles.map((f) => f.path)
}
return {
envInfo,
experimentalFeatures,
cacheComponents,
}
} }
...@@ -8,6 +8,7 @@ import type { ServerResponse } from 'http' ...@@ -8,6 +8,7 @@ import type { ServerResponse } from 'http'
import type { OnCacheEntryHandler } from '../request-meta' import type { OnCacheEntryHandler } from '../request-meta'
import { interopDefault } from '../../lib/interop-default' import { interopDefault } from '../../lib/interop-default'
import { formatDynamicImportPath } from '../../lib/format-dynamic-import-path' import { formatDynamicImportPath } from '../../lib/format-dynamic-import-path'
import type { ConfiguredExperimentalFeature } from '../config'
export type ServerInitResult = { export type ServerInitResult = {
requestHandler: RequestHandler requestHandler: RequestHandler
...@@ -17,6 +18,10 @@ export type ServerInitResult = { ...@@ -17,6 +18,10 @@ export type ServerInitResult = {
closeUpgraded: () => void closeUpgraded: () => void
// The distDir from config, used by the parent process for telemetry/trace // The distDir from config, used by the parent process for telemetry/trace
distDir: string distDir: string
// Experimental features from config, used for logging after server is ready
experimentalFeatures: ConfiguredExperimentalFeature[]
// Whether cache components is enabled
cacheComponents: boolean
} }
let initializations: Record<string, Promise<ServerInitResult> | undefined> = {} let initializations: Record<string, Promise<ServerInitResult> | undefined> = {}
...@@ -94,6 +99,8 @@ async function initializeImpl(opts: { ...@@ -94,6 +99,8 @@ async function initializeImpl(opts: {
quiet?: boolean quiet?: boolean
onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined
distDir: string distDir: string
experimentalFeatures: ConfiguredExperimentalFeature[]
cacheComponents: boolean
}): Promise<ServerInitResult> { }): Promise<ServerInitResult> {
const type = process.env.__NEXT_PRIVATE_RENDER_WORKER const type = process.env.__NEXT_PRIVATE_RENDER_WORKER
if (type) { if (type) {
...@@ -170,6 +177,8 @@ async function initializeImpl(opts: { ...@@ -170,6 +177,8 @@ async function initializeImpl(opts: {
opts.bundlerService?.close() opts.bundlerService?.close()
}, },
distDir: opts.distDir, distDir: opts.distDir,
experimentalFeatures: opts.experimentalFeatures,
cacheComponents: opts.cacheComponents,
} }
} }
......
...@@ -9,7 +9,7 @@ import '../require-hook' ...@@ -9,7 +9,7 @@ import '../require-hook'
import url from 'url' import url from 'url'
import path from 'path' import path from 'path'
import loadConfig from '../config' import loadConfig, { type ConfiguredExperimentalFeature } from '../config'
import { serveStatic } from '../serve-static' import { serveStatic } from '../serve-static'
import setupDebug from 'next/dist/compiled/debug' import setupDebug from 'next/dist/compiled/debug'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
...@@ -98,10 +98,18 @@ export async function initialize(opts: { ...@@ -98,10 +98,18 @@ export async function initialize(opts: {
process.env.NODE_ENV = opts.dev ? 'development' : 'production' process.env.NODE_ENV = opts.dev ? 'development' : 'production'
} }
let experimentalFeatures: ConfiguredExperimentalFeature[] = []
const config = await loadConfig( const config = await loadConfig(
opts.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER, opts.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER,
opts.dir, opts.dir,
{ silent: false } {
silent: false,
reportExperimentalFeatures(features) {
experimentalFeatures = features.toSorted(({ key: a }, { key: b }) =>
a.localeCompare(b)
)
},
}
) )
let compress: ReturnType<typeof setupCompression> | undefined let compress: ReturnType<typeof setupCompression> | undefined
...@@ -728,6 +736,8 @@ export async function initialize(opts: { ...@@ -728,6 +736,8 @@ export async function initialize(opts: {
quiet: opts.quiet, quiet: opts.quiet,
onDevServerCleanup: opts.onDevServerCleanup, onDevServerCleanup: opts.onDevServerCleanup,
distDir: config.distDir, distDir: config.distDir,
experimentalFeatures,
cacheComponents: config.cacheComponents,
} }
renderServerOpts.serverFields.routerServerHandler = requestHandlerImpl renderServerOpts.serverFields.routerServerHandler = requestHandlerImpl
...@@ -900,5 +910,7 @@ export async function initialize(opts: { ...@@ -900,5 +910,7 @@ export async function initialize(opts: {
development?.bundler?.hotReloader?.close() development?.bundler?.hotReloader?.close()
}, },
distDir: config.distDir, distDir: config.distDir,
experimentalFeatures,
cacheComponents: config.cacheComponents,
} }
} }
...@@ -29,13 +29,13 @@ import { ...@@ -29,13 +29,13 @@ import {
CONFIG_FILES, CONFIG_FILES,
PHASE_DEVELOPMENT_SERVER, PHASE_DEVELOPMENT_SERVER,
} from '../../shared/lib/constants' } from '../../shared/lib/constants'
import { getStartServerInfo, logStartInfo } from './app-info-log' import { getEnvInfo, logExperimentalInfo, logStartInfo } from './app-info-log'
import { validateTurboNextConfig } from '../../lib/turbopack-warning' import { validateTurboNextConfig } from '../../lib/turbopack-warning'
import { type Span, trace, flushAllTraces } from '../../trace' import { type Span, trace, flushAllTraces } from '../../trace'
import { isIPv6 } from './is-ipv6' import { isIPv6 } from './is-ipv6'
import { AsyncCallbackSet } from './async-callback-set' import { AsyncCallbackSet } from './async-callback-set'
import type { NextServer } from '../next' import type { NextServer } from '../next'
import type { ConfiguredExperimentalFeature } from '../config' import { durationToString } from '../../build/duration-to-string'
const debug = setupDebug('next:start-server') const debug = setupDebug('next:start-server')
let startServerSpan: Span | undefined let startServerSpan: Span | undefined
...@@ -358,28 +358,30 @@ export async function startServer( ...@@ -358,28 +358,30 @@ export async function startServer(
process.env.__NEXT_EXPERIMENTAL_HTTPS = '1' process.env.__NEXT_EXPERIMENTAL_HTTPS = '1'
} }
// Only load env and config in dev to for logging purposes // Get env info first (fast, doesn't require config)
let envInfo: string[] | undefined const envInfo = isDev ? getEnvInfo(dir) : undefined
let experimentalFeatures: ConfiguredExperimentalFeature[] | undefined
let cacheComponents: boolean | undefined // Log basic startup info immediately (before loading config)
try { logStartInfo({
if (isDev) { networkUrl,
const startServerInfo = await getStartServerInfo({ dir, dev: isDev }) appUrl,
envInfo = startServerInfo.envInfo envInfo,
cacheComponents = startServerInfo.cacheComponents logBundler: isDev,
experimentalFeatures = startServerInfo.experimentalFeatures })
}
logStartInfo({ // Calculate and log "Ready in X" before loading config
networkUrl, // so it reflects actual framework startup time
appUrl, const startTime = parseInt(process.env.NEXT_PRIVATE_START_TIME || '0', 10)
envInfo, const endTime = Date.now()
experimentalFeatures, const startServerProcessDurationMs = endTime - startTime
cacheComponents,
logBundler: isDev,
})
Log.event(`Starting...`) const formattedStartDuration = durationToString(
startServerProcessDurationMs / 1000
)
Log.event(`Ready in ${formattedStartDuration}`)
try {
let cleanupStarted = false let cleanupStarted = false
let closeUpgraded: (() => void) | null = null let closeUpgraded: (() => void) | null = null
const cleanup = () => { const cleanup = () => {
...@@ -446,6 +448,7 @@ export async function startServer( ...@@ -446,6 +448,7 @@ export async function startServer(
process.on('SIGTERM', cleanup) process.on('SIGTERM', cleanup)
} }
// Now load config via getRequestHandlers (single loadConfig call)
const initResult = await getRequestHandlers({ const initResult = await getRequestHandlers({
dir, dir,
port, port,
...@@ -464,21 +467,15 @@ export async function startServer( ...@@ -464,21 +467,15 @@ export async function startServer(
nextServer = initResult.server nextServer = initResult.server
closeUpgraded = initResult.closeUpgraded closeUpgraded = initResult.closeUpgraded
const startServerProcessDuration = // Log experimental features after config is loaded
performance.mark('next-start-end') && if (isDev) {
performance.measure( logExperimentalInfo({
'next-start-duration', experimentalFeatures: initResult.experimentalFeatures,
'next-start', cacheComponents: initResult.cacheComponents,
'next-start-end' })
).duration }
handlersReady() handlersReady()
const formatDurationText =
startServerProcessDuration > 2000
? `${Math.round(startServerProcessDuration / 100) / 10}s`
: `${Math.round(startServerProcessDuration)}ms`
Log.event(`Ready in ${formatDurationText}`)
if (process.env.TURBOPACK && isDev) { if (process.env.TURBOPACK && isDev) {
await validateTurboNextConfig({ await validateTurboNextConfig({
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
const { version: nextVersion } = require('next/package.json') import { retry } from 'next-test-utils'
const cacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true' const cacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true'
...@@ -9,42 +9,30 @@ describe('dev-output', () => { ...@@ -9,42 +9,30 @@ describe('dev-output', () => {
}) })
it('shows Cache Components indicator when enabled', async () => { it('shows Cache Components indicator when enabled', async () => {
const preamble = getPreambleOutput(next.cliOutput) await next.fetch('/')
await retry(async () => {
if (cacheComponentsEnabled) { const output = next.cliOutput
if (isTurbopack) {
expect(preamble).toContain('Next.js') if (cacheComponentsEnabled) {
expect(preamble).toContain('Turbopack') if (isTurbopack) {
expect(preamble).toContain('Cache Components') expect(output).toContain('Next.js')
} else { expect(output).toContain('Turbopack')
expect(preamble).toContain('Next.js') expect(output).toContain('Cache Components')
expect(preamble).toContain('webpack') } else {
expect(preamble).toContain('Cache Components') expect(output).toContain('Next.js')
} expect(output).toContain('webpack')
} else { expect(output).toContain('Cache Components')
// When cache components env is not set, should not show the indicator }
expect(preamble).toContain('Next.js')
if (isTurbopack) {
expect(preamble).toContain('Turbopack')
} else { } else {
expect(preamble).toContain('webpack') // When cache components env is not set, should not show the indicator
expect(output).toContain('Next.js')
if (isTurbopack) {
expect(output).toContain('Turbopack')
} else {
expect(output).toContain('webpack')
}
expect(output).not.toContain('Cache Components')
} }
expect(preamble).not.toContain('Cache Components') })
}
}) })
}) })
function getPreambleOutput(cliOutput: string): string {
const lines: string[] = []
for (const line of cliOutput.split('\n')) {
// Capture lines up to and including the "Local:" line
lines.push(line.replace(nextVersion, 'x.y.z'))
if (line.includes('Local:')) {
break
}
}
return lines.join('\n').trim()
}
...@@ -7,8 +7,10 @@ describe('isolated-dev-build', () => { ...@@ -7,8 +7,10 @@ describe('isolated-dev-build', () => {
}) })
it('should create dev artifacts in .next/dev/ directory', async () => { it('should create dev artifacts in .next/dev/ directory', async () => {
expect(await next.hasFile('.next/dev')).toBe(true) await retry(async () => {
expect(await next.hasFile('.next/server')).toBe(false) expect(await next.hasFile('.next/dev')).toBe(true)
expect(await next.hasFile('.next/server')).toBe(false)
})
}) })
it('should work with HMR', async () => { it('should work with HMR', async () => {
......
...@@ -57,7 +57,7 @@ describe('server-components-hmr-cache', () => { ...@@ -57,7 +57,7 @@ describe('server-components-hmr-cache', () => {
it('should use cached fetch calls for fast refresh requests', async () => { it('should use cached fetch calls for fast refresh requests', async () => {
const browser = await next.browser(`/${runtime}`) const browser = await next.browser(`/${runtime}`)
const valueBeforePatch = getLoggedAfterValue() const valueBeforePatch = await retry(() => getLoggedAfterValue())
cliOutputLength = next.cliOutput.length cliOutputLength = next.cliOutput.length
await next.patchFile( await next.patchFile(
...@@ -70,7 +70,7 @@ describe('server-components-hmr-cache', () => { ...@@ -70,7 +70,7 @@ describe('server-components-hmr-cache', () => {
// TODO: remove custom duration in case we increase the default. // TODO: remove custom duration in case we increase the default.
}, 5000) }, 5000)
const valueAfterPatch = getLoggedAfterValue() const valueAfterPatch = await retry(() => getLoggedAfterValue())
expect(valueBeforePatch).toEqual(valueAfterPatch) expect(valueBeforePatch).toEqual(valueAfterPatch)
} }
) )
...@@ -148,6 +148,8 @@ describe('server-components-hmr-cache', () => { ...@@ -148,6 +148,8 @@ describe('server-components-hmr-cache', () => {
describe('with experimental.serverComponentsHmrCache disabled', () => { describe('with experimental.serverComponentsHmrCache disabled', () => {
beforeAll(async () => { beforeAll(async () => {
// Wait for server to be ready
await next.fetch('/404')
await next.patchFile('next.config.js', (content) => await next.patchFile('next.config.js', (content) =>
content.replace( content.replace(
'// serverComponentsHmrCache: false,', '// serverComponentsHmrCache: false,',
......
...@@ -6,7 +6,7 @@ describe('next start without next build', () => { ...@@ -6,7 +6,7 @@ describe('next start without next build', () => {
files: __dirname, files: __dirname,
skipStart: true, skipStart: true,
startCommand: `pnpm next start`, startCommand: `pnpm next start`,
serverReadyPattern: /✓ Starting.../, serverReadyPattern: /Local:/,
}) })
await next.start() await next.start()
......
...@@ -10,9 +10,11 @@ describe('app-dir with middleware', () => { ...@@ -10,9 +10,11 @@ describe('app-dir with middleware', () => {
}) })
it('should warn when deprecated middleware file is used', async () => { it('should warn when deprecated middleware file is used', async () => {
expect(next.cliOutput).toContain( await retry(async () => {
'The "middleware" file convention is deprecated. Please use "proxy" instead.' expect(next.cliOutput).toContain(
) 'The "middleware" file convention is deprecated. Please use "proxy" instead.'
)
})
}) })
it('should filter correctly after middleware rewrite', async () => { it('should filter correctly after middleware rewrite', async () => {
......
import { isNextDev, nextTestSetup } from 'e2e-utils' import { isNextDev, nextTestSetup } from 'e2e-utils'
import { getPrerenderOutput } from './utils' import { getPrerenderOutput } from './utils'
import stripAnsi from 'strip-ansi' import { retry } from 'next-test-utils'
describe('Cache Components Errors', () => { describe('Cache Components Errors', () => {
const { next, isTurbopack, isNextStart, skipped } = nextTestSetup({ const { next, isTurbopack, isNextStart, skipped } = nextTestSetup({
...@@ -32,16 +32,19 @@ describe('Cache Components Errors', () => { ...@@ -32,16 +32,19 @@ describe('Cache Components Errors', () => {
describe('Console Patching', () => { describe('Console Patching', () => {
if (isNextDev) { if (isNextDev) {
it('does not warn about sync IO if console.log is patched to call new Date() internally', async () => { it('does not warn about sync IO if console.log is patched to call new Date() internally', async () => {
await next.browser('/') await next.fetch('/404')
let output = stripAnsi(next.cliOutput)
// Wait for after 404 is rendered to the console.
await retry(async () => {
expect(next.cliOutput).toContain('GET /404 404')
})
// trim off Next.js's startup logs const from = next.cliOutput.length
const compilationMarker = /Ready in.*(\n.*Compiling.*)?/
expect(output).toMatch(compilationMarker) await next.browser('/')
const match = compilationMarker.exec(output)
output = output.slice(match.index + match[0].length).trim()
// trim off any logs after the HTTP request finished // trim off any logs after the HTTP request finished
const output = next.cliOutput.slice(from)
expect(output).toContain('GET / 200') expect(output).toContain('GET / 200')
const snapshot = output.slice(0, output.indexOf('GET / 200')).trim() const snapshot = output.slice(0, output.indexOf('GET / 200')).trim()
......
...@@ -12,6 +12,8 @@ describe('Cache Components Errors', () => { ...@@ -12,6 +12,8 @@ describe('Cache Components Errors', () => {
describe('Warning for Bypassing Caches in Dev', () => { describe('Warning for Bypassing Caches in Dev', () => {
if (isNextDev) { if (isNextDev) {
it('warns if you render with cache-control: no-cache in dev on initial page load', async () => { it('warns if you render with cache-control: no-cache in dev on initial page load', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length const from = next.cliOutput.length
await next.fetch('/', { await next.fetch('/', {
...@@ -26,6 +28,8 @@ describe('Cache Components Errors', () => { ...@@ -26,6 +28,8 @@ describe('Cache Components Errors', () => {
}) })
it('warns if you render with cache-control: no-cache in dev on client navigation', async () => { it('warns if you render with cache-control: no-cache in dev on client navigation', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length const from = next.cliOutput.length
await next.fetch('/other', { await next.fetch('/other', {
...@@ -40,6 +44,8 @@ describe('Cache Components Errors', () => { ...@@ -40,6 +44,8 @@ describe('Cache Components Errors', () => {
}) })
it('does not warn if you render without cache-control: no-cache in dev on initial page load', async () => { it('does not warn if you render without cache-control: no-cache in dev on initial page load', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length const from = next.cliOutput.length
await next.fetch('/') await next.fetch('/')
...@@ -50,6 +56,8 @@ describe('Cache Components Errors', () => { ...@@ -50,6 +56,8 @@ describe('Cache Components Errors', () => {
}) })
it('does not warn if you render without cache-control: no-cache in dev on client navigation', async () => { it('does not warn if you render without cache-control: no-cache in dev on client navigation', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length const from = next.cliOutput.length
await next.fetch('/', { await next.fetch('/', {
...@@ -62,6 +70,8 @@ describe('Cache Components Errors', () => { ...@@ -62,6 +70,8 @@ describe('Cache Components Errors', () => {
}) })
} else { } else {
it('does not warn if you render with cache-control: no-cache in dev on initial page load', async () => { it('does not warn if you render with cache-control: no-cache in dev on initial page load', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length const from = next.cliOutput.length
await next.fetch('/', { await next.fetch('/', {
...@@ -74,6 +84,8 @@ describe('Cache Components Errors', () => { ...@@ -74,6 +84,8 @@ describe('Cache Components Errors', () => {
}) })
it('does not warn if you render with cache-control: no-cache in dev on client navigation', async () => { it('does not warn if you render with cache-control: no-cache in dev on client navigation', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length const from = next.cliOutput.length
await next.fetch('/', { await next.fetch('/', {
...@@ -86,6 +98,8 @@ describe('Cache Components Errors', () => { ...@@ -86,6 +98,8 @@ describe('Cache Components Errors', () => {
}) })
it('does not warn if you render without cache-control: no-cache in dev on initial page load in start', async () => { it('does not warn if you render without cache-control: no-cache in dev on initial page load in start', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length const from = next.cliOutput.length
await next.fetch('/') await next.fetch('/')
...@@ -96,6 +110,8 @@ describe('Cache Components Errors', () => { ...@@ -96,6 +110,8 @@ describe('Cache Components Errors', () => {
}) })
it('does not warn if you render without cache-control: no-cache in dev on client navigation in start', async () => { it('does not warn if you render without cache-control: no-cache in dev on client navigation in start', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length const from = next.cliOutput.length
await next.fetch('/', { await next.fetch('/', {
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
// @ts-ignore // @ts-ignore
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import { retry } from 'next-test-utils'
const { i18n } = require('./next.config') const { i18n } = require('./next.config')
...@@ -53,9 +54,11 @@ describe('i18n-hybrid', () => { ...@@ -53,9 +54,11 @@ describe('i18n-hybrid', () => {
}) })
it('should warn about i18n in app dir', async () => { it('should warn about i18n in app dir', async () => {
expect(next.cliOutput).toContain( await retry(async () => {
'i18n configuration in next.config.js is unsupported in App Router.' expect(next.cliOutput).toContain(
) 'i18n configuration in next.config.js is unsupported in App Router.'
)
})
}) })
it.each(urls.filter((url) => !url.expected))( it.each(urls.filter((url) => !url.expected))(
......
...@@ -11,7 +11,9 @@ describe('instrumentation-order', () => { ...@@ -11,7 +11,9 @@ describe('instrumentation-order', () => {
await next.fetch('/') await next.fetch('/')
await retry(async () => { await retry(async () => {
const serverLog = next.cliOutput.split('Starting...')[1] // `next.cliOutput` includes both `next build` and `next start` in the production test run
// Because of that we have to split the output by `Ready in` and get the second part only
const serverLog = next.cliOutput.split('Ready in')[1]
const cliOutputLines = serverLog.split('\n') const cliOutputLines = serverLog.split('\n')
const ORDERED_LOGS = [ const ORDERED_LOGS = [
......
...@@ -67,7 +67,8 @@ describe('log-file', () => { ...@@ -67,7 +67,8 @@ describe('log-file', () => {
return normalizeLogContent(newContent) return normalizeLogContent(newContent)
} }
beforeEach(() => { beforeEach(async () => {
await next.fetch('/404')
// Reset log tracking at the start of each test to only capture new logs // Reset log tracking at the start of each test to only capture new logs
previousLogContent = readLogFile() previousLogContent = readLogFile()
}) })
......
import { join } from 'path' import { join } from 'path'
import { FileRef, nextTestSetup } from 'e2e-utils' import { FileRef, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('multiple-lockfiles', () => { describe('multiple-lockfiles', () => {
const { next, skipped, isTurbopack } = nextTestSetup({ const { next, skipped, isTurbopack } = nextTestSetup({
...@@ -23,18 +24,20 @@ describe('multiple-lockfiles', () => { ...@@ -23,18 +24,20 @@ describe('multiple-lockfiles', () => {
} }
it('should have multiple lockfiles warnings', async () => { it('should have multiple lockfiles warnings', async () => {
expect(next.cliOutput).toMatch( await retry(async () => {
/We detected multiple lockfiles and selected the directory of .+ as the root directory\./
)
if (isTurbopack) {
expect(next.cliOutput).toMatch(
/To silence this warning, set `turbopack\.root` in your Next\.js config, or consider removing one of the lockfiles if it's not needed\./
)
} else {
expect(next.cliOutput).toMatch( expect(next.cliOutput).toMatch(
/To silence this warning, set `outputFileTracingRoot` in your Next\.js config, or consider removing one of the lockfiles if it's not needed\./ /We detected multiple lockfiles and selected the directory of .+ as the root directory\./
) )
}
if (isTurbopack) {
expect(next.cliOutput).toMatch(
/To silence this warning, set `turbopack\.root` in your Next\.js config, or consider removing one of the lockfiles if it's not needed\./
)
} else {
expect(next.cliOutput).toMatch(
/To silence this warning, set `outputFileTracingRoot` in your Next\.js config, or consider removing one of the lockfiles if it's not needed\./
)
}
})
}) })
}) })
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('proxy-with-middleware', () => { describe('proxy-with-middleware', () => {
const { next, isNextDev, skipped } = nextTestSetup({ const { next, isNextDev, skipped } = nextTestSetup({
...@@ -17,7 +18,9 @@ describe('proxy-with-middleware', () => { ...@@ -17,7 +18,9 @@ describe('proxy-with-middleware', () => {
if (isNextDev) { if (isNextDev) {
await next.start().catch(() => {}) await next.start().catch(() => {})
expect(next.cliOutput).toContain(message) await retry(async () => {
expect(next.cliOutput).toContain(message)
})
} else { } else {
const { cliOutput } = await next.build() const { cliOutput } = await next.build()
expect(cliOutput).toContain(message) expect(cliOutput).toContain(message)
......
...@@ -18,6 +18,7 @@ describe('typed-routes-validator', () => { ...@@ -18,6 +18,7 @@ describe('typed-routes-validator', () => {
it('should generate route validation correctly', async () => { it('should generate route validation correctly', async () => {
if (isNextDev) { if (isNextDev) {
await next.start() await next.start()
await next.fetch('/')
} else { } else {
await next.build() await next.build()
} }
......
...@@ -49,9 +49,11 @@ describe('Build Activity Indicator', () => { ...@@ -49,9 +49,11 @@ describe('Build Activity Indicator', () => {
expect(result.exitCode).toBe(1) expect(result.exitCode).toBe(1)
} }
expect(next.cliOutput).toContain( await retry(async () => {
`Invalid "devIndicator.position" provided, expected one of top-left, top-right, bottom-left, bottom-right, received ttop-leff` expect(next.cliOutput).toContain(
) `Invalid "devIndicator.position" provided, expected one of top-left, top-right, bottom-left, bottom-right, received ttop-leff`
)
})
}) })
}) })
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import path from 'path' import path from 'path'
describe('deprecation-warnings', () => { describe('deprecation-warnings', () => {
...@@ -27,28 +28,32 @@ describe('deprecation-warnings', () => { ...@@ -27,28 +28,32 @@ describe('deprecation-warnings', () => {
it('should emit deprecation warnings for explicitly configured deprecated options', async () => { it('should emit deprecation warnings for explicitly configured deprecated options', async () => {
await next.start() await next.start()
const logs = next.cliOutput await retry(async () => {
const logs = next.cliOutput
// Should warn about experimental.instrumentationHook // Should warn about experimental.instrumentationHook
expect(logs).toContain('experimental.instrumentationHook') expect(logs).toContain('experimental.instrumentationHook')
expect(logs).toContain('no longer needed') expect(logs).toContain('no longer needed')
// Should warn about middleware config options // Should warn about middleware config options
expect(logs).toContain('experimental.middlewarePrefetch') expect(logs).toContain('experimental.middlewarePrefetch')
expect(logs).toContain('Please use `experimental.proxyPrefetch` instead') expect(logs).toContain(
'Please use `experimental.proxyPrefetch` instead'
)
expect(logs).toContain('experimental.middlewareClientMaxBodySize') expect(logs).toContain('experimental.middlewareClientMaxBodySize')
expect(logs).toContain( expect(logs).toContain(
'Please use `experimental.proxyClientMaxBodySize` instead' 'Please use `experimental.proxyClientMaxBodySize` instead'
) )
expect(logs).toContain('experimental.externalMiddlewareRewritesResolve') expect(logs).toContain('experimental.externalMiddlewareRewritesResolve')
expect(logs).toContain( expect(logs).toContain(
'Please use `experimental.externalProxyRewritesResolve` instead' 'Please use `experimental.externalProxyRewritesResolve` instead'
) )
expect(logs).toContain('skipMiddlewareUrlNormalize') expect(logs).toContain('skipMiddlewareUrlNormalize')
expect(logs).toContain('Please use `skipProxyUrlNormalize` instead') expect(logs).toContain('Please use `skipProxyUrlNormalize` instead')
})
}) })
}) })
}) })
...@@ -23,6 +23,9 @@ describe('next-phase', () => { ...@@ -23,6 +23,9 @@ describe('next-phase', () => {
if (skipped) return if (skipped) return
it('should render page with next phase correctly', async () => { it('should render page with next phase correctly', async () => {
await next.fetch('/')
await next.fetch('/foo')
const phases = { const phases = {
dev: 'phase-development-server', dev: 'phase-development-server',
build: 'phase-production-build', build: 'phase-production-build',
...@@ -34,9 +37,6 @@ describe('next-phase', () => { ...@@ -34,9 +37,6 @@ describe('next-phase', () => {
expect(next.cliOutput).toContain(currentPhase) expect(next.cliOutput).toContain(currentPhase)
expect(next.cliOutput).not.toContain(nonExistedPhase) expect(next.cliOutput).not.toContain(nonExistedPhase)
await next.fetch('/')
await next.fetch('/foo')
if (isNextDev) { if (isNextDev) {
expect(next.cliOutput).not.toContain(phases.start) expect(next.cliOutput).not.toContain(phases.start)
} else { } else {
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
const CASES = [ const CASES = [
[ [
...@@ -47,8 +48,10 @@ describe('persistent-caching-migration', () => { ...@@ -47,8 +48,10 @@ describe('persistent-caching-migration', () => {
}) })
} else { } else {
it('error on old option in dev', async () => { it('error on old option in dev', async () => {
await expect(next.start()).toReject() await next.start()
expect(next.cliOutput).toContain(error) await retry(async () => {
expect(next.cliOutput).toContain(error)
})
}) })
} }
}) })
......
...@@ -27,6 +27,8 @@ async function collectStdoutFromDev(appDir) { ...@@ -27,6 +27,8 @@ async function collectStdoutFromDev(appDir) {
stdout += msg stdout += msg
}, },
}) })
await fetch(`http://localhost:${port}`)
return stdout return stdout
} }
...@@ -114,7 +116,7 @@ describe('Config Experimental Warning', () => { ...@@ -114,7 +116,7 @@ describe('Config Experimental Warning', () => {
configFile.write(` configFile.write(`
module.exports = (phase) => ({ module.exports = (phase) => ({
experimental: { experimental: {
workerThreads: false workerThreads: false,
// We enable this by default in CI // We enable this by default in CI
strictRouteTypes: false, strictRouteTypes: false,
} }
...@@ -253,7 +255,7 @@ describe('Config Experimental Warning', () => { ...@@ -253,7 +255,7 @@ describe('Config Experimental Warning', () => {
}, },
}) })
await retry(() => { await retry(async () => {
const cliOutput = stripAnsi(stdout) const cliOutput = stripAnsi(stdout)
const cliOutputErr = stripAnsi(stderr) const cliOutputErr = stripAnsi(stderr)
expect(cliOutput).not.toContain(experimentalHeader) expect(cliOutput).not.toContain(experimentalHeader)
......
...@@ -8,6 +8,7 @@ import { ...@@ -8,6 +8,7 @@ import {
getRedboxHeader, getRedboxHeader,
killApp, killApp,
launchApp, launchApp,
retry,
} from 'next-test-utils' } from 'next-test-utils'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { join } from 'path' import { join } from 'path'
...@@ -17,7 +18,7 @@ import type { Response } from 'node-fetch' ...@@ -17,7 +18,7 @@ import type { Response } from 'node-fetch'
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const nextConfig = new File(join(appDir, 'next.config.js')) const nextConfig = new File(join(appDir, 'next.config.js'))
let app let app
const runDev = async (config: any) => { const runDev = async (config: any, shouldWaitForReady = true) => {
await nextConfig.write(`module.exports = ${JSON.stringify(config)}`) await nextConfig.write(`module.exports = ${JSON.stringify(config)}`)
const port = await findPort() const port = await findPort()
const obj = { port, stdout: '', stderr: '' } const obj = { port, stdout: '', stderr: '' }
...@@ -31,6 +32,9 @@ const runDev = async (config: any) => { ...@@ -31,6 +32,9 @@ const runDev = async (config: any) => {
obj.stderr += msg || '' obj.stderr += msg || ''
}, },
}) })
if (shouldWaitForReady) {
await fetch(`http://localhost:${port}`)
}
return obj return obj
} }
...@@ -53,16 +57,22 @@ describe('config-output-export', () => { ...@@ -53,16 +57,22 @@ describe('config-output-export', () => {
}) })
it('should error with "i18n" config', async () => { it('should error with "i18n" config', async () => {
const { stderr } = await runDev({ const data = await runDev(
output: 'export', {
i18n: { output: 'export',
locales: ['en'], i18n: {
defaultLocale: 'en', locales: ['en'],
defaultLocale: 'en',
},
}, },
}) false
expect(stderr).toContain(
'Specified "i18n" cannot be used with "output: export".'
) )
await retry(() => {
expect(data.stderr).toContain(
'Specified "i18n" cannot be used with "output: export".'
)
})
}) })
describe('when hasNextSupport = false', () => { describe('when hasNextSupport = false', () => {
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
import fs from 'fs-extra' import fs from 'fs-extra'
import { join } from 'path' import { join } from 'path'
import { launchApp, findPort, nextBuild } from 'next-test-utils' import { launchApp, findPort, nextBuild, retry } from 'next-test-utils'
let appDir = join(__dirname, '..') let appDir = join(__dirname, '..')
const nextConfigPath = join(appDir, 'next.config.js') const nextConfigPath = join(appDir, 'next.config.js')
...@@ -33,11 +33,13 @@ const runTests = () => { ...@@ -33,11 +33,13 @@ const runTests = () => {
], ],
'headers' 'headers'
) )
const stderr = await getStderr() await retry(async () => {
const stderr = await getStderr()
expect(stderr).toContain( expect(stderr).toContain(
'`headers` field cannot be empty for route {"source":"/:path*"' '`headers` field cannot be empty for route {"source":"/:path*"'
) )
})
}) })
it('should error when source and destination length is exceeded', async () => { it('should error when source and destination length is exceeded', async () => {
...@@ -137,61 +139,64 @@ const runTests = () => { ...@@ -137,61 +139,64 @@ const runTests = () => {
], ],
'redirects' 'redirects'
) )
const stderr = await getStderr()
expect(stderr).toContain(
`\`destination\` is missing for route {"source":"/hello","permanent":false}`
)
expect(stderr).toContain(
`\`source\` is not a string for route {"source":123,"destination":"/another","permanent":false}`
)
expect(stderr).toContain(
`\`statusCode\` is not undefined or valid statusCode for route {"source":"/hello","destination":"/another","statusCode":"301"}`
)
expect(stderr).toContain(
`\`statusCode\` is not undefined or valid statusCode for route {"source":"/hello","destination":"/another","statusCode":404}`
)
expect(stderr).toContain(
`\`permanent\` is not set to \`true\` or \`false\` for route {"source":"/hello","destination":"/another","permanent":"yes"}`
)
expect(stderr).toContain(
`\`destination\` has unnamed params :0 for route {"source":"/hello/world/(.*)","destination":"/:0","permanent":true}`
)
expect(stderr).toContain(
`The route null is not a valid object with \`source\` and \`destination\``
)
expect(stderr).toContain(
`The route "string" is not a valid object with \`source\` and \`destination\``
)
expect(stderr).toContain('Invalid `has` item:')
expect(stderr).toContain(
`invalid type "cookiee" for {"type":"cookiee","key":"loggedIn"}`
)
expect(stderr).toContain(
`invalid \`has\` item found for route {"source":"/hello","destination":"/another","has":[{"type":"cookiee","key":"loggedIn"}],"permanent":false}`
)
expect(stderr).toContain('Invalid `has` items:')
expect(stderr).toContain(
`invalid type "headerr", invalid key "undefined" for {"type":"headerr"}`
)
expect(stderr).toContain(
`invalid type "queryr" for {"type":"queryr","key":"hello"}`
)
expect(stderr).toContain(
`invalid \`has\` items found for route {"source":"/hello","destination":"/another","permanent":false,"has":[{"type":"headerr"},{"type":"queryr","key":"hello"}]}`
)
expect(stderr).toContain(`Valid \`has\` object shape is {`)
expect(stderr).toContain('Invalid redirects found') await retry(async () => {
const stderr = await getStderr()
expect(stderr).toContain(
`\`destination\` is missing for route {"source":"/hello","permanent":false}`
)
expect(stderr).toContain(
`\`source\` is not a string for route {"source":123,"destination":"/another","permanent":false}`
)
expect(stderr).toContain(
`\`statusCode\` is not undefined or valid statusCode for route {"source":"/hello","destination":"/another","statusCode":"301"}`
)
expect(stderr).toContain(
`\`statusCode\` is not undefined or valid statusCode for route {"source":"/hello","destination":"/another","statusCode":404}`
)
expect(stderr).toContain(
`\`permanent\` is not set to \`true\` or \`false\` for route {"source":"/hello","destination":"/another","permanent":"yes"}`
)
expect(stderr).toContain(
`\`destination\` has unnamed params :0 for route {"source":"/hello/world/(.*)","destination":"/:0","permanent":true}`
)
expect(stderr).toContain(
`The route null is not a valid object with \`source\` and \`destination\``
)
expect(stderr).toContain(
`The route "string" is not a valid object with \`source\` and \`destination\``
)
expect(stderr).toContain('Invalid `has` item:')
expect(stderr).toContain(
`invalid type "cookiee" for {"type":"cookiee","key":"loggedIn"}`
)
expect(stderr).toContain(
`invalid \`has\` item found for route {"source":"/hello","destination":"/another","has":[{"type":"cookiee","key":"loggedIn"}],"permanent":false}`
)
expect(stderr).toContain('Invalid `has` items:')
expect(stderr).toContain(
`invalid type "headerr", invalid key "undefined" for {"type":"headerr"}`
)
expect(stderr).toContain(
`invalid type "queryr" for {"type":"queryr","key":"hello"}`
)
expect(stderr).toContain(
`invalid \`has\` items found for route {"source":"/hello","destination":"/another","permanent":false,"has":[{"type":"headerr"},{"type":"queryr","key":"hello"}]}`
)
expect(stderr).toContain(`Valid \`has\` object shape is {`)
expect(stderr).toContain('Invalid redirects found')
})
}) })
it('should error during next build for invalid rewrites', async () => { it('should error during next build for invalid rewrites', async () => {
......
...@@ -65,6 +65,7 @@ describe('TypeScript Image Component', () => { ...@@ -65,6 +65,7 @@ describe('TypeScript Image Component', () => {
onStdout: handleOutput, onStdout: handleOutput,
onStderr: handleOutput, onStderr: handleOutput,
}) })
await fetch(`http://localhost:${appPort}`)
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
...@@ -96,7 +97,9 @@ describe('TypeScript Image Component', () => { ...@@ -96,7 +97,9 @@ describe('TypeScript Image Component', () => {
nextConfig, nextConfig,
content.replace('// disableStaticImages', 'disableStaticImages') content.replace('// disableStaticImages', 'disableStaticImages')
) )
const app = await launchApp(appDir, await findPort()) const port = await findPort()
const app = await launchApp(appDir, port)
await fetch(`http://localhost:${port}`)
await killApp(app) await killApp(app)
await fs.writeFile(nextConfig, content) await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8') const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8')
......
...@@ -65,6 +65,7 @@ describe('TypeScript Image Component', () => { ...@@ -65,6 +65,7 @@ describe('TypeScript Image Component', () => {
onStdout: handleOutput, onStdout: handleOutput,
onStderr: handleOutput, onStderr: handleOutput,
}) })
await fetch(`http://localhost:${appPort}`)
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
...@@ -95,7 +96,9 @@ describe('TypeScript Image Component', () => { ...@@ -95,7 +96,9 @@ describe('TypeScript Image Component', () => {
nextConfig, nextConfig,
content.replace('// disableStaticImages', 'disableStaticImages') content.replace('// disableStaticImages', 'disableStaticImages')
) )
const app = await launchApp(appDir, await findPort()) const port = await findPort()
const app = await launchApp(appDir, port)
await fetch(`http://localhost:${port}`)
await killApp(app) await killApp(app)
await fs.writeFile(nextConfig, content) await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8') const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8')
......
...@@ -42,6 +42,7 @@ describe('TypeScript App Type Declarations', () => { ...@@ -42,6 +42,7 @@ describe('TypeScript App Type Declarations', () => {
let app let app
try { try {
app = await launchApp(appDir, appPort, {}) app = await launchApp(appDir, appPort, {})
await fetch(`http://localhost:${appPort}`)
const content = await fs.readFile(appTypeDeclarations, 'utf8') const content = await fs.readFile(appTypeDeclarations, 'utf8')
expect(content).toEqual(prevContent) expect(content).toEqual(prevContent)
} finally { } finally {
...@@ -60,6 +61,7 @@ describe('TypeScript App Type Declarations', () => { ...@@ -60,6 +61,7 @@ describe('TypeScript App Type Declarations', () => {
let app let app
try { try {
app = await launchApp(appDir, appPort, {}) app = await launchApp(appDir, appPort, {})
await fetch(`http://localhost:${appPort}`)
const content = await fs.readFile(appTypeDeclarations, 'utf8') const content = await fs.readFile(appTypeDeclarations, 'utf8')
expect(content).toEqual(prevContent) expect(content).toEqual(prevContent)
} finally { } finally {
......
/* eslint-env jest */ /* eslint-env jest */
import { join } from 'path' import { join } from 'path'
import { launchApp, findPort, nextBuild } from 'next-test-utils' import { launchApp, findPort, nextBuild, retry } from 'next-test-utils'
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const expectedErr = const expectedErr =
...@@ -33,7 +33,9 @@ const expectedErr = ...@@ -33,7 +33,9 @@ const expectedErr =
}, },
}) })
expect(output).toMatch(expectedErr) await retry(async () => {
expect(output).toMatch(expectedErr)
})
}) })
} }
) )
...@@ -26,7 +26,8 @@ describe('build-output-prerender', () => { ...@@ -26,7 +26,8 @@ describe('build-output-prerender', () => {
`) `)
} else { } else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (webpack, Cache Components) "▲ Next.js x.y.z (webpack)
- Cache Components enabled
- Experiments (use with caution): - Experiments (use with caution):
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)" ✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)"
`) `)
...@@ -48,7 +49,8 @@ describe('build-output-prerender', () => { ...@@ -48,7 +49,8 @@ describe('build-output-prerender', () => {
} else { } else {
if (isTurbopack) { if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (Turbopack, Cache Components) "▲ Next.js x.y.z (Turbopack)
- Cache Components enabled
- Experiments (use with caution): - Experiments (use with caution):
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)" ✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)"
`) `)
...@@ -58,7 +60,8 @@ describe('build-output-prerender', () => { ...@@ -58,7 +60,8 @@ describe('build-output-prerender', () => {
`) `)
} else { } else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (webpack, Cache Components) "▲ Next.js x.y.z (webpack)
- Cache Components enabled
- Experiments (use with caution): - Experiments (use with caution):
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)" ✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)"
`) `)
...@@ -122,7 +125,8 @@ describe('build-output-prerender', () => { ...@@ -122,7 +125,8 @@ describe('build-output-prerender', () => {
} else { } else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production. "⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (webpack, Cache Components) ▲ Next.js x.y.z (webpack)
- Cache Components enabled
- Experiments (use with caution): - Experiments (use with caution):
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`) ⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`) ✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)
...@@ -156,7 +160,8 @@ describe('build-output-prerender', () => { ...@@ -156,7 +160,8 @@ describe('build-output-prerender', () => {
if (isTurbopack) { if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production. "⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (Turbopack, Cache Components) ▲ Next.js x.y.z (Turbopack)
- Cache Components enabled
- Experiments (use with caution): - Experiments (use with caution):
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`) ⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`) ✓ serverSourceMaps (enabled by \`--debug-prerender\`)
...@@ -175,7 +180,8 @@ describe('build-output-prerender', () => { ...@@ -175,7 +180,8 @@ describe('build-output-prerender', () => {
} else { } else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production. "⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (webpack, Cache Components) ▲ Next.js x.y.z (webpack)
- Cache Components enabled
- Experiments (use with caution): - Experiments (use with caution):
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`) ⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`) ⨯ serverMinification (disabled by \`--debug-prerender\`)
...@@ -266,7 +272,8 @@ describe('build-output-prerender', () => { ...@@ -266,7 +272,8 @@ describe('build-output-prerender', () => {
`) `)
} else { } else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (webpack, Cache Components) "▲ Next.js x.y.z (webpack)
- Cache Components enabled
- Experiments (use with caution): - Experiments (use with caution):
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)" ✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)"
`) `)
...@@ -331,7 +338,8 @@ describe('build-output-prerender', () => { ...@@ -331,7 +338,8 @@ describe('build-output-prerender', () => {
} else { } else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(` expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production. "⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (webpack, Cache Components) ▲ Next.js x.y.z (webpack)
- Cache Components enabled
- Experiments (use with caution): - Experiments (use with caution):
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`) ⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`) ✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)
......
...@@ -100,7 +100,7 @@ describe('Graceful Shutdown', () => { ...@@ -100,7 +100,7 @@ describe('Graceful Shutdown', () => {
appPort = await findPort() appPort = await findPort()
app = await initNextServerScript( app = await initNextServerScript(
serverFile, serverFile,
/✓ Ready in \d+m?s/, /✓ Ready in/,
{ {
...process.env, ...process.env,
NEXT_EXIT_TIMEOUT_MS: '10', NEXT_EXIT_TIMEOUT_MS: '10',
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment