Unverified Commit a510f2f2 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Add no-adhoc-sleep lint rule and migrate ad-hoc sleep promises

Rebase the change from #96841 onto the current canary branch and preserve canary’s segment-cache import cleanup while adopting the canonical wait helper.
Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent bd6bdd1a
......@@ -199,6 +199,12 @@ tail -5 /tmp/test-output.log # Summary
await new Promise((resolve) => setTimeout(resolve, 1000))
```
When a fixed delay really is what you want, use `waitFor(ms)` from
`next-test-utils` rather than hand-rolling the promise. The
`@next/internal/no-adhoc-sleep` lint rule enforces this and can autofix it
(`pnpm lint-eslint . --fix`); shipped code in `packages/next/src` uses
`wait(ms)` from `src/lib/wait.ts` instead.
- **Do NOT use `check()` - it is deprecated. Use `retry()` + `expect()` instead**
```typescript
......
......@@ -439,6 +439,37 @@ export default defineConfig([
'jsdoc/no-undefined-types': 'error',
},
},
{
// Shipped runtime code sleeps via `wait()` from `src/lib/wait.ts`. The
// helper's own module is exempted by the rule itself.
files: ['packages/next/src/**/*.ts', 'packages/next/src/**/*.tsx'],
ignores: ['**/*.test.ts', '**/*.test.tsx'],
plugins: {
'@next/internal': nextEslintPluginInternal,
},
rules: {
'@next/internal/no-adhoc-sleep': [
'error',
{ helper: 'wait', modulePath: 'packages/next/src/lib/wait' },
],
},
},
{
// Test files sleep via `waitFor()` from `next-test-utils`. Only test files
// are covered: fixture apps are compiled by `next build` and cannot
// resolve `next-test-utils`, which is a Jest-only module.
files: ['test/**/*.test.ts', 'test/**/*.test.tsx'],
ignores: ['test/tmp/**'],
plugins: {
'@next/internal': nextEslintPluginInternal,
},
rules: {
'@next/internal/no-adhoc-sleep': [
'error',
{ helper: 'waitFor', module: 'next-test-utils' },
],
},
},
{
files: [
'packages/next/src/server/**/*.js',
......
const path = require('path')
/**
* Resolve the module specifier used to import the canonical sleep helper into
* `filename`.
*
* - `module`: a bare specifier (e.g. `next-test-utils`), used verbatim.
* - `modulePath`: a repo-relative path (e.g. `packages/next/src/lib/wait`),
* turned into a relative specifier computed from the linted file.
*
* @param {{ module?: string, modulePath?: string }} options
* @param {string} filename absolute path of the file being linted
* @param {string} cwd
* @returns {string}
*/
function resolveSpecifier(options, filename, cwd) {
if (options.module) {
return options.module
}
const target = path.resolve(cwd, options.modulePath)
const relative = path
.relative(path.dirname(filename), target)
.split(path.sep)
.join('/')
return relative.startsWith('.') ? relative : `./${relative}`
}
/**
* Match `new Promise((resolve) => setTimeout(resolve, ms))` and its variants,
* and return the `ms` node. Returns `null` for anything that is not exactly a
* sleep, so that the autofix can never change behaviour:
*
* - `setTimeout(resolve)` has no delay, and the canonical helpers treat a
* non-number as a condition to poll, so it would never resolve.
* - `setTimeout(resolve, ms, arg)` forwards `arg` to `resolve`.
* - `setTimeout(() => resolve(value), ms)` resolves with a value.
* - an executor body that does anything else does more than sleep.
*
* @param {import('estree').NewExpression} node
* @returns {import('estree').Node | null}
*/
function getSleepDelay(node) {
if (node.callee.type !== 'Identifier' || node.callee.name !== 'Promise') {
return null
}
if (node.arguments.length !== 1) {
return null
}
const executor = node.arguments[0]
if (
executor.type !== 'ArrowFunctionExpression' &&
executor.type !== 'FunctionExpression'
) {
return null
}
if (
executor.params.length !== 1 ||
executor.params[0].type !== 'Identifier'
) {
return null
}
const resolveName = executor.params[0].name
let call = executor.body
if (call.type === 'BlockStatement') {
if (call.body.length !== 1) {
return null
}
const statement = call.body[0]
if (statement.type === 'ExpressionStatement') {
call = statement.expression
} else if (statement.type === 'ReturnStatement' && statement.argument) {
call = statement.argument
} else {
return null
}
}
if (call.type !== 'CallExpression') {
return null
}
if (call.callee.type !== 'Identifier' || call.callee.name !== 'setTimeout') {
return null
}
if (call.arguments.length !== 2) {
return null
}
const [callback, delay] = call.arguments
if (callback.type !== 'Identifier' || callback.name !== resolveName) {
return null
}
if (delay.type === 'SpreadElement') {
return null
}
return delay
}
/**
* @type {import('eslint').Rule.RuleModule}
*/
const plugin = {
name: 'no-adhoc-sleep',
meta: {
type: 'problem',
docs: {
description:
'Use the canonical sleep helper instead of hand-rolling `new Promise((resolve) => setTimeout(resolve, ms))`.',
recommended: true,
},
fixable: 'code',
schema: [
{
type: 'object',
properties: {
// Name of the canonical helper, e.g. `wait` or `waitFor`.
helper: { type: 'string' },
// Bare module specifier, e.g. `next-test-utils`.
module: { type: 'string' },
// Repo-relative path, e.g. `packages/next/src/lib/wait`.
modulePath: { type: 'string' },
},
additionalProperties: false,
},
],
messages: {
adhocSleep:
"Use `{{helper}}({{delay}})` from '{{module}}' instead of hand-rolling a sleep promise. If you are waiting for something to become true, prefer `retry()` — see AGENTS.md, 'Writing Tests'.",
adhocSleepShadowed:
'Use the canonical sleep helper instead of hand-rolling a sleep promise. `{{helper}}` is already bound to something else in this scope, so this cannot be fixed automatically: rename that binding first.',
adhocSleepComment:
"Use `{{helper}}({{delay}})` from '{{module}}' instead of hand-rolling a sleep promise. Not fixed automatically because the expression contains a comment that would be lost.",
},
},
create(context) {
const options = context.options[0] || {}
const helper = options.helper || 'wait'
const sourceCode = context.sourceCode
const filename = path.resolve(context.cwd, context.filename)
const specifier = resolveSpecifier(options, filename, context.cwd)
// The canonical helper's own module defines the helper with this very
// pattern, so it must not lint itself.
if (options.modulePath) {
const target = path.resolve(context.cwd, options.modulePath)
if (filename.replace(/\.[cm]?[jt]sx?$/, '') === target) {
return {}
}
}
/**
* Is `helper` bound, at `node`, to anything other than a *value* import of
* the canonical module? Walks the whole scope chain, so a function
* parameter or a block-local variable named `helper` counts too —
* rewriting inside such a scope would silently call that binding instead of
* the helper. A type-only import counts as well: it produces no runtime
* binding, and a second import with the same local name is invalid.
*/
function isShadowedAt(node) {
for (let scope = sourceCode.getScope(node); scope; scope = scope.upper) {
const variable = scope.set.get(helper)
if (!variable) {
continue
}
return !variable.defs.every(
(def) =>
def.type === 'ImportBinding' &&
def.parent.type === 'ImportDeclaration' &&
def.parent.source.value === specifier &&
def.parent.importKind !== 'type' &&
def.node.importKind !== 'type'
)
}
return false
}
// At most one report per pass may edit the import list, otherwise the
// fixes overlap and ESLint discards all but one of them.
let importFixQueued = false
/**
* The declaration a `{ helper }` specifier can be added to: a *value*
* import of the canonical module that is not a namespace import.
* `import def from '<module>'` is fine — it becomes
* `import def, { helper } from '<module>'`.
*
* Skipped, so that a fresh value import is inserted instead:
* - `import type { X } from '<module>'` — a specifier added there would
* stay type-only, leaving the call without a runtime binding.
* - `import * as ns from '<module>'` — `* as ns, { helper }` is a syntax
* error.
* - `import '<module>'` — a side-effect import has no specifier list to
* extend.
*/
function findHelperImport() {
return sourceCode.ast.body.find((statement) => {
if (
statement.type !== 'ImportDeclaration' ||
statement.source.value !== specifier ||
statement.importKind === 'type' ||
statement.specifiers.length === 0
) {
return false
}
return !statement.specifiers.some(
(specifierNode) => specifierNode.type === 'ImportNamespaceSpecifier'
)
})
}
return {
NewExpression(node) {
const delay = getSleepDelay(node)
if (!delay) {
return
}
const data = {
helper,
delay: sourceCode.getText(delay),
module: specifier,
}
if (isShadowedAt(node)) {
context.report({ node, messageId: 'adhocSleepShadowed', data })
return
}
// Rewriting would drop a comment that lives inside the expression.
if (sourceCode.getCommentsInside(node).length > 0) {
context.report({ node, messageId: 'adhocSleepComment', data })
return
}
context.report({
node,
messageId: 'adhocSleep',
data,
*fix(fixer) {
yield fixer.replaceText(node, `${helper}(${data.delay})`)
if (importFixQueued) {
return
}
const declaration = findHelperImport()
if (declaration) {
const alreadyImported = declaration.specifiers.some(
(specifierNode) =>
specifierNode.type === 'ImportSpecifier' &&
specifierNode.local.name === helper
)
if (alreadyImported) {
return
}
importFixQueued = true
const named = declaration.specifiers.filter(
(specifierNode) => specifierNode.type === 'ImportSpecifier'
)
if (named.length > 0) {
yield fixer.insertTextBefore(named[0], `${helper}, `)
} else {
// `import def from 'x'` -> `import def, { helper } from 'x'`
const last =
declaration.specifiers[declaration.specifiers.length - 1]
yield fixer.insertTextAfter(last, `, { ${helper} }`)
}
return
}
importFixQueued = true
const importLine = `import { ${helper} } from '${specifier}'`
const firstImport = sourceCode.ast.body.find(
(statement) => statement.type === 'ImportDeclaration'
)
if (firstImport) {
yield fixer.insertTextBefore(firstImport, `${importLine}\n`)
} else if (sourceCode.ast.body.length > 0) {
yield fixer.insertTextBefore(
sourceCode.ast.body[0],
`${importLine}\n\n`
)
}
},
})
},
}
},
}
module.exports = plugin
const typecheckedRequire = require('./eslint-typechecked-require')
const noAmbiguousJSX = require('./eslint-no-ambiguous-jsx')
const noAdhocSleep = require('./eslint-no-adhoc-sleep')
module.exports = {
rules: {
'no-adhoc-sleep': noAdhocSleep,
'no-ambiguous-jsx': noAmbiguousJSX,
'typechecked-require': typecheckedRequire,
},
......
import { wait } from '../lib/wait'
import fs from 'fs'
import nodePath from 'path'
import { bold, cyan } from '../lib/picocolors'
......@@ -176,7 +177,7 @@ export class Lockfile {
while (Date.now() - startMs < MAX_RETRY_MS) {
lockfile = Lockfile.tryAcquire(path, unlockOnExit, content)
if (lockfile !== undefined) break
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS))
await wait(RETRY_DELAY_MS)
}
if (lockfile === undefined) {
const isDev = processName === 'next dev'
......
import { wait } from '../lib/wait'
import path from 'path'
import { readLockfileContent, parseDevServerInfo } from '../build/lockfile'
import { getProjectDir } from '../lib/get-project-dir'
......@@ -118,9 +119,7 @@ async function discoverDevServerUrl(directory?: string): Promise<URL> {
return parseDevServerUrl(serverInfo.appUrl)
}
await new Promise((resolve) =>
setTimeout(resolve, DEV_SERVER_DISCOVERY_RETRY_MS)
)
await wait(DEV_SERVER_DISCOVERY_RETRY_MS)
}
return exitWithError(
......
import type { CacheNode, Segment } from '../../../shared/lib/app-router-types'
import type React from 'react'
import { wait } from '../../../lib/wait'
import {
PrefetchHint,
StaticAttemptHints,
......@@ -2470,9 +2471,7 @@ async function retryUpgradeableFallbackPrefetch(
fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell
): Promise<void> {
for (let attempt = 0; attempt < MAX_FALLBACK_RETRIES; attempt++) {
await new Promise<void>((resolve) =>
setTimeout(resolve, FALLBACK_RETRY_DELAY_MS)
)
await wait(FALLBACK_RETRY_DELAY_MS)
if (task.isCanceled) {
break
}
......
import { wait } from '../lib/wait'
import type {
ExportPagesInput,
ExportPageInput,
......@@ -514,7 +515,7 @@ export async function exportPages(
const maxDelay = 2000 // 2 seconds
const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay)
const jitter = Math.random() * 0.3 * delay // Add up to 30% random jitter
await new Promise((r) => setTimeout(r, delay + jitter))
await wait(delay + jitter)
}
}
......
import { wait } from './wait'
export type ScheduledFn<T = void> = () => T | PromiseLike<T>
export type SchedulerFn<T = void> = (cb: ScheduledFn<T>) => void
......@@ -57,7 +59,7 @@ export function atLeastOneTask() {
*/
export function waitAtLeastOneReactRenderTask(): Promise<void> {
if (process.env.NEXT_RUNTIME === 'edge') {
return new Promise((r) => setTimeout(r, 0))
return wait(0)
} else {
return new Promise((r) => setImmediate(r))
}
......
import { wait } from '../wait'
import path from 'path'
import { getFormattedDiagnostic } from './diagnosticFormatter'
import { getTypeScriptConfiguration } from './getTypeScriptConfiguration'
......@@ -195,7 +196,7 @@ export async function runTypeCheck(
)
// Make sure all stdout is flushed before we exit.
await new Promise((resolve) => setTimeout(resolve, 100))
await wait(100)
}
}
......
/**
* Wait for a given number of milliseconds and then resolve.
*
* This is the canonical sleep helper: prefer it over hand-rolling
* `new Promise((resolve) => setTimeout(resolve, ms))`, which the
* `@next/internal/no-adhoc-sleep` lint rule flags.
*
* @param ms the number of milliseconds to wait
*/
export async function wait(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
export async function wait(ms: number): Promise<void> {
return new Promise<void>((resolve) => setTimeout(resolve, ms))
}
import { wait } from '../../../../../lib/wait'
import { useState } from 'react'
export function useRestartServer() {
......@@ -51,7 +52,7 @@ export function useRestartServer() {
// Poll for server restart confirmation.
for (let i = 0; i < 10; i++) {
// generous 1 second delay for large apps.
await new Promise((resolveTimeout) => setTimeout(resolveTimeout, 1_000))
await wait(1_000)
try {
const nextId = await fetch('/__nextjs_server_status')
......
/* eslint-env jest */
import { createSandbox } from 'development-sandbox'
import { FileRef, nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import { waitFor, check } from 'next-test-utils'
import path from 'path'
import { outdent } from 'outdent'
......@@ -651,7 +651,7 @@ describe('Error recovery app', () => {
`
)
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
if (isTurbopack) {
await expect(browser).toDisplayRedbox(`
{
......
/* eslint-env jest */
import { createSandbox } from 'development-sandbox'
import { FileRef, isReact18, nextTestSetup } from 'e2e-utils'
import { check, retry } from 'next-test-utils'
import { waitFor, check, retry } from 'next-test-utils'
import { outdent } from 'outdent'
import path from 'path'
......@@ -798,7 +798,7 @@ describe('pages/ error recovery', () => {
export default function FunctionNamed() {`
)
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
if (isTurbopack) {
// TODO: Remove this branching once import traces are implemented in Turbopack
......@@ -864,7 +864,7 @@ describe('pages/ error recovery', () => {
}
// Test that runtime error does not take over:
await new Promise((resolve) => setTimeout(resolve, 3500))
await waitFor(3500)
if (isTurbopack) {
// TODO: Remove this branching once import traces are implemented in Turbopack
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils'
import { join } from 'path'
import { existsSync } from 'fs'
......@@ -22,7 +23,7 @@ describe('render-path tracing', () => {
expect(await browser.elementByCss('p').text()).toBe('hello world')
await browser.close()
await next.stop('SIGTERM')
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
}
const traceStructure = parseTraceFile(tracePath)
......
import { nextTestSetup, type Playwright } from 'e2e-utils'
import { retry, toggleDevToolsIndicatorPopover } from 'next-test-utils'
import { waitFor, retry, toggleDevToolsIndicatorPopover } from 'next-test-utils'
describe('instant-nav-panel', () => {
const { isNextDev, isTurbopack, next } = nextTestSetup({
......@@ -10,13 +10,8 @@ describe('instant-nav-panel', () => {
// Run all the necessary CSS transitions
// and click-outside event handler adjustment due to cascading update.
// TODO: Consider disabling transitions entirely in Next.js tests.
await new Promise((resolve) =>
setTimeout(
resolve,
// MENU_DURATION_MS + some flakiness buffer
200 + 50
)
)
// MENU_DURATION_MS + some flakiness buffer
await waitFor(200 + 50)
}
async function waitForInstantModeCookie(browser: Playwright): Promise<void> {
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils'
import { PHASE_DEVELOPMENT_SERVER } from 'next/constants'
import { createDefineEnv, loadBindings } from 'next/dist/build/swc'
......@@ -596,7 +597,7 @@ describe('next.rs api', () => {
// eslint-disable-next-line no-loop-func
it(`should have working HMR on ${name} ${i}`, async () => {
console.log('start')
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const entrypointsSubscribtion = project.entrypointsSubscribe()
const entrypoints: TurbopackResult<RawEntrypoints | {}> = (
await entrypointsSubscribtion.next()
......@@ -739,7 +740,7 @@ describe('next.rs api', () => {
it.skip('should allow to make many HMR updates', async () => {
console.log('start')
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const entrypointsSubscribtion = project.entrypointsSubscribe()
const entrypoints: TurbopackResult<RawEntrypoints | {}> = (
await entrypointsSubscribtion.next()
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils'
describe('development HMR refresh', () => {
......@@ -11,7 +12,7 @@ describe('development HMR refresh', () => {
await browser.eval(`window.doesNotReloadCheck = true`)
await new Promise<void>((resolve) => setTimeout(resolve, 10000))
await waitFor(10000)
expect(await browser.eval('window.doesNotReloadCheck')).toBe(true)
})
......
import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path'
import { retry, debugPrint, getFullUrl } from 'next-test-utils'
import { waitFor, retry, debugPrint, getFullUrl } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
import { chromium, firefox, webkit } from 'playwright'
import type { Browser } from 'playwright'
......@@ -124,7 +124,7 @@ describe('mcp-server get_errors tool', () => {
try {
// Wait for server to be ready
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
let errors: any = null
await retry(async () => {
const sessionId = 'test-multi-' + Date.now()
......
import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path'
import { retry } from 'next-test-utils'
import { waitFor, retry } from 'next-test-utils'
import { launchStandaloneSession } from './test-utils'
describe('mcp-server get_page_metadata tool', () => {
......@@ -106,7 +106,7 @@ describe('mcp-server get_page_metadata tool', () => {
const session2 = await launchStandaloneSession(next.url, '/parallel')
try {
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
let metadata: any = null
await retry(async () => {
......@@ -158,13 +158,13 @@ describe('mcp-server get_page_metadata tool', () => {
})
it('should count multiple browser tabs with the same URL separately', async () => {
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
const session1 = await launchStandaloneSession(next.url, '/')
const session2 = await launchStandaloneSession(next.url, '/')
try {
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
let metadata: any = null
await retry(async () => {
......
import { nextTestSetup } from 'e2e-utils'
import { fetchViaHTTP } from 'next-test-utils'
import { waitFor, fetchViaHTTP } from 'next-test-utils'
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'Slow Module Detection',
() => {
......@@ -32,7 +32,7 @@ import { fetchViaHTTP } from 'next-test-utils'
await fetchViaHTTP(next.url, '/')
// Wait for compilation to complete and check logs
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
// Verify slow module detection output
expect(logs).toContain('🐌 Detected slow modules while compiling client:')
......
import { nextTestSetup } from 'e2e-utils'
import { getRedboxHeader, retry } from 'next-test-utils'
import { waitFor, getRedboxHeader, retry } from 'next-test-utils'
describe('TypeScript HMR', () => {
const { next, isTurbopack } = nextTestSetup({
......@@ -17,7 +17,7 @@ describe('TypeScript HMR', () => {
const editedContent = originalContent.replace('Hello', 'COOL page')
if (isTurbopack) {
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
}
await next.patchFile('pages/hello.tsx', editedContent)
......@@ -64,7 +64,7 @@ describe('TypeScript HMR', () => {
'(): boolean => <p>hello with error</p>'
)
if (isTurbopack) {
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
}
try {
await next.patchFile('pages/type-error-recover.tsx', errContent)
......
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import { waitFor, check } from 'next-test-utils'
describe('app dir - css', () => {
const { next, isNextDev, skipped } = nextTestSetup({
......@@ -273,7 +273,7 @@ describe('app dir - css', () => {
await browser.elementByCss('button').click()
// Wait for error page to render and CSS to be loaded
await new Promise((resolve) => setTimeout(resolve, 2000))
await waitFor(2000)
await check(
async () =>
......
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { waitFor, retry } from 'next-test-utils'
describe('expire-time', () => {
const { next, isNextDeploy } = nextTestSetup({
......@@ -46,7 +46,7 @@ describe('expire-time', () => {
// Wait past the `expireTime` (10 s). The next request must trigger a
// blocking prerender, not stale-while-revalidate — so the response
// returned right here carries a freshly-computed value.
await new Promise((resolve) => setTimeout(resolve, 10_000))
await waitFor(10_000)
const $third = await next.render$('/')
const v3 = $third('#value').text()
......
import fs from 'fs'
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { waitFor, retry } from 'next-test-utils'
describe('log-file', () => {
const { next, isNextDev, skipped } = nextTestSetup({
......@@ -91,7 +91,7 @@ describe('log-file', () => {
// Request to RSC page and wait for hydration
await next.browser('/server')
// Wait for logs to be written (increased timeout for batched logging)
await new Promise((resolve) => setTimeout(resolve, 2000))
await waitFor(2000)
if (isNextDev) {
await retry(async () => {
......@@ -129,7 +129,7 @@ describe('log-file', () => {
)
})
// Wait for logs to be written (reduced timeout with faster flush)
await new Promise((resolve) => setTimeout(resolve, 2000))
await waitFor(2000)
if (isNextDev) {
await retry(async () => {
......@@ -152,7 +152,7 @@ describe('log-file', () => {
// Make request to page with getServerSideProps
await next.browser('/pages-router-page')
// Wait for logs to be written (increased timeout for batched logging)
await new Promise((resolve) => setTimeout(resolve, 2000))
await waitFor(2000)
if (isNextDev) {
await retry(async () => {
......
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import { waitFor, check } from 'next-test-utils'
describe('app dir - not-found - basic', () => {
const { next, isNextDev, isNextStart, skipped } = nextTestSetup({
......@@ -121,9 +121,7 @@ describe('app dir - not-found - basic', () => {
const browser = await next.browser('/random-content')
const timestamp = await browser.elementByCss('#timestamp').text()
await new Promise((resolve) => {
setTimeout(resolve, 3000)
})
await waitFor(3000)
await check(async () => {
const newTimestamp = await browser.elementByCss('#timestamp').text()
......
import { nextTestSetup, FileRef } from 'e2e-utils'
import { NextConfig } from 'next'
import { check, retry } from 'next-test-utils'
import { waitFor, check, retry } from 'next-test-utils'
import path from 'path'
const nextConfig: NextConfig = {
......@@ -502,9 +502,7 @@ describe.each([true, false])(
const browser = await next.browser('/parallel-no-page/foo')
const timestamp = await browser.elementByCss('#timestamp').text()
await new Promise((resolve) => {
setTimeout(resolve, 3000)
})
await waitFor(3000)
await check(async () => {
// an invalid response triggers a fast refresh, so if the timestamp doesn't update, this behaved correctly
......@@ -517,9 +515,7 @@ describe.each([true, false])(
const browser = await next.browser('parallel-nested/home/nested')
const timestamp = await browser.elementByCss('#timestamp').text()
await new Promise((resolve) => {
setTimeout(resolve, 3000)
})
await waitFor(3000)
await check(async () => {
// an invalid response triggers a fast refresh, so if the timestamp doesn't update, this behaved correctly
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils'
// TODO(NAR-423): Migrate to Cache Components.
......@@ -39,7 +40,7 @@ describe.skip('prefetch-navigation', () => {
resolve: async () => {
await route.continue()
// wait a moment to ensure the response is received
await new Promise((res) => setTimeout(res, 500))
await waitFor(500)
resolvePromise()
},
})
......
import { nextTestSetup } from 'e2e-utils'
import { retry, waitForRedbox, getRedboxDescription } from 'next-test-utils'
import {
waitFor,
retry,
waitForRedbox,
getRedboxDescription,
} from 'next-test-utils'
describe('app-dir refresh', () => {
const { next, skipped, isNextDev } = nextTestSetup({
......@@ -19,7 +24,7 @@ describe('app-dir refresh', () => {
expect(initialServerTimestamp).toBeTruthy()
await new Promise((resolve) => setTimeout(resolve, 100))
await waitFor(100)
await browser.elementById('refresh-button').click()
......
import path from 'path'
import {
waitFor,
check,
getClientReferenceManifest,
getDistDir,
......@@ -221,10 +222,10 @@ describe('app dir - rsc basics', () => {
const browser = await next.browser('/root')
await browser.waitForElementByCss('#goto-next-link').click()
await new Promise((res) => setTimeout(res, 1000))
await waitFor(1000)
await check(() => browser.url(), `${next.url}/next-api/link`)
await browser.waitForElementByCss('#goto-home').click()
await new Promise((res) => setTimeout(res, 1000))
await waitFor(1000)
await check(() => browser.url(), `${next.url}/root`)
const content = await browser.elementByCss('body').text()
expect(content).toContain('component:root.server')
......@@ -284,7 +285,7 @@ describe('app dir - rsc basics', () => {
// it will be a full redirection instead of being taken over by the next
// router. This timeout prevents it being flaky caused by fast refresh's
// rebuilding event.
await new Promise((res) => setTimeout(res, 1000))
await waitFor(1000)
await browser.eval('window.beforeNav = 1')
await browser.waitForElementByCss('#next_id').click()
......
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { waitFor, retry } from 'next-test-utils'
describe('searchparams-reuse-loading', () => {
const { next, isNextDev } = nextTestSetup({
......@@ -243,7 +243,7 @@ describe('searchparams-reuse-loading', () => {
resolve: async () => {
await route.continue()
// wait a moment to ensure the response is received
await new Promise((res) => setTimeout(res, 500))
await waitFor(500)
resolvePromise()
},
})
......@@ -360,7 +360,7 @@ describe('searchparams-reuse-loading', () => {
resolve: async () => {
await route.continue()
// wait a moment to ensure the response is received
await new Promise((res) => setTimeout(res, 500))
await waitFor(500)
resolvePromise()
},
})
......@@ -446,7 +446,7 @@ describe('searchparams-reuse-loading', () => {
resolve: async () => {
await route.continue()
// wait a moment to ensure the response is received
await new Promise((res) => setTimeout(res, 500))
await waitFor(500)
resolvePromise()
},
})
......@@ -532,7 +532,7 @@ describe('searchparams-reuse-loading', () => {
resolve: async () => {
await route.continue()
// wait a moment to ensure the response is received
await new Promise((res) => setTimeout(res, 500))
await waitFor(500)
resolvePromise()
},
})
......
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { retry, waitFor } from 'next-test-utils'
import { randomUUID } from 'crypto'
import escapeStringRegexp from 'escape-string-regexp'
import stripAnsi from 'strip-ansi'
......@@ -32,7 +32,7 @@ describe('use-cache-swr', () => {
expect(initialOuter).toBeDateString()
// Wait for the outer cache to go stale (revalidate: 5).
await new Promise((resolve) => setTimeout(resolve, 6000))
await waitFor(6000)
// Reset output index so the regen set we poll for below can't be satisfied
// by the initial cold-fill set from the first fetch.
......@@ -83,7 +83,7 @@ describe('use-cache-swr', () => {
expect(dynamic1).toBeDateString()
// Wait past the 1s revalidate window (cacheLife('seconds')).
await new Promise((resolve) => setTimeout(resolve, 1200))
await waitFor(1200)
outputIndex = next.cliOutput.length
......@@ -128,7 +128,7 @@ describe('use-cache-swr', () => {
expect(dynamic1).toBeDateString()
// Wait past the 1s revalidate window (cacheLife('seconds')).
await new Promise((resolve) => setTimeout(resolve, 1200))
await waitFor(1200)
outputIndex = next.cliOutput.length
......@@ -168,7 +168,7 @@ describe('use-cache-swr', () => {
await browser.elementById('outer-data').text()
// Wait for the outer cache to go stale (revalidate: 5).
await new Promise((resolve) => setTimeout(resolve, 6000))
await waitFor(6000)
// Reset output index to capture only the SWR-related logs.
outputIndex = next.cliOutput.length
......@@ -179,7 +179,7 @@ describe('use-cache-swr', () => {
await browser.refresh()
// Wait for the background regen to complete.
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const cliOutput = next.cliOutput.slice(outputIndex)
......
......@@ -810,21 +810,21 @@ describe('use-cache', () => {
// Click 1: revalidateTag with profile - should NOT cause immediate refresh
await browser.elementByCss('#revalidate-tag-with-profile').click()
// Wait for the action to complete
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const afterClick1 = await browser.elementByCss('#random').text()
console.log('[Test] After click 1:', afterClick1)
expect(afterClick1).toBe(initial) // No change - stale-while-revalidate
// Click 2: Same as click 1 - should still show stale data
await browser.elementByCss('#revalidate-tag-with-profile').click()
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const afterClick2 = await browser.elementByCss('#random').text()
console.log('[Test] After click 2:', afterClick2)
expect(afterClick2).toBe(initial) // Still no change
// Click 3: Same as before - should still show stale data (not data from click 1)
await browser.elementByCss('#revalidate-tag-with-profile').click()
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const afterClick3 = await browser.elementByCss('#random').text()
console.log('[Test] After click 3:', afterClick3)
expect(afterClick3).toBe(initial) // Still no change - no read-your-own-writes
......
......@@ -2,7 +2,7 @@
import http from 'http'
import httpProxy from 'http-proxy'
import cheerio from 'cheerio'
import { findPort } from 'next-test-utils'
import { waitFor, findPort } from 'next-test-utils'
import { nextTestSetup, isNextDev, isNextStart } from 'e2e-utils'
describe('CSS Module client-side navigation', () => {
......@@ -40,7 +40,7 @@ describe('CSS Module client-side navigation', () => {
new URL(req.url, next.url).pathname.endsWith('.css')
) {
console.log('stalling request for', req.url)
await new Promise((resolve) => setTimeout(resolve, 5 * 1000))
await waitFor(5 * 1000)
}
proxy.web(req, res)
})
......
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { waitFor, retry } from 'next-test-utils'
import fs from 'fs'
import path from 'path'
......@@ -73,7 +73,7 @@ async function expectPngResponse(res: Response) {
}
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
return waitFor(ms)
}
async function waitForCallbackTimestampToStabilize(
......@@ -513,7 +513,7 @@ describe('deferred-entries', () => {
})
// Wait a bit to ensure timestamps will be different
await new Promise((resolve) => setTimeout(resolve, 100))
await waitFor(100)
// Modify the home page (non-deferred entry) to trigger HMR
await next.patchFile('app/page.tsx', (content) =>
......@@ -556,7 +556,7 @@ describe('deferred-entries', () => {
})
// Ensure callback timestamp changes after a non-deferred edit.
await new Promise((resolve) => setTimeout(resolve, 100))
await waitFor(100)
await next.patchFile('app/page.tsx', (content) =>
content.includes('Home Page Updated')
? content.replace('Home Page Updated', 'Home Page Updated Again')
......
/* eslint-disable jest/no-identical-title */
import { nextTestSetup, isNextDev } from 'e2e-utils'
import { waitForRedbox, getRedboxHeader, retry } from 'next-test-utils'
import { waitFor, waitForRedbox, getRedboxHeader, retry } from 'next-test-utils'
jest.retryTimes(0)
......@@ -30,7 +30,7 @@ describe('Invalid hrefs', () => {
}
if (click) {
await browser.elementByCss('#click-me').click()
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
}
if (isWarn) {
await retry(async () => {
......@@ -63,7 +63,7 @@ describe('Invalid hrefs', () => {
await browser.waitForElementByCss('#click-me')
if (click) {
await browser.elementByCss('#click-me').click()
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
}
const caughtErrors = await browser.eval(`window.caughtErrors`)
expect(caughtErrors).toHaveLength(0)
......@@ -102,7 +102,7 @@ describe('Invalid hrefs', () => {
})
})()`)
await browser.elementByCss('a').click()
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
const errors = await browser.eval('window.caughtErrors')
expect(
errors.find((err: string) =>
......
......@@ -5,7 +5,7 @@ import {
RSC_HEADER,
} from 'next/src/client/components/app-router-headers'
import type { Page, Request as PlaywrightRequest } from 'playwright'
import { retry } from 'next-test-utils'
import { waitFor, retry } from 'next-test-utils'
const _describe =
// prefetching is disabled in dev.
......@@ -218,7 +218,7 @@ class RequestInterceptor {
this.pendingRequests.delete(requestKey)
await route.continue()
// wait a moment to ensure the response is received
await new Promise((res) => setTimeout(res, 500))
await waitFor(500)
blocked.resolve()
},
})
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils'
describe('Build Error Tests for basePath', () => {
......@@ -63,7 +64,7 @@ describe('Static Image Component Tests for basePath', () => {
await browser.eval(
`document.getElementById("basic-static").scrollIntoView()`
)
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const url = await browser.eval(
`document.getElementById("basic-static").src`
)
......@@ -78,7 +79,7 @@ describe('Static Image Component Tests for basePath', () => {
await browser.eval(
`document.getElementById("static-unoptimized").scrollIntoView()`
)
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const url = await browser.eval(
`document.getElementById("static-unoptimized").src`
)
......
import { nextTestSetup, isNextDev } from 'e2e-utils'
import {
waitFor,
waitForRedbox,
waitForNoRedbox,
getRedboxHeader,
......@@ -369,7 +370,7 @@ describe('Legacy Image Component basePath Tests', () => {
expect(result).toBeGreaterThan(0)
})
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height')
......@@ -389,7 +390,7 @@ describe('Legacy Image Component basePath Tests', () => {
expect(result).toBeGreaterThan(0)
})
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height')
......
/* eslint-disable jest/no-standalone-expect */
import { waitFor } from 'next-test-utils'
import {
nextTestSetup,
isNextDev,
......@@ -74,7 +75,7 @@ describe('Static Image Component Tests', () => {
await browser.eval(
`document.getElementById("basic-static").scrollIntoView()`
)
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const url = await browser.eval(
`document.getElementById("basic-static").src`
)
......@@ -90,7 +91,7 @@ describe('Static Image Component Tests', () => {
await browser.eval(
`document.getElementById("static-unoptimized").scrollIntoView()`
)
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const url = await browser.eval(
`document.getElementById("static-unoptimized").src`
)
......
......@@ -2,6 +2,7 @@ import cheerio from 'cheerio'
import validateHTML from 'html-validator'
import { nextTestSetup, isNextDev } from 'e2e-utils'
import {
waitFor,
waitForRedbox,
waitForNoRedbox,
getRedboxHeader,
......@@ -728,7 +729,7 @@ describe('Image Component Tests', () => {
)
if (isNextDev) {
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
......@@ -816,7 +817,7 @@ describe('Image Component Tests', () => {
it('should warn when img with layout=fill is inside a container without position relative', async () => {
const browser = await next.browser('/layout-fill-inside-nonrelative')
await browser.eval(`document.querySelector("footer").scrollIntoView()`)
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
......@@ -880,7 +881,7 @@ describe('Image Component Tests', () => {
)
expect(result).toBeGreaterThan(0)
})
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
......@@ -974,7 +975,7 @@ describe('Image Component Tests', () => {
)
expect(result).toBeGreaterThan(0)
})
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.filter((log) => log.startsWith('Image with src'))
......@@ -1008,7 +1009,7 @@ describe('Image Component Tests', () => {
expect(result).toBeGreaterThan(0)
})
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height')
......@@ -1058,7 +1059,7 @@ describe('Image Component Tests', () => {
const src = await getSrc(browser, 'img-blur')
expect(src).toMatch(/^\/_next\/image/)
})
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
expect(await getComputedStyle(browser, 'img-plain', 'filter')).toBe(
'opacity(0.5)'
......@@ -1108,7 +1109,7 @@ describe('Image Component Tests', () => {
expect(result).toBeGreaterThan(0)
})
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height')
......@@ -1287,7 +1288,7 @@ describe('Image Component Tests', () => {
it('should be valid HTML', async () => {
const browser = await next.browser('/valid-html-w3c')
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
expect(await browser.hasElementByCssSelector('img')).toBeTruthy()
const url = await browser.url()
const result = (await validateHTML({
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils'
import cheerio from 'cheerio'
......@@ -85,7 +86,7 @@ import cheerio from 'cheerio'
await browser.eval(
`document.getElementById("basic-static").scrollIntoView()`
)
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const url = await browser.eval(
`document.getElementById("basic-static").src`
)
......@@ -101,7 +102,7 @@ import cheerio from 'cheerio'
await browser.eval(
`document.getElementById("static-unoptimized").scrollIntoView()`
)
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const url = await browser.eval(
`document.getElementById("static-unoptimized").src`
)
......
import cheerio from 'cheerio'
import validateHTML from 'html-validator'
import {
waitFor,
waitForRedbox,
waitForNoRedbox,
getRedboxHeader,
......@@ -765,7 +766,7 @@ describe('Image Component App Dir Tests', () => {
`/_next/image?url=%2Ftest.png&w=640&q=75${dpl} 1x, /_next/image?url=%2Ftest.png&w=828&q=75${dpl} 2x`
)
if (isNextDev) {
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
......@@ -1203,7 +1204,7 @@ describe('Image Component App Dir Tests', () => {
)
expect(result).toBeGreaterThan(0)
})
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
......@@ -1287,7 +1288,7 @@ describe('Image Component App Dir Tests', () => {
)
expect(result).toBeGreaterThan(0)
})
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.filter((log) => log.startsWith('Image with src'))
......@@ -1348,7 +1349,7 @@ describe('Image Component App Dir Tests', () => {
expect(result).toBeGreaterThan(0)
})
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height')
......@@ -1396,7 +1397,7 @@ describe('Image Component App Dir Tests', () => {
await retry(async () => {
expect(await getSrc(browser, 'img-blur')).toMatch(/^\/_next\/image/)
})
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
expect(await getComputedStyle(browser, 'img-plain', 'filter')).toBe(
'opacity(0.5)'
......@@ -1471,7 +1472,7 @@ describe('Image Component App Dir Tests', () => {
})
if (isNextDev) {
it('should not log incorrect warnings', async () => {
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
......@@ -1482,7 +1483,7 @@ describe('Image Component App Dir Tests', () => {
})
it('should log warnings when using fill mode incorrectly', async () => {
browser = await next.browser('/fill-warnings')
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
......@@ -1501,7 +1502,7 @@ describe('Image Component App Dir Tests', () => {
})
it('should not log warnings when image unmounts', async () => {
browser = await next.browser('/should-not-warn-unmount')
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
......@@ -1526,7 +1527,7 @@ describe('Image Component App Dir Tests', () => {
expect(result).not.toBe(0)
})
await new Promise((r) => setTimeout(r, 500))
await waitFor(500)
const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height')
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils'
import cheerio from 'cheerio'
......@@ -74,7 +75,7 @@ describe('Static Image Component Tests for basePath', () => {
await browser.eval(
`document.getElementById("basic-static").scrollIntoView()`
)
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const url = await browser.eval(
`document.getElementById("basic-static").src`
)
......@@ -88,7 +89,7 @@ describe('Static Image Component Tests for basePath', () => {
await browser.eval(
`document.getElementById("static-unoptimized").scrollIntoView()`
)
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const url = await browser.eval(
`document.getElementById("static-unoptimized").src`
)
......
import { nextTestSetup, isNextDev } from 'e2e-utils'
import {
waitFor,
waitForRedbox,
waitForNoRedbox,
getRedboxHeader,
......@@ -142,7 +143,7 @@ describe('Image Component basePath Tests', () => {
expect(result).toBeGreaterThan(0)
})
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height')
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils'
import cheerio from 'cheerio'
......@@ -76,7 +77,7 @@ describe('Static Image Component Tests', () => {
await browser.eval(
`document.getElementById("basic-static").scrollIntoView()`
)
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const url = await browser.eval(
`document.getElementById("basic-static").src`
)
......@@ -90,7 +91,7 @@ describe('Static Image Component Tests', () => {
await browser.eval(
`document.getElementById("static-unoptimized").scrollIntoView()`
)
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
const url = await browser.eval(
`document.getElementById("static-unoptimized").src`
)
......
import cheerio from 'cheerio'
import validateHTML from 'html-validator'
import {
waitFor,
waitForRedbox,
waitForNoRedbox,
getRedboxHeader,
......@@ -766,7 +767,7 @@ describe('Image Component Default Tests', () => {
`/_next/image?url=%2Ftest.png&w=640&q=75${dpl} 1x, /_next/image?url=%2Ftest.png&w=828&q=75${dpl} 2x`
)
if (isNextDev) {
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
......@@ -1204,7 +1205,7 @@ describe('Image Component Default Tests', () => {
)
expect(result).toBeGreaterThan(0)
})
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
......@@ -1288,7 +1289,7 @@ describe('Image Component Default Tests', () => {
)
expect(result).toBeGreaterThan(0)
})
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.filter((log) => log.startsWith('Image with src'))
......@@ -1354,7 +1355,7 @@ describe('Image Component Default Tests', () => {
expect(result).toBeGreaterThan(0)
})
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height')
......@@ -1402,7 +1403,7 @@ describe('Image Component Default Tests', () => {
await retry(async () => {
expect(await getSrc(browser, 'img-blur')).toMatch(/^\/_next\/image/)
})
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
expect(await getComputedStyle(browser, 'img-plain', 'filter')).toBe(
'opacity(0.5)'
......@@ -1477,7 +1478,7 @@ describe('Image Component Default Tests', () => {
})
if (isNextDev) {
it('should not log incorrect warnings', async () => {
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
......@@ -1488,7 +1489,7 @@ describe('Image Component Default Tests', () => {
})
it('should log warnings when using fill mode incorrectly', async () => {
browser = await next.browser('/fill-warnings')
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
......@@ -1507,7 +1508,7 @@ describe('Image Component Default Tests', () => {
})
it('should not log warnings when image unmounts', async () => {
browser = await next.browser('/should-not-warn-unmount')
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
......@@ -1532,7 +1533,7 @@ describe('Image Component Default Tests', () => {
expect(result).not.toBe(0)
})
await new Promise((r) => setTimeout(r, 500))
await waitFor(500)
const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height')
......@@ -1685,7 +1686,7 @@ describe('Image Component Default Tests', () => {
it('should be valid HTML', async () => {
const browser = await next.browser('/valid-html-w3c')
await new Promise((r) => setTimeout(r, 1000))
await waitFor(1000)
expect(await browser.hasElementByCssSelector('img')).toBeTruthy()
const url = await browser.url()
const result = (await validateHTML({
......
import { FileRef, isNextDev, isNextStart, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { waitFor, retry } from 'next-test-utils'
import { NEXT_RSC_UNION_QUERY } from 'next/dist/client/components/app-router-headers'
import path from 'path'
......
......@@ -28,6 +28,7 @@ import type { SpawnOptions, ChildProcess } from 'child_process'
import type { NextServer } from 'next/dist/server/next'
import type { Playwright } from './browsers/playwright'
import { recursiveReadDir } from 'next/dist/lib/recursive-readdir'
import { wait } from 'next/dist/lib/wait'
import { shouldUseTurbopack } from './turbo'
import stripAnsi from 'strip-ansi'
......@@ -792,11 +793,18 @@ export async function stopApp(server: http.Server | undefined) {
await promisify(server.close).apply(server)
}
/**
* Wait for a fixed number of milliseconds, or poll until a condition holds.
*
* Prefer `retry()` when you are waiting for something to become true — a fixed
* sleep is a common source of flakiness. The `@next/internal/no-adhoc-sleep`
* lint rule points hand-rolled sleep promises here.
*/
export async function waitFor(
millisOrCondition: number | (() => boolean)
): Promise<void> {
if (typeof millisOrCondition === 'number') {
return new Promise((resolve) => setTimeout(resolve, millisOrCondition))
return wait(millisOrCondition)
}
return new Promise((resolve) => {
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils'
describe('unstable-cache-foreground-revalidate', () => {
......@@ -18,13 +19,13 @@ describe('unstable-cache-foreground-revalidate', () => {
const initialLogLength = next.cliOutput.length
// Wait for both ISR and unstable_cache to become stale
await new Promise((resolve) => setTimeout(resolve, 11000))
await waitFor(11000)
// This request triggers ISR background revalidation
await next.render('/isr-10')
// Wait for ISR background revalidation to complete
await new Promise((resolve) => setTimeout(resolve, 2000))
await waitFor(2000)
// Get logs since the initial render
const logs = next.cliOutput.substring(initialLogLength)
......@@ -76,10 +77,10 @@ describe('unstable-cache-foreground-revalidate', () => {
const initialLogLength = next.cliOutput.length
await new Promise((resolve) => setTimeout(resolve, 11000))
await waitFor(11000)
await next.render('/isr-10-nested')
await new Promise((resolve) => setTimeout(resolve, 2000))
await waitFor(2000)
const logs = next.cliOutput.substring(initialLogLength)
const cacheExecutions = [
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils'
describe('handle already sent response', () => {
......@@ -24,7 +25,7 @@ describe('handle already sent response', () => {
if ((next.cliOutput.match(/getServerSideProps/g) || []).length >= 2) {
break
}
await new Promise((resolve) => setTimeout(resolve, 1000))
await waitFor(1000)
}
if (i === 3) {
throw new Error('Timed out waiting for logs to show')
......
import { nextTestSetup, type Playwright } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { waitFor, retry } from 'next-test-utils'
const emptyImage =
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
......@@ -207,7 +207,7 @@ describe('Image Component Tests', () => {
await b.eval(
`window.scrollTo(0, ${topOfBottomImage - (viewportHeight + buffer)})`
)
await new Promise((r) => setTimeout(r, 200))
await waitFor(200)
expect(await b.elementById('lazy-bottom').getAttribute('src')).toBe(
'https://next-data-api-endpoint.vercel.app/next-image-legacy/lazy3.jpg'
)
......@@ -231,7 +231,7 @@ describe('Image Component Tests', () => {
await b.eval(
`window.scrollTo(0, ${topOfBottomImage - (viewportHeight + buffer)})`
)
await new Promise((r) => setTimeout(r, 200))
await waitFor(200)
expect(
await b.elementById('lazy-without-attribute').getAttribute('src')
).toBe(
......@@ -422,7 +422,7 @@ describe('Image Component Tests', () => {
beforeAll(async () => {
browser = await next.browser('/')
await browser.waitForElementByCss('#lazylink').click()
await new Promise((r) => setTimeout(r, 500))
await waitFor(500)
})
lazyLoadingTests(() => browser)
})
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils'
const strictRouteTypes =
......@@ -120,7 +121,7 @@ describe('tsconfig.json verifier', () => {
expect(await next.hasFile('tsconfig.json')).toBe(false)
await next.patchFile('tsconfig.json', '')
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
expect(await next.readFile('tsconfig.json')).toBe('')
const { exitCode, cliOutput } = await next.build()
......@@ -232,7 +233,7 @@ describe('tsconfig.json verifier', () => {
// end comment
`
)
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
const { exitCode } = await next.build()
expect(exitCode).toBe(0)
......@@ -350,7 +351,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json',
`{ "compilerOptions": { "esModuleInterop": false, "module": "es2020" } }`
)
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
const { exitCode } = await next.build()
expect(exitCode).toBe(0)
......@@ -446,7 +447,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json',
`{ "compilerOptions": { "esModuleInterop": false, "moduleResolution": "node16", "module": "node16" } }`
)
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('moduleResolution')
expect(exitCode).toBe(0)
......@@ -543,7 +544,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json',
`{ "compilerOptions": { "esModuleInterop": false, "moduleResolution": "bundler" } }`
)
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('moduleResolution')
expect(exitCode).toBe(0)
......@@ -640,7 +641,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json',
`{ "compilerOptions": { "target": "es2022" } }`
)
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('target')
expect(exitCode).toBe(0)
......@@ -737,7 +738,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json',
`{ "compilerOptions": { "esModuleInterop": false, "module": "node16", "moduleResolution": "node16" } }`
)
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('moduleResolution')
expect(exitCode).toBe(0)
......@@ -834,7 +835,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json',
`{ "compilerOptions": { "verbatimModuleSyntax": true } }`
)
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('isolatedModules')
expect(exitCode).toBe(0)
......@@ -972,7 +973,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json',
`{ "extends": "./tsconfig.base.json" }`
)
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('isolatedModules')
expect(exitCode).toBe(0)
......@@ -1028,13 +1029,13 @@ describe('tsconfig.json verifier', () => {
}
`
)
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
await next.patchFile(
'tsconfig.json',
`{ "extends": "./tsconfig.base.json" }`
)
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('moduleResolution')
......@@ -1090,13 +1091,13 @@ describe('tsconfig.json verifier', () => {
}
`
)
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
await next.patchFile(
'tsconfig.json',
`{ "extends": "./tsconfig.base.json" }`
)
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('moduleResolution')
......@@ -1115,7 +1116,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json',
`{ "compilerOptions": { "module": "preserve" } }`
)
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('moduleResolution')
expect(cliOutput).not.toContain('esModuleInterop')
......@@ -1167,7 +1168,7 @@ describe('tsconfig.json verifier 5.x', () => {
'tsconfig.json',
`{ "compilerOptions": { "esModuleInterop": false, "module": "commonjs" } }`
)
await new Promise((resolve) => setTimeout(resolve, 500))
await waitFor(500)
const { exitCode } = await next.build()
expect(exitCode).toBe(0)
......
/* eslint-env jest */
import { wait } from '../../packages/next/src/lib/wait'
import {
IntervalsManager,
TimeoutsManager,
......@@ -8,13 +9,13 @@ import {
// value passed to timer callbacks.
const globalObject = {} as any
async function waitFor(condition: () => boolean, timeoutMs = 1000) {
async function waitForCondition(condition: () => boolean, timeoutMs = 1000) {
const start = Date.now()
while (!condition()) {
if (Date.now() - start > timeoutMs) {
throw new Error('waitFor timed out')
throw new Error('waitForCondition timed out')
}
await new Promise((resolve) => setTimeout(resolve, 5))
await wait(5)
}
}
......@@ -38,8 +39,8 @@ describe('web sandbox TimeoutsManager', () => {
// After they complete naturally, tracking must drop back to zero even
// though user code never called clearTimeout.
await waitFor(() => ran === count)
await waitFor(() => manager.size === 0)
await waitForCondition(() => ran === count)
await waitForCondition(() => manager.size === 0)
expect(manager.size).toBe(0)
})
......@@ -50,7 +51,7 @@ describe('web sandbox TimeoutsManager', () => {
for (let i = 0; i < 20; i++) {
manager.add([globalObject, () => {}, 0])
}
await waitFor(() => manager.size === 0)
await waitForCondition(() => manager.size === 0)
}
expect(manager.size).toBe(0)
......@@ -72,7 +73,7 @@ describe('web sandbox TimeoutsManager', () => {
'b',
])
await waitFor(() => observedArgs.length > 0)
await waitForCondition(() => observedArgs.length > 0)
expect(observedThis).toBe(globalObject)
expect(observedArgs).toEqual(['a', 'b'])
expect(manager.size).toBe(0)
......@@ -105,8 +106,8 @@ describe('web sandbox TimeoutsManager', () => {
let ran = false
const firedId = manager.add([globalObject, () => (ran = true), 0])
const pendingId = manager.add([globalObject, () => {}, 1000])
await waitFor(() => ran)
await waitFor(() => manager.size === 1)
await waitForCondition(() => ran)
await waitForCondition(() => manager.size === 1)
// Matches user code that calls clearTimeout inside the callback (the
// documented workaround for #95094); must not throw or affect other
......@@ -129,7 +130,7 @@ describe('web sandbox TimeoutsManager', () => {
expect(manager.size).toBe(0)
// Give the original delay time to elapse; the callback must not run.
await new Promise((resolve) => setTimeout(resolve, 100))
await wait(100)
expect(ran).toBe(false)
})
......@@ -154,7 +155,7 @@ describe('web sandbox IntervalsManager', () => {
// Intervals fire repeatedly, so they must remain tracked (unlike one-shot
// timeouts) even after several ticks have run.
await waitFor(() => ticks >= 3)
await waitForCondition(() => ticks >= 3)
expect(manager.size).toBe(1)
manager.remove(id)
......
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