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 ...@@ -199,6 +199,12 @@ tail -5 /tmp/test-output.log # Summary
await new Promise((resolve) => setTimeout(resolve, 1000)) 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** - **Do NOT use `check()` - it is deprecated. Use `retry()` + `expect()` instead**
```typescript ```typescript
......
...@@ -439,6 +439,37 @@ export default defineConfig([ ...@@ -439,6 +439,37 @@ export default defineConfig([
'jsdoc/no-undefined-types': 'error', '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: [ files: [
'packages/next/src/server/**/*.js', '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 typecheckedRequire = require('./eslint-typechecked-require')
const noAmbiguousJSX = require('./eslint-no-ambiguous-jsx') const noAmbiguousJSX = require('./eslint-no-ambiguous-jsx')
const noAdhocSleep = require('./eslint-no-adhoc-sleep')
module.exports = { module.exports = {
rules: { rules: {
'no-adhoc-sleep': noAdhocSleep,
'no-ambiguous-jsx': noAmbiguousJSX, 'no-ambiguous-jsx': noAmbiguousJSX,
'typechecked-require': typecheckedRequire, 'typechecked-require': typecheckedRequire,
}, },
......
import { wait } from '../lib/wait'
import fs from 'fs' import fs from 'fs'
import nodePath from 'path' import nodePath from 'path'
import { bold, cyan } from '../lib/picocolors' import { bold, cyan } from '../lib/picocolors'
...@@ -176,7 +177,7 @@ export class Lockfile { ...@@ -176,7 +177,7 @@ export class Lockfile {
while (Date.now() - startMs < MAX_RETRY_MS) { while (Date.now() - startMs < MAX_RETRY_MS) {
lockfile = Lockfile.tryAcquire(path, unlockOnExit, content) lockfile = Lockfile.tryAcquire(path, unlockOnExit, content)
if (lockfile !== undefined) break if (lockfile !== undefined) break
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS)) await wait(RETRY_DELAY_MS)
} }
if (lockfile === undefined) { if (lockfile === undefined) {
const isDev = processName === 'next dev' const isDev = processName === 'next dev'
......
import { wait } from '../lib/wait'
import path from 'path' import path from 'path'
import { readLockfileContent, parseDevServerInfo } from '../build/lockfile' import { readLockfileContent, parseDevServerInfo } from '../build/lockfile'
import { getProjectDir } from '../lib/get-project-dir' import { getProjectDir } from '../lib/get-project-dir'
...@@ -118,9 +119,7 @@ async function discoverDevServerUrl(directory?: string): Promise<URL> { ...@@ -118,9 +119,7 @@ async function discoverDevServerUrl(directory?: string): Promise<URL> {
return parseDevServerUrl(serverInfo.appUrl) return parseDevServerUrl(serverInfo.appUrl)
} }
await new Promise((resolve) => await wait(DEV_SERVER_DISCOVERY_RETRY_MS)
setTimeout(resolve, DEV_SERVER_DISCOVERY_RETRY_MS)
)
} }
return exitWithError( return exitWithError(
......
import type { CacheNode, Segment } from '../../../shared/lib/app-router-types' import type { CacheNode, Segment } from '../../../shared/lib/app-router-types'
import type React from 'react' import type React from 'react'
import { wait } from '../../../lib/wait'
import { import {
PrefetchHint, PrefetchHint,
StaticAttemptHints, StaticAttemptHints,
...@@ -2470,9 +2471,7 @@ async function retryUpgradeableFallbackPrefetch( ...@@ -2470,9 +2471,7 @@ async function retryUpgradeableFallbackPrefetch(
fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell
): Promise<void> { ): Promise<void> {
for (let attempt = 0; attempt < MAX_FALLBACK_RETRIES; attempt++) { for (let attempt = 0; attempt < MAX_FALLBACK_RETRIES; attempt++) {
await new Promise<void>((resolve) => await wait(FALLBACK_RETRY_DELAY_MS)
setTimeout(resolve, FALLBACK_RETRY_DELAY_MS)
)
if (task.isCanceled) { if (task.isCanceled) {
break break
} }
......
import { wait } from '../lib/wait'
import type { import type {
ExportPagesInput, ExportPagesInput,
ExportPageInput, ExportPageInput,
...@@ -514,7 +515,7 @@ export async function exportPages( ...@@ -514,7 +515,7 @@ export async function exportPages(
const maxDelay = 2000 // 2 seconds const maxDelay = 2000 // 2 seconds
const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay) const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay)
const jitter = Math.random() * 0.3 * delay // Add up to 30% random jitter 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 ScheduledFn<T = void> = () => T | PromiseLike<T>
export type SchedulerFn<T = void> = (cb: ScheduledFn<T>) => void export type SchedulerFn<T = void> = (cb: ScheduledFn<T>) => void
...@@ -57,7 +59,7 @@ export function atLeastOneTask() { ...@@ -57,7 +59,7 @@ export function atLeastOneTask() {
*/ */
export function waitAtLeastOneReactRenderTask(): Promise<void> { export function waitAtLeastOneReactRenderTask(): Promise<void> {
if (process.env.NEXT_RUNTIME === 'edge') { if (process.env.NEXT_RUNTIME === 'edge') {
return new Promise((r) => setTimeout(r, 0)) return wait(0)
} else { } else {
return new Promise((r) => setImmediate(r)) return new Promise((r) => setImmediate(r))
} }
......
import { wait } from '../wait'
import path from 'path' import path from 'path'
import { getFormattedDiagnostic } from './diagnosticFormatter' import { getFormattedDiagnostic } from './diagnosticFormatter'
import { getTypeScriptConfiguration } from './getTypeScriptConfiguration' import { getTypeScriptConfiguration } from './getTypeScriptConfiguration'
...@@ -195,7 +196,7 @@ export async function runTypeCheck( ...@@ -195,7 +196,7 @@ export async function runTypeCheck(
) )
// Make sure all stdout is flushed before we exit. // 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. * 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 * @param ms the number of milliseconds to wait
*/ */
export async function wait(ms: number) { export async function wait(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms)) return new Promise<void>((resolve) => setTimeout(resolve, ms))
} }
import { wait } from '../../../../../lib/wait'
import { useState } from 'react' import { useState } from 'react'
export function useRestartServer() { export function useRestartServer() {
...@@ -51,7 +52,7 @@ export function useRestartServer() { ...@@ -51,7 +52,7 @@ export function useRestartServer() {
// Poll for server restart confirmation. // Poll for server restart confirmation.
for (let i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
// generous 1 second delay for large apps. // generous 1 second delay for large apps.
await new Promise((resolveTimeout) => setTimeout(resolveTimeout, 1_000)) await wait(1_000)
try { try {
const nextId = await fetch('/__nextjs_server_status') const nextId = await fetch('/__nextjs_server_status')
......
/* eslint-env jest */ /* eslint-env jest */
import { createSandbox } from 'development-sandbox' import { createSandbox } from 'development-sandbox'
import { FileRef, nextTestSetup } from 'e2e-utils' import { FileRef, nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils' import { waitFor, check } from 'next-test-utils'
import path from 'path' import path from 'path'
import { outdent } from 'outdent' import { outdent } from 'outdent'
...@@ -651,7 +651,7 @@ describe('Error recovery app', () => { ...@@ -651,7 +651,7 @@ describe('Error recovery app', () => {
` `
) )
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
if (isTurbopack) { if (isTurbopack) {
await expect(browser).toDisplayRedbox(` await expect(browser).toDisplayRedbox(`
{ {
......
/* eslint-env jest */ /* eslint-env jest */
import { createSandbox } from 'development-sandbox' import { createSandbox } from 'development-sandbox'
import { FileRef, isReact18, nextTestSetup } from 'e2e-utils' 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 { outdent } from 'outdent'
import path from 'path' import path from 'path'
...@@ -798,7 +798,7 @@ describe('pages/ error recovery', () => { ...@@ -798,7 +798,7 @@ describe('pages/ error recovery', () => {
export default function FunctionNamed() {` export default function FunctionNamed() {`
) )
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
if (isTurbopack) { if (isTurbopack) {
// TODO: Remove this branching once import traces are implemented in Turbopack // TODO: Remove this branching once import traces are implemented in Turbopack
...@@ -864,7 +864,7 @@ describe('pages/ error recovery', () => { ...@@ -864,7 +864,7 @@ describe('pages/ error recovery', () => {
} }
// Test that runtime error does not take over: // Test that runtime error does not take over:
await new Promise((resolve) => setTimeout(resolve, 3500)) await waitFor(3500)
if (isTurbopack) { if (isTurbopack) {
// TODO: Remove this branching once import traces are implemented in Turbopack // TODO: Remove this branching once import traces are implemented in Turbopack
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { join } from 'path' import { join } from 'path'
import { existsSync } from 'fs' import { existsSync } from 'fs'
...@@ -22,7 +23,7 @@ describe('render-path tracing', () => { ...@@ -22,7 +23,7 @@ describe('render-path tracing', () => {
expect(await browser.elementByCss('p').text()).toBe('hello world') expect(await browser.elementByCss('p').text()).toBe('hello world')
await browser.close() await browser.close()
await next.stop('SIGTERM') await next.stop('SIGTERM')
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
} }
const traceStructure = parseTraceFile(tracePath) const traceStructure = parseTraceFile(tracePath)
......
import { nextTestSetup, type Playwright } from 'e2e-utils' 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', () => { describe('instant-nav-panel', () => {
const { isNextDev, isTurbopack, next } = nextTestSetup({ const { isNextDev, isTurbopack, next } = nextTestSetup({
...@@ -10,13 +10,8 @@ describe('instant-nav-panel', () => { ...@@ -10,13 +10,8 @@ describe('instant-nav-panel', () => {
// Run all the necessary CSS transitions // Run all the necessary CSS transitions
// and click-outside event handler adjustment due to cascading update. // and click-outside event handler adjustment due to cascading update.
// TODO: Consider disabling transitions entirely in Next.js tests. // TODO: Consider disabling transitions entirely in Next.js tests.
await new Promise((resolve) =>
setTimeout(
resolve,
// MENU_DURATION_MS + some flakiness buffer // MENU_DURATION_MS + some flakiness buffer
200 + 50 await waitFor(200 + 50)
)
)
} }
async function waitForInstantModeCookie(browser: Playwright): Promise<void> { async function waitForInstantModeCookie(browser: Playwright): Promise<void> {
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { PHASE_DEVELOPMENT_SERVER } from 'next/constants' import { PHASE_DEVELOPMENT_SERVER } from 'next/constants'
import { createDefineEnv, loadBindings } from 'next/dist/build/swc' import { createDefineEnv, loadBindings } from 'next/dist/build/swc'
...@@ -596,7 +597,7 @@ describe('next.rs api', () => { ...@@ -596,7 +597,7 @@ describe('next.rs api', () => {
// eslint-disable-next-line no-loop-func // eslint-disable-next-line no-loop-func
it(`should have working HMR on ${name} ${i}`, async () => { it(`should have working HMR on ${name} ${i}`, async () => {
console.log('start') console.log('start')
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const entrypointsSubscribtion = project.entrypointsSubscribe() const entrypointsSubscribtion = project.entrypointsSubscribe()
const entrypoints: TurbopackResult<RawEntrypoints | {}> = ( const entrypoints: TurbopackResult<RawEntrypoints | {}> = (
await entrypointsSubscribtion.next() await entrypointsSubscribtion.next()
...@@ -739,7 +740,7 @@ describe('next.rs api', () => { ...@@ -739,7 +740,7 @@ describe('next.rs api', () => {
it.skip('should allow to make many HMR updates', async () => { it.skip('should allow to make many HMR updates', async () => {
console.log('start') console.log('start')
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const entrypointsSubscribtion = project.entrypointsSubscribe() const entrypointsSubscribtion = project.entrypointsSubscribe()
const entrypoints: TurbopackResult<RawEntrypoints | {}> = ( const entrypoints: TurbopackResult<RawEntrypoints | {}> = (
await entrypointsSubscribtion.next() await entrypointsSubscribtion.next()
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
describe('development HMR refresh', () => { describe('development HMR refresh', () => {
...@@ -11,7 +12,7 @@ describe('development HMR refresh', () => { ...@@ -11,7 +12,7 @@ describe('development HMR refresh', () => {
await browser.eval(`window.doesNotReloadCheck = true`) 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) expect(await browser.eval('window.doesNotReloadCheck')).toBe(true)
}) })
......
import { FileRef, nextTestSetup } from 'e2e-utils' import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path' 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 stripAnsi from 'strip-ansi'
import { chromium, firefox, webkit } from 'playwright' import { chromium, firefox, webkit } from 'playwright'
import type { Browser } from 'playwright' import type { Browser } from 'playwright'
...@@ -124,7 +124,7 @@ describe('mcp-server get_errors tool', () => { ...@@ -124,7 +124,7 @@ describe('mcp-server get_errors tool', () => {
try { try {
// Wait for server to be ready // Wait for server to be ready
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
let errors: any = null let errors: any = null
await retry(async () => { await retry(async () => {
const sessionId = 'test-multi-' + Date.now() const sessionId = 'test-multi-' + Date.now()
......
import { FileRef, nextTestSetup } from 'e2e-utils' import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path' import path from 'path'
import { retry } from 'next-test-utils' import { waitFor, retry } from 'next-test-utils'
import { launchStandaloneSession } from './test-utils' import { launchStandaloneSession } from './test-utils'
describe('mcp-server get_page_metadata tool', () => { describe('mcp-server get_page_metadata tool', () => {
...@@ -106,7 +106,7 @@ 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') const session2 = await launchStandaloneSession(next.url, '/parallel')
try { try {
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
let metadata: any = null let metadata: any = null
await retry(async () => { await retry(async () => {
...@@ -158,13 +158,13 @@ describe('mcp-server get_page_metadata tool', () => { ...@@ -158,13 +158,13 @@ describe('mcp-server get_page_metadata tool', () => {
}) })
it('should count multiple browser tabs with the same URL separately', async () => { 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 session1 = await launchStandaloneSession(next.url, '/')
const session2 = await launchStandaloneSession(next.url, '/') const session2 = await launchStandaloneSession(next.url, '/')
try { try {
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
let metadata: any = null let metadata: any = null
await retry(async () => { await retry(async () => {
......
import { nextTestSetup } from 'e2e-utils' 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)( ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'Slow Module Detection', 'Slow Module Detection',
() => { () => {
...@@ -32,7 +32,7 @@ import { fetchViaHTTP } from 'next-test-utils' ...@@ -32,7 +32,7 @@ import { fetchViaHTTP } from 'next-test-utils'
await fetchViaHTTP(next.url, '/') await fetchViaHTTP(next.url, '/')
// Wait for compilation to complete and check logs // Wait for compilation to complete and check logs
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
// Verify slow module detection output // Verify slow module detection output
expect(logs).toContain('🐌 Detected slow modules while compiling client:') expect(logs).toContain('🐌 Detected slow modules while compiling client:')
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { getRedboxHeader, retry } from 'next-test-utils' import { waitFor, getRedboxHeader, retry } from 'next-test-utils'
describe('TypeScript HMR', () => { describe('TypeScript HMR', () => {
const { next, isTurbopack } = nextTestSetup({ const { next, isTurbopack } = nextTestSetup({
...@@ -17,7 +17,7 @@ describe('TypeScript HMR', () => { ...@@ -17,7 +17,7 @@ describe('TypeScript HMR', () => {
const editedContent = originalContent.replace('Hello', 'COOL page') const editedContent = originalContent.replace('Hello', 'COOL page')
if (isTurbopack) { if (isTurbopack) {
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
} }
await next.patchFile('pages/hello.tsx', editedContent) await next.patchFile('pages/hello.tsx', editedContent)
...@@ -64,7 +64,7 @@ describe('TypeScript HMR', () => { ...@@ -64,7 +64,7 @@ describe('TypeScript HMR', () => {
'(): boolean => <p>hello with error</p>' '(): boolean => <p>hello with error</p>'
) )
if (isTurbopack) { if (isTurbopack) {
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
} }
try { try {
await next.patchFile('pages/type-error-recover.tsx', errContent) await next.patchFile('pages/type-error-recover.tsx', errContent)
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils' import { waitFor, check } from 'next-test-utils'
describe('app dir - css', () => { describe('app dir - css', () => {
const { next, isNextDev, skipped } = nextTestSetup({ const { next, isNextDev, skipped } = nextTestSetup({
...@@ -273,7 +273,7 @@ describe('app dir - css', () => { ...@@ -273,7 +273,7 @@ describe('app dir - css', () => {
await browser.elementByCss('button').click() await browser.elementByCss('button').click()
// Wait for error page to render and CSS to be loaded // Wait for error page to render and CSS to be loaded
await new Promise((resolve) => setTimeout(resolve, 2000)) await waitFor(2000)
await check( await check(
async () => async () =>
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { waitFor, retry } from 'next-test-utils'
describe('expire-time', () => { describe('expire-time', () => {
const { next, isNextDeploy } = nextTestSetup({ const { next, isNextDeploy } = nextTestSetup({
...@@ -46,7 +46,7 @@ describe('expire-time', () => { ...@@ -46,7 +46,7 @@ describe('expire-time', () => {
// Wait past the `expireTime` (10 s). The next request must trigger a // Wait past the `expireTime` (10 s). The next request must trigger a
// blocking prerender, not stale-while-revalidate — so the response // blocking prerender, not stale-while-revalidate — so the response
// returned right here carries a freshly-computed value. // 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 $third = await next.render$('/')
const v3 = $third('#value').text() const v3 = $third('#value').text()
......
import fs from 'fs' import fs from 'fs'
import path from 'path' import path from 'path'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { waitFor, retry } from 'next-test-utils'
describe('log-file', () => { describe('log-file', () => {
const { next, isNextDev, skipped } = nextTestSetup({ const { next, isNextDev, skipped } = nextTestSetup({
...@@ -91,7 +91,7 @@ describe('log-file', () => { ...@@ -91,7 +91,7 @@ describe('log-file', () => {
// Request to RSC page and wait for hydration // Request to RSC page and wait for hydration
await next.browser('/server') await next.browser('/server')
// Wait for logs to be written (increased timeout for batched logging) // Wait for logs to be written (increased timeout for batched logging)
await new Promise((resolve) => setTimeout(resolve, 2000)) await waitFor(2000)
if (isNextDev) { if (isNextDev) {
await retry(async () => { await retry(async () => {
...@@ -129,7 +129,7 @@ describe('log-file', () => { ...@@ -129,7 +129,7 @@ describe('log-file', () => {
) )
}) })
// Wait for logs to be written (reduced timeout with faster flush) // Wait for logs to be written (reduced timeout with faster flush)
await new Promise((resolve) => setTimeout(resolve, 2000)) await waitFor(2000)
if (isNextDev) { if (isNextDev) {
await retry(async () => { await retry(async () => {
...@@ -152,7 +152,7 @@ describe('log-file', () => { ...@@ -152,7 +152,7 @@ describe('log-file', () => {
// Make request to page with getServerSideProps // Make request to page with getServerSideProps
await next.browser('/pages-router-page') await next.browser('/pages-router-page')
// Wait for logs to be written (increased timeout for batched logging) // Wait for logs to be written (increased timeout for batched logging)
await new Promise((resolve) => setTimeout(resolve, 2000)) await waitFor(2000)
if (isNextDev) { if (isNextDev) {
await retry(async () => { await retry(async () => {
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils' import { waitFor, check } from 'next-test-utils'
describe('app dir - not-found - basic', () => { describe('app dir - not-found - basic', () => {
const { next, isNextDev, isNextStart, skipped } = nextTestSetup({ const { next, isNextDev, isNextStart, skipped } = nextTestSetup({
...@@ -121,9 +121,7 @@ describe('app dir - not-found - basic', () => { ...@@ -121,9 +121,7 @@ describe('app dir - not-found - basic', () => {
const browser = await next.browser('/random-content') const browser = await next.browser('/random-content')
const timestamp = await browser.elementByCss('#timestamp').text() const timestamp = await browser.elementByCss('#timestamp').text()
await new Promise((resolve) => { await waitFor(3000)
setTimeout(resolve, 3000)
})
await check(async () => { await check(async () => {
const newTimestamp = await browser.elementByCss('#timestamp').text() const newTimestamp = await browser.elementByCss('#timestamp').text()
......
import { nextTestSetup, FileRef } from 'e2e-utils' import { nextTestSetup, FileRef } from 'e2e-utils'
import { NextConfig } from 'next' import { NextConfig } from 'next'
import { check, retry } from 'next-test-utils' import { waitFor, check, retry } from 'next-test-utils'
import path from 'path' import path from 'path'
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
...@@ -502,9 +502,7 @@ describe.each([true, false])( ...@@ -502,9 +502,7 @@ describe.each([true, false])(
const browser = await next.browser('/parallel-no-page/foo') const browser = await next.browser('/parallel-no-page/foo')
const timestamp = await browser.elementByCss('#timestamp').text() const timestamp = await browser.elementByCss('#timestamp').text()
await new Promise((resolve) => { await waitFor(3000)
setTimeout(resolve, 3000)
})
await check(async () => { await check(async () => {
// an invalid response triggers a fast refresh, so if the timestamp doesn't update, this behaved correctly // 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])( ...@@ -517,9 +515,7 @@ describe.each([true, false])(
const browser = await next.browser('parallel-nested/home/nested') const browser = await next.browser('parallel-nested/home/nested')
const timestamp = await browser.elementByCss('#timestamp').text() const timestamp = await browser.elementByCss('#timestamp').text()
await new Promise((resolve) => { await waitFor(3000)
setTimeout(resolve, 3000)
})
await check(async () => { await check(async () => {
// an invalid response triggers a fast refresh, so if the timestamp doesn't update, this behaved correctly // 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' import { nextTestSetup } from 'e2e-utils'
// TODO(NAR-423): Migrate to Cache Components. // TODO(NAR-423): Migrate to Cache Components.
...@@ -39,7 +40,7 @@ describe.skip('prefetch-navigation', () => { ...@@ -39,7 +40,7 @@ describe.skip('prefetch-navigation', () => {
resolve: async () => { resolve: async () => {
await route.continue() await route.continue()
// wait a moment to ensure the response is received // wait a moment to ensure the response is received
await new Promise((res) => setTimeout(res, 500)) await waitFor(500)
resolvePromise() resolvePromise()
}, },
}) })
......
import { nextTestSetup } from 'e2e-utils' 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', () => { describe('app-dir refresh', () => {
const { next, skipped, isNextDev } = nextTestSetup({ const { next, skipped, isNextDev } = nextTestSetup({
...@@ -19,7 +24,7 @@ describe('app-dir refresh', () => { ...@@ -19,7 +24,7 @@ describe('app-dir refresh', () => {
expect(initialServerTimestamp).toBeTruthy() expect(initialServerTimestamp).toBeTruthy()
await new Promise((resolve) => setTimeout(resolve, 100)) await waitFor(100)
await browser.elementById('refresh-button').click() await browser.elementById('refresh-button').click()
......
import path from 'path' import path from 'path'
import { import {
waitFor,
check, check,
getClientReferenceManifest, getClientReferenceManifest,
getDistDir, getDistDir,
...@@ -221,10 +222,10 @@ describe('app dir - rsc basics', () => { ...@@ -221,10 +222,10 @@ describe('app dir - rsc basics', () => {
const browser = await next.browser('/root') const browser = await next.browser('/root')
await browser.waitForElementByCss('#goto-next-link').click() 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 check(() => browser.url(), `${next.url}/next-api/link`)
await browser.waitForElementByCss('#goto-home').click() await browser.waitForElementByCss('#goto-home').click()
await new Promise((res) => setTimeout(res, 1000)) await waitFor(1000)
await check(() => browser.url(), `${next.url}/root`) await check(() => browser.url(), `${next.url}/root`)
const content = await browser.elementByCss('body').text() const content = await browser.elementByCss('body').text()
expect(content).toContain('component:root.server') expect(content).toContain('component:root.server')
...@@ -284,7 +285,7 @@ describe('app dir - rsc basics', () => { ...@@ -284,7 +285,7 @@ describe('app dir - rsc basics', () => {
// it will be a full redirection instead of being taken over by the next // 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 // router. This timeout prevents it being flaky caused by fast refresh's
// rebuilding event. // rebuilding event.
await new Promise((res) => setTimeout(res, 1000)) await waitFor(1000)
await browser.eval('window.beforeNav = 1') await browser.eval('window.beforeNav = 1')
await browser.waitForElementByCss('#next_id').click() await browser.waitForElementByCss('#next_id').click()
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { waitFor, retry } from 'next-test-utils'
describe('searchparams-reuse-loading', () => { describe('searchparams-reuse-loading', () => {
const { next, isNextDev } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
...@@ -243,7 +243,7 @@ describe('searchparams-reuse-loading', () => { ...@@ -243,7 +243,7 @@ describe('searchparams-reuse-loading', () => {
resolve: async () => { resolve: async () => {
await route.continue() await route.continue()
// wait a moment to ensure the response is received // wait a moment to ensure the response is received
await new Promise((res) => setTimeout(res, 500)) await waitFor(500)
resolvePromise() resolvePromise()
}, },
}) })
...@@ -360,7 +360,7 @@ describe('searchparams-reuse-loading', () => { ...@@ -360,7 +360,7 @@ describe('searchparams-reuse-loading', () => {
resolve: async () => { resolve: async () => {
await route.continue() await route.continue()
// wait a moment to ensure the response is received // wait a moment to ensure the response is received
await new Promise((res) => setTimeout(res, 500)) await waitFor(500)
resolvePromise() resolvePromise()
}, },
}) })
...@@ -446,7 +446,7 @@ describe('searchparams-reuse-loading', () => { ...@@ -446,7 +446,7 @@ describe('searchparams-reuse-loading', () => {
resolve: async () => { resolve: async () => {
await route.continue() await route.continue()
// wait a moment to ensure the response is received // wait a moment to ensure the response is received
await new Promise((res) => setTimeout(res, 500)) await waitFor(500)
resolvePromise() resolvePromise()
}, },
}) })
...@@ -532,7 +532,7 @@ describe('searchparams-reuse-loading', () => { ...@@ -532,7 +532,7 @@ describe('searchparams-reuse-loading', () => {
resolve: async () => { resolve: async () => {
await route.continue() await route.continue()
// wait a moment to ensure the response is received // wait a moment to ensure the response is received
await new Promise((res) => setTimeout(res, 500)) await waitFor(500)
resolvePromise() resolvePromise()
}, },
}) })
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { retry, waitFor } from 'next-test-utils'
import { randomUUID } from 'crypto' import { randomUUID } from 'crypto'
import escapeStringRegexp from 'escape-string-regexp' import escapeStringRegexp from 'escape-string-regexp'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
...@@ -32,7 +32,7 @@ describe('use-cache-swr', () => { ...@@ -32,7 +32,7 @@ describe('use-cache-swr', () => {
expect(initialOuter).toBeDateString() expect(initialOuter).toBeDateString()
// Wait for the outer cache to go stale (revalidate: 5). // 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 // 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. // by the initial cold-fill set from the first fetch.
...@@ -83,7 +83,7 @@ describe('use-cache-swr', () => { ...@@ -83,7 +83,7 @@ describe('use-cache-swr', () => {
expect(dynamic1).toBeDateString() expect(dynamic1).toBeDateString()
// Wait past the 1s revalidate window (cacheLife('seconds')). // Wait past the 1s revalidate window (cacheLife('seconds')).
await new Promise((resolve) => setTimeout(resolve, 1200)) await waitFor(1200)
outputIndex = next.cliOutput.length outputIndex = next.cliOutput.length
...@@ -128,7 +128,7 @@ describe('use-cache-swr', () => { ...@@ -128,7 +128,7 @@ describe('use-cache-swr', () => {
expect(dynamic1).toBeDateString() expect(dynamic1).toBeDateString()
// Wait past the 1s revalidate window (cacheLife('seconds')). // Wait past the 1s revalidate window (cacheLife('seconds')).
await new Promise((resolve) => setTimeout(resolve, 1200)) await waitFor(1200)
outputIndex = next.cliOutput.length outputIndex = next.cliOutput.length
...@@ -168,7 +168,7 @@ describe('use-cache-swr', () => { ...@@ -168,7 +168,7 @@ describe('use-cache-swr', () => {
await browser.elementById('outer-data').text() await browser.elementById('outer-data').text()
// Wait for the outer cache to go stale (revalidate: 5). // 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. // Reset output index to capture only the SWR-related logs.
outputIndex = next.cliOutput.length outputIndex = next.cliOutput.length
...@@ -179,7 +179,7 @@ describe('use-cache-swr', () => { ...@@ -179,7 +179,7 @@ describe('use-cache-swr', () => {
await browser.refresh() await browser.refresh()
// Wait for the background regen to complete. // Wait for the background regen to complete.
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const cliOutput = next.cliOutput.slice(outputIndex) const cliOutput = next.cliOutput.slice(outputIndex)
......
...@@ -810,21 +810,21 @@ describe('use-cache', () => { ...@@ -810,21 +810,21 @@ describe('use-cache', () => {
// Click 1: revalidateTag with profile - should NOT cause immediate refresh // Click 1: revalidateTag with profile - should NOT cause immediate refresh
await browser.elementByCss('#revalidate-tag-with-profile').click() await browser.elementByCss('#revalidate-tag-with-profile').click()
// Wait for the action to complete // Wait for the action to complete
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const afterClick1 = await browser.elementByCss('#random').text() const afterClick1 = await browser.elementByCss('#random').text()
console.log('[Test] After click 1:', afterClick1) console.log('[Test] After click 1:', afterClick1)
expect(afterClick1).toBe(initial) // No change - stale-while-revalidate expect(afterClick1).toBe(initial) // No change - stale-while-revalidate
// Click 2: Same as click 1 - should still show stale data // Click 2: Same as click 1 - should still show stale data
await browser.elementByCss('#revalidate-tag-with-profile').click() 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() const afterClick2 = await browser.elementByCss('#random').text()
console.log('[Test] After click 2:', afterClick2) console.log('[Test] After click 2:', afterClick2)
expect(afterClick2).toBe(initial) // Still no change expect(afterClick2).toBe(initial) // Still no change
// Click 3: Same as before - should still show stale data (not data from click 1) // Click 3: Same as before - should still show stale data (not data from click 1)
await browser.elementByCss('#revalidate-tag-with-profile').click() 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() const afterClick3 = await browser.elementByCss('#random').text()
console.log('[Test] After click 3:', afterClick3) console.log('[Test] After click 3:', afterClick3)
expect(afterClick3).toBe(initial) // Still no change - no read-your-own-writes expect(afterClick3).toBe(initial) // Still no change - no read-your-own-writes
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
import http from 'http' import http from 'http'
import httpProxy from 'http-proxy' import httpProxy from 'http-proxy'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import { findPort } from 'next-test-utils' import { waitFor, findPort } from 'next-test-utils'
import { nextTestSetup, isNextDev, isNextStart } from 'e2e-utils' import { nextTestSetup, isNextDev, isNextStart } from 'e2e-utils'
describe('CSS Module client-side navigation', () => { describe('CSS Module client-side navigation', () => {
...@@ -40,7 +40,7 @@ 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') new URL(req.url, next.url).pathname.endsWith('.css')
) { ) {
console.log('stalling request for', req.url) console.log('stalling request for', req.url)
await new Promise((resolve) => setTimeout(resolve, 5 * 1000)) await waitFor(5 * 1000)
} }
proxy.web(req, res) proxy.web(req, res)
}) })
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { waitFor, retry } from 'next-test-utils'
import fs from 'fs' import fs from 'fs'
import path from 'path' import path from 'path'
...@@ -73,7 +73,7 @@ async function expectPngResponse(res: Response) { ...@@ -73,7 +73,7 @@ async function expectPngResponse(res: Response) {
} }
function sleep(ms: number) { function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms)) return waitFor(ms)
} }
async function waitForCallbackTimestampToStabilize( async function waitForCallbackTimestampToStabilize(
...@@ -513,7 +513,7 @@ describe('deferred-entries', () => { ...@@ -513,7 +513,7 @@ describe('deferred-entries', () => {
}) })
// Wait a bit to ensure timestamps will be different // 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 // Modify the home page (non-deferred entry) to trigger HMR
await next.patchFile('app/page.tsx', (content) => await next.patchFile('app/page.tsx', (content) =>
...@@ -556,7 +556,7 @@ describe('deferred-entries', () => { ...@@ -556,7 +556,7 @@ describe('deferred-entries', () => {
}) })
// Ensure callback timestamp changes after a non-deferred edit. // 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) => await next.patchFile('app/page.tsx', (content) =>
content.includes('Home Page Updated') content.includes('Home Page Updated')
? content.replace('Home Page Updated', 'Home Page Updated Again') ? content.replace('Home Page Updated', 'Home Page Updated Again')
......
/* eslint-disable jest/no-identical-title */ /* eslint-disable jest/no-identical-title */
import { nextTestSetup, isNextDev } from 'e2e-utils' 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) jest.retryTimes(0)
...@@ -30,7 +30,7 @@ describe('Invalid hrefs', () => { ...@@ -30,7 +30,7 @@ describe('Invalid hrefs', () => {
} }
if (click) { if (click) {
await browser.elementByCss('#click-me').click() await browser.elementByCss('#click-me').click()
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
} }
if (isWarn) { if (isWarn) {
await retry(async () => { await retry(async () => {
...@@ -63,7 +63,7 @@ describe('Invalid hrefs', () => { ...@@ -63,7 +63,7 @@ describe('Invalid hrefs', () => {
await browser.waitForElementByCss('#click-me') await browser.waitForElementByCss('#click-me')
if (click) { if (click) {
await browser.elementByCss('#click-me').click() await browser.elementByCss('#click-me').click()
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
} }
const caughtErrors = await browser.eval(`window.caughtErrors`) const caughtErrors = await browser.eval(`window.caughtErrors`)
expect(caughtErrors).toHaveLength(0) expect(caughtErrors).toHaveLength(0)
...@@ -102,7 +102,7 @@ describe('Invalid hrefs', () => { ...@@ -102,7 +102,7 @@ describe('Invalid hrefs', () => {
}) })
})()`) })()`)
await browser.elementByCss('a').click() await browser.elementByCss('a').click()
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
const errors = await browser.eval('window.caughtErrors') const errors = await browser.eval('window.caughtErrors')
expect( expect(
errors.find((err: string) => errors.find((err: string) =>
......
...@@ -5,7 +5,7 @@ import { ...@@ -5,7 +5,7 @@ import {
RSC_HEADER, RSC_HEADER,
} from 'next/src/client/components/app-router-headers' } from 'next/src/client/components/app-router-headers'
import type { Page, Request as PlaywrightRequest } from 'playwright' import type { Page, Request as PlaywrightRequest } from 'playwright'
import { retry } from 'next-test-utils' import { waitFor, retry } from 'next-test-utils'
const _describe = const _describe =
// prefetching is disabled in dev. // prefetching is disabled in dev.
...@@ -218,7 +218,7 @@ class RequestInterceptor { ...@@ -218,7 +218,7 @@ class RequestInterceptor {
this.pendingRequests.delete(requestKey) this.pendingRequests.delete(requestKey)
await route.continue() await route.continue()
// wait a moment to ensure the response is received // wait a moment to ensure the response is received
await new Promise((res) => setTimeout(res, 500)) await waitFor(500)
blocked.resolve() blocked.resolve()
}, },
}) })
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils' import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils'
describe('Build Error Tests for basePath', () => { describe('Build Error Tests for basePath', () => {
...@@ -63,7 +64,7 @@ describe('Static Image Component Tests for basePath', () => { ...@@ -63,7 +64,7 @@ describe('Static Image Component Tests for basePath', () => {
await browser.eval( await browser.eval(
`document.getElementById("basic-static").scrollIntoView()` `document.getElementById("basic-static").scrollIntoView()`
) )
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const url = await browser.eval( const url = await browser.eval(
`document.getElementById("basic-static").src` `document.getElementById("basic-static").src`
) )
...@@ -78,7 +79,7 @@ describe('Static Image Component Tests for basePath', () => { ...@@ -78,7 +79,7 @@ describe('Static Image Component Tests for basePath', () => {
await browser.eval( await browser.eval(
`document.getElementById("static-unoptimized").scrollIntoView()` `document.getElementById("static-unoptimized").scrollIntoView()`
) )
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const url = await browser.eval( const url = await browser.eval(
`document.getElementById("static-unoptimized").src` `document.getElementById("static-unoptimized").src`
) )
......
import { nextTestSetup, isNextDev } from 'e2e-utils' import { nextTestSetup, isNextDev } from 'e2e-utils'
import { import {
waitFor,
waitForRedbox, waitForRedbox,
waitForNoRedbox, waitForNoRedbox,
getRedboxHeader, getRedboxHeader,
...@@ -369,7 +370,7 @@ describe('Legacy Image Component basePath Tests', () => { ...@@ -369,7 +370,7 @@ describe('Legacy Image Component basePath Tests', () => {
expect(result).toBeGreaterThan(0) expect(result).toBeGreaterThan(0)
}) })
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width') const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height') const computedHeight = await getComputed(browser, id, 'height')
...@@ -389,7 +390,7 @@ describe('Legacy Image Component basePath Tests', () => { ...@@ -389,7 +390,7 @@ describe('Legacy Image Component basePath Tests', () => {
expect(result).toBeGreaterThan(0) expect(result).toBeGreaterThan(0)
}) })
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width') const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height') const computedHeight = await getComputed(browser, id, 'height')
......
/* eslint-disable jest/no-standalone-expect */ /* eslint-disable jest/no-standalone-expect */
import { waitFor } from 'next-test-utils'
import { import {
nextTestSetup, nextTestSetup,
isNextDev, isNextDev,
...@@ -74,7 +75,7 @@ describe('Static Image Component Tests', () => { ...@@ -74,7 +75,7 @@ describe('Static Image Component Tests', () => {
await browser.eval( await browser.eval(
`document.getElementById("basic-static").scrollIntoView()` `document.getElementById("basic-static").scrollIntoView()`
) )
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const url = await browser.eval( const url = await browser.eval(
`document.getElementById("basic-static").src` `document.getElementById("basic-static").src`
) )
...@@ -90,7 +91,7 @@ describe('Static Image Component Tests', () => { ...@@ -90,7 +91,7 @@ describe('Static Image Component Tests', () => {
await browser.eval( await browser.eval(
`document.getElementById("static-unoptimized").scrollIntoView()` `document.getElementById("static-unoptimized").scrollIntoView()`
) )
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const url = await browser.eval( const url = await browser.eval(
`document.getElementById("static-unoptimized").src` `document.getElementById("static-unoptimized").src`
) )
......
...@@ -2,6 +2,7 @@ import cheerio from 'cheerio' ...@@ -2,6 +2,7 @@ import cheerio from 'cheerio'
import validateHTML from 'html-validator' import validateHTML from 'html-validator'
import { nextTestSetup, isNextDev } from 'e2e-utils' import { nextTestSetup, isNextDev } from 'e2e-utils'
import { import {
waitFor,
waitForRedbox, waitForRedbox,
waitForNoRedbox, waitForNoRedbox,
getRedboxHeader, getRedboxHeader,
...@@ -728,7 +729,7 @@ describe('Image Component Tests', () => { ...@@ -728,7 +729,7 @@ describe('Image Component Tests', () => {
) )
if (isNextDev) { if (isNextDev) {
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.join('\n') .join('\n')
...@@ -816,7 +817,7 @@ describe('Image Component Tests', () => { ...@@ -816,7 +817,7 @@ describe('Image Component Tests', () => {
it('should warn when img with layout=fill is inside a container without position relative', async () => { 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') const browser = await next.browser('/layout-fill-inside-nonrelative')
await browser.eval(`document.querySelector("footer").scrollIntoView()`) await browser.eval(`document.querySelector("footer").scrollIntoView()`)
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.join('\n') .join('\n')
...@@ -880,7 +881,7 @@ describe('Image Component Tests', () => { ...@@ -880,7 +881,7 @@ describe('Image Component Tests', () => {
) )
expect(result).toBeGreaterThan(0) expect(result).toBeGreaterThan(0)
}) })
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.join('\n') .join('\n')
...@@ -974,7 +975,7 @@ describe('Image Component Tests', () => { ...@@ -974,7 +975,7 @@ describe('Image Component Tests', () => {
) )
expect(result).toBeGreaterThan(0) expect(result).toBeGreaterThan(0)
}) })
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.filter((log) => log.startsWith('Image with src')) .filter((log) => log.startsWith('Image with src'))
...@@ -1008,7 +1009,7 @@ describe('Image Component Tests', () => { ...@@ -1008,7 +1009,7 @@ describe('Image Component Tests', () => {
expect(result).toBeGreaterThan(0) expect(result).toBeGreaterThan(0)
}) })
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width') const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height') const computedHeight = await getComputed(browser, id, 'height')
...@@ -1058,7 +1059,7 @@ describe('Image Component Tests', () => { ...@@ -1058,7 +1059,7 @@ describe('Image Component Tests', () => {
const src = await getSrc(browser, 'img-blur') const src = await getSrc(browser, 'img-blur')
expect(src).toMatch(/^\/_next\/image/) expect(src).toMatch(/^\/_next\/image/)
}) })
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
expect(await getComputedStyle(browser, 'img-plain', 'filter')).toBe( expect(await getComputedStyle(browser, 'img-plain', 'filter')).toBe(
'opacity(0.5)' 'opacity(0.5)'
...@@ -1108,7 +1109,7 @@ describe('Image Component Tests', () => { ...@@ -1108,7 +1109,7 @@ describe('Image Component Tests', () => {
expect(result).toBeGreaterThan(0) expect(result).toBeGreaterThan(0)
}) })
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width') const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height') const computedHeight = await getComputed(browser, id, 'height')
...@@ -1287,7 +1288,7 @@ describe('Image Component Tests', () => { ...@@ -1287,7 +1288,7 @@ describe('Image Component Tests', () => {
it('should be valid HTML', async () => { it('should be valid HTML', async () => {
const browser = await next.browser('/valid-html-w3c') const browser = await next.browser('/valid-html-w3c')
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
expect(await browser.hasElementByCssSelector('img')).toBeTruthy() expect(await browser.hasElementByCssSelector('img')).toBeTruthy()
const url = await browser.url() const url = await browser.url()
const result = (await validateHTML({ const result = (await validateHTML({
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils' import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
...@@ -85,7 +86,7 @@ import cheerio from 'cheerio' ...@@ -85,7 +86,7 @@ import cheerio from 'cheerio'
await browser.eval( await browser.eval(
`document.getElementById("basic-static").scrollIntoView()` `document.getElementById("basic-static").scrollIntoView()`
) )
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const url = await browser.eval( const url = await browser.eval(
`document.getElementById("basic-static").src` `document.getElementById("basic-static").src`
) )
...@@ -101,7 +102,7 @@ import cheerio from 'cheerio' ...@@ -101,7 +102,7 @@ import cheerio from 'cheerio'
await browser.eval( await browser.eval(
`document.getElementById("static-unoptimized").scrollIntoView()` `document.getElementById("static-unoptimized").scrollIntoView()`
) )
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const url = await browser.eval( const url = await browser.eval(
`document.getElementById("static-unoptimized").src` `document.getElementById("static-unoptimized").src`
) )
......
import cheerio from 'cheerio' import cheerio from 'cheerio'
import validateHTML from 'html-validator' import validateHTML from 'html-validator'
import { import {
waitFor,
waitForRedbox, waitForRedbox,
waitForNoRedbox, waitForNoRedbox,
getRedboxHeader, getRedboxHeader,
...@@ -765,7 +766,7 @@ describe('Image Component App Dir Tests', () => { ...@@ -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` `/_next/image?url=%2Ftest.png&w=640&q=75${dpl} 1x, /_next/image?url=%2Ftest.png&w=828&q=75${dpl} 2x`
) )
if (isNextDev) { if (isNextDev) {
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.join('\n') .join('\n')
...@@ -1203,7 +1204,7 @@ describe('Image Component App Dir Tests', () => { ...@@ -1203,7 +1204,7 @@ describe('Image Component App Dir Tests', () => {
) )
expect(result).toBeGreaterThan(0) expect(result).toBeGreaterThan(0)
}) })
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.join('\n') .join('\n')
...@@ -1287,7 +1288,7 @@ describe('Image Component App Dir Tests', () => { ...@@ -1287,7 +1288,7 @@ describe('Image Component App Dir Tests', () => {
) )
expect(result).toBeGreaterThan(0) expect(result).toBeGreaterThan(0)
}) })
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.filter((log) => log.startsWith('Image with src')) .filter((log) => log.startsWith('Image with src'))
...@@ -1348,7 +1349,7 @@ describe('Image Component App Dir Tests', () => { ...@@ -1348,7 +1349,7 @@ describe('Image Component App Dir Tests', () => {
expect(result).toBeGreaterThan(0) expect(result).toBeGreaterThan(0)
}) })
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width') const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height') const computedHeight = await getComputed(browser, id, 'height')
...@@ -1396,7 +1397,7 @@ describe('Image Component App Dir Tests', () => { ...@@ -1396,7 +1397,7 @@ describe('Image Component App Dir Tests', () => {
await retry(async () => { await retry(async () => {
expect(await getSrc(browser, 'img-blur')).toMatch(/^\/_next\/image/) 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( expect(await getComputedStyle(browser, 'img-plain', 'filter')).toBe(
'opacity(0.5)' 'opacity(0.5)'
...@@ -1471,7 +1472,7 @@ describe('Image Component App Dir Tests', () => { ...@@ -1471,7 +1472,7 @@ describe('Image Component App Dir Tests', () => {
}) })
if (isNextDev) { if (isNextDev) {
it('should not log incorrect warnings', async () => { it('should not log incorrect warnings', async () => {
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.join('\n') .join('\n')
...@@ -1482,7 +1483,7 @@ describe('Image Component App Dir Tests', () => { ...@@ -1482,7 +1483,7 @@ describe('Image Component App Dir Tests', () => {
}) })
it('should log warnings when using fill mode incorrectly', async () => { it('should log warnings when using fill mode incorrectly', async () => {
browser = await next.browser('/fill-warnings') browser = await next.browser('/fill-warnings')
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.join('\n') .join('\n')
...@@ -1501,7 +1502,7 @@ describe('Image Component App Dir Tests', () => { ...@@ -1501,7 +1502,7 @@ describe('Image Component App Dir Tests', () => {
}) })
it('should not log warnings when image unmounts', async () => { it('should not log warnings when image unmounts', async () => {
browser = await next.browser('/should-not-warn-unmount') browser = await next.browser('/should-not-warn-unmount')
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.join('\n') .join('\n')
...@@ -1526,7 +1527,7 @@ describe('Image Component App Dir Tests', () => { ...@@ -1526,7 +1527,7 @@ describe('Image Component App Dir Tests', () => {
expect(result).not.toBe(0) expect(result).not.toBe(0)
}) })
await new Promise((r) => setTimeout(r, 500)) await waitFor(500)
const computedWidth = await getComputed(browser, id, 'width') const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height') const computedHeight = await getComputed(browser, id, 'height')
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils' import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
...@@ -74,7 +75,7 @@ describe('Static Image Component Tests for basePath', () => { ...@@ -74,7 +75,7 @@ describe('Static Image Component Tests for basePath', () => {
await browser.eval( await browser.eval(
`document.getElementById("basic-static").scrollIntoView()` `document.getElementById("basic-static").scrollIntoView()`
) )
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const url = await browser.eval( const url = await browser.eval(
`document.getElementById("basic-static").src` `document.getElementById("basic-static").src`
) )
...@@ -88,7 +89,7 @@ describe('Static Image Component Tests for basePath', () => { ...@@ -88,7 +89,7 @@ describe('Static Image Component Tests for basePath', () => {
await browser.eval( await browser.eval(
`document.getElementById("static-unoptimized").scrollIntoView()` `document.getElementById("static-unoptimized").scrollIntoView()`
) )
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const url = await browser.eval( const url = await browser.eval(
`document.getElementById("static-unoptimized").src` `document.getElementById("static-unoptimized").src`
) )
......
import { nextTestSetup, isNextDev } from 'e2e-utils' import { nextTestSetup, isNextDev } from 'e2e-utils'
import { import {
waitFor,
waitForRedbox, waitForRedbox,
waitForNoRedbox, waitForNoRedbox,
getRedboxHeader, getRedboxHeader,
...@@ -142,7 +143,7 @@ describe('Image Component basePath Tests', () => { ...@@ -142,7 +143,7 @@ describe('Image Component basePath Tests', () => {
expect(result).toBeGreaterThan(0) expect(result).toBeGreaterThan(0)
}) })
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width') const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height') const computedHeight = await getComputed(browser, id, 'height')
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils' import { nextTestSetup, isNextDev, type Playwright } from 'e2e-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
...@@ -76,7 +77,7 @@ describe('Static Image Component Tests', () => { ...@@ -76,7 +77,7 @@ describe('Static Image Component Tests', () => {
await browser.eval( await browser.eval(
`document.getElementById("basic-static").scrollIntoView()` `document.getElementById("basic-static").scrollIntoView()`
) )
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const url = await browser.eval( const url = await browser.eval(
`document.getElementById("basic-static").src` `document.getElementById("basic-static").src`
) )
...@@ -90,7 +91,7 @@ describe('Static Image Component Tests', () => { ...@@ -90,7 +91,7 @@ describe('Static Image Component Tests', () => {
await browser.eval( await browser.eval(
`document.getElementById("static-unoptimized").scrollIntoView()` `document.getElementById("static-unoptimized").scrollIntoView()`
) )
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
const url = await browser.eval( const url = await browser.eval(
`document.getElementById("static-unoptimized").src` `document.getElementById("static-unoptimized").src`
) )
......
import cheerio from 'cheerio' import cheerio from 'cheerio'
import validateHTML from 'html-validator' import validateHTML from 'html-validator'
import { import {
waitFor,
waitForRedbox, waitForRedbox,
waitForNoRedbox, waitForNoRedbox,
getRedboxHeader, getRedboxHeader,
...@@ -766,7 +767,7 @@ describe('Image Component Default Tests', () => { ...@@ -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` `/_next/image?url=%2Ftest.png&w=640&q=75${dpl} 1x, /_next/image?url=%2Ftest.png&w=828&q=75${dpl} 2x`
) )
if (isNextDev) { if (isNextDev) {
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.join('\n') .join('\n')
...@@ -1204,7 +1205,7 @@ describe('Image Component Default Tests', () => { ...@@ -1204,7 +1205,7 @@ describe('Image Component Default Tests', () => {
) )
expect(result).toBeGreaterThan(0) expect(result).toBeGreaterThan(0)
}) })
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.join('\n') .join('\n')
...@@ -1288,7 +1289,7 @@ describe('Image Component Default Tests', () => { ...@@ -1288,7 +1289,7 @@ describe('Image Component Default Tests', () => {
) )
expect(result).toBeGreaterThan(0) expect(result).toBeGreaterThan(0)
}) })
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.filter((log) => log.startsWith('Image with src')) .filter((log) => log.startsWith('Image with src'))
...@@ -1354,7 +1355,7 @@ describe('Image Component Default Tests', () => { ...@@ -1354,7 +1355,7 @@ describe('Image Component Default Tests', () => {
expect(result).toBeGreaterThan(0) expect(result).toBeGreaterThan(0)
}) })
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width') const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height') const computedHeight = await getComputed(browser, id, 'height')
...@@ -1402,7 +1403,7 @@ describe('Image Component Default Tests', () => { ...@@ -1402,7 +1403,7 @@ describe('Image Component Default Tests', () => {
await retry(async () => { await retry(async () => {
expect(await getSrc(browser, 'img-blur')).toMatch(/^\/_next\/image/) 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( expect(await getComputedStyle(browser, 'img-plain', 'filter')).toBe(
'opacity(0.5)' 'opacity(0.5)'
...@@ -1477,7 +1478,7 @@ describe('Image Component Default Tests', () => { ...@@ -1477,7 +1478,7 @@ describe('Image Component Default Tests', () => {
}) })
if (isNextDev) { if (isNextDev) {
it('should not log incorrect warnings', async () => { it('should not log incorrect warnings', async () => {
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.join('\n') .join('\n')
...@@ -1488,7 +1489,7 @@ describe('Image Component Default Tests', () => { ...@@ -1488,7 +1489,7 @@ describe('Image Component Default Tests', () => {
}) })
it('should log warnings when using fill mode incorrectly', async () => { it('should log warnings when using fill mode incorrectly', async () => {
browser = await next.browser('/fill-warnings') browser = await next.browser('/fill-warnings')
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.join('\n') .join('\n')
...@@ -1507,7 +1508,7 @@ describe('Image Component Default Tests', () => { ...@@ -1507,7 +1508,7 @@ describe('Image Component Default Tests', () => {
}) })
it('should not log warnings when image unmounts', async () => { it('should not log warnings when image unmounts', async () => {
browser = await next.browser('/should-not-warn-unmount') browser = await next.browser('/should-not-warn-unmount')
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
const warnings = (await browser.log()) const warnings = (await browser.log())
.map((log) => log.message) .map((log) => log.message)
.join('\n') .join('\n')
...@@ -1532,7 +1533,7 @@ describe('Image Component Default Tests', () => { ...@@ -1532,7 +1533,7 @@ describe('Image Component Default Tests', () => {
expect(result).not.toBe(0) expect(result).not.toBe(0)
}) })
await new Promise((r) => setTimeout(r, 500)) await waitFor(500)
const computedWidth = await getComputed(browser, id, 'width') const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height') const computedHeight = await getComputed(browser, id, 'height')
...@@ -1685,7 +1686,7 @@ describe('Image Component Default Tests', () => { ...@@ -1685,7 +1686,7 @@ describe('Image Component Default Tests', () => {
it('should be valid HTML', async () => { it('should be valid HTML', async () => {
const browser = await next.browser('/valid-html-w3c') const browser = await next.browser('/valid-html-w3c')
await new Promise((r) => setTimeout(r, 1000)) await waitFor(1000)
expect(await browser.hasElementByCssSelector('img')).toBeTruthy() expect(await browser.hasElementByCssSelector('img')).toBeTruthy()
const url = await browser.url() const url = await browser.url()
const result = (await validateHTML({ const result = (await validateHTML({
......
import { FileRef, isNextDev, isNextStart, nextTestSetup } from 'e2e-utils' 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 { NEXT_RSC_UNION_QUERY } from 'next/dist/client/components/app-router-headers'
import path from 'path' import path from 'path'
......
...@@ -28,6 +28,7 @@ import type { SpawnOptions, ChildProcess } from 'child_process' ...@@ -28,6 +28,7 @@ import type { SpawnOptions, ChildProcess } from 'child_process'
import type { NextServer } from 'next/dist/server/next' import type { NextServer } from 'next/dist/server/next'
import type { Playwright } from './browsers/playwright' import type { Playwright } from './browsers/playwright'
import { recursiveReadDir } from 'next/dist/lib/recursive-readdir' import { recursiveReadDir } from 'next/dist/lib/recursive-readdir'
import { wait } from 'next/dist/lib/wait'
import { shouldUseTurbopack } from './turbo' import { shouldUseTurbopack } from './turbo'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
...@@ -792,11 +793,18 @@ export async function stopApp(server: http.Server | undefined) { ...@@ -792,11 +793,18 @@ export async function stopApp(server: http.Server | undefined) {
await promisify(server.close).apply(server) 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( export async function waitFor(
millisOrCondition: number | (() => boolean) millisOrCondition: number | (() => boolean)
): Promise<void> { ): Promise<void> {
if (typeof millisOrCondition === 'number') { if (typeof millisOrCondition === 'number') {
return new Promise((resolve) => setTimeout(resolve, millisOrCondition)) return wait(millisOrCondition)
} }
return new Promise((resolve) => { return new Promise((resolve) => {
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
describe('unstable-cache-foreground-revalidate', () => { describe('unstable-cache-foreground-revalidate', () => {
...@@ -18,13 +19,13 @@ describe('unstable-cache-foreground-revalidate', () => { ...@@ -18,13 +19,13 @@ describe('unstable-cache-foreground-revalidate', () => {
const initialLogLength = next.cliOutput.length const initialLogLength = next.cliOutput.length
// Wait for both ISR and unstable_cache to become stale // 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 // This request triggers ISR background revalidation
await next.render('/isr-10') await next.render('/isr-10')
// Wait for ISR background revalidation to complete // Wait for ISR background revalidation to complete
await new Promise((resolve) => setTimeout(resolve, 2000)) await waitFor(2000)
// Get logs since the initial render // Get logs since the initial render
const logs = next.cliOutput.substring(initialLogLength) const logs = next.cliOutput.substring(initialLogLength)
...@@ -76,10 +77,10 @@ describe('unstable-cache-foreground-revalidate', () => { ...@@ -76,10 +77,10 @@ describe('unstable-cache-foreground-revalidate', () => {
const initialLogLength = next.cliOutput.length const initialLogLength = next.cliOutput.length
await new Promise((resolve) => setTimeout(resolve, 11000)) await waitFor(11000)
await next.render('/isr-10-nested') await next.render('/isr-10-nested')
await new Promise((resolve) => setTimeout(resolve, 2000)) await waitFor(2000)
const logs = next.cliOutput.substring(initialLogLength) const logs = next.cliOutput.substring(initialLogLength)
const cacheExecutions = [ const cacheExecutions = [
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
describe('handle already sent response', () => { describe('handle already sent response', () => {
...@@ -24,7 +25,7 @@ describe('handle already sent response', () => { ...@@ -24,7 +25,7 @@ describe('handle already sent response', () => {
if ((next.cliOutput.match(/getServerSideProps/g) || []).length >= 2) { if ((next.cliOutput.match(/getServerSideProps/g) || []).length >= 2) {
break break
} }
await new Promise((resolve) => setTimeout(resolve, 1000)) await waitFor(1000)
} }
if (i === 3) { if (i === 3) {
throw new Error('Timed out waiting for logs to show') throw new Error('Timed out waiting for logs to show')
......
import { nextTestSetup, type Playwright } from 'e2e-utils' import { nextTestSetup, type Playwright } from 'e2e-utils'
import { retry } from 'next-test-utils' import { waitFor, retry } from 'next-test-utils'
const emptyImage = const emptyImage =
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7' 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
...@@ -207,7 +207,7 @@ describe('Image Component Tests', () => { ...@@ -207,7 +207,7 @@ describe('Image Component Tests', () => {
await b.eval( await b.eval(
`window.scrollTo(0, ${topOfBottomImage - (viewportHeight + buffer)})` `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( expect(await b.elementById('lazy-bottom').getAttribute('src')).toBe(
'https://next-data-api-endpoint.vercel.app/next-image-legacy/lazy3.jpg' 'https://next-data-api-endpoint.vercel.app/next-image-legacy/lazy3.jpg'
) )
...@@ -231,7 +231,7 @@ describe('Image Component Tests', () => { ...@@ -231,7 +231,7 @@ describe('Image Component Tests', () => {
await b.eval( await b.eval(
`window.scrollTo(0, ${topOfBottomImage - (viewportHeight + buffer)})` `window.scrollTo(0, ${topOfBottomImage - (viewportHeight + buffer)})`
) )
await new Promise((r) => setTimeout(r, 200)) await waitFor(200)
expect( expect(
await b.elementById('lazy-without-attribute').getAttribute('src') await b.elementById('lazy-without-attribute').getAttribute('src')
).toBe( ).toBe(
...@@ -422,7 +422,7 @@ describe('Image Component Tests', () => { ...@@ -422,7 +422,7 @@ describe('Image Component Tests', () => {
beforeAll(async () => { beforeAll(async () => {
browser = await next.browser('/') browser = await next.browser('/')
await browser.waitForElementByCss('#lazylink').click() await browser.waitForElementByCss('#lazylink').click()
await new Promise((r) => setTimeout(r, 500)) await waitFor(500)
}) })
lazyLoadingTests(() => browser) lazyLoadingTests(() => browser)
}) })
......
import { waitFor } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
const strictRouteTypes = const strictRouteTypes =
...@@ -120,7 +121,7 @@ describe('tsconfig.json verifier', () => { ...@@ -120,7 +121,7 @@ describe('tsconfig.json verifier', () => {
expect(await next.hasFile('tsconfig.json')).toBe(false) expect(await next.hasFile('tsconfig.json')).toBe(false)
await next.patchFile('tsconfig.json', '') await next.patchFile('tsconfig.json', '')
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
expect(await next.readFile('tsconfig.json')).toBe('') expect(await next.readFile('tsconfig.json')).toBe('')
const { exitCode, cliOutput } = await next.build() const { exitCode, cliOutput } = await next.build()
...@@ -232,7 +233,7 @@ describe('tsconfig.json verifier', () => { ...@@ -232,7 +233,7 @@ describe('tsconfig.json verifier', () => {
// end comment // end comment
` `
) )
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
const { exitCode } = await next.build() const { exitCode } = await next.build()
expect(exitCode).toBe(0) expect(exitCode).toBe(0)
...@@ -350,7 +351,7 @@ describe('tsconfig.json verifier', () => { ...@@ -350,7 +351,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json', 'tsconfig.json',
`{ "compilerOptions": { "esModuleInterop": false, "module": "es2020" } }` `{ "compilerOptions": { "esModuleInterop": false, "module": "es2020" } }`
) )
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
const { exitCode } = await next.build() const { exitCode } = await next.build()
expect(exitCode).toBe(0) expect(exitCode).toBe(0)
...@@ -446,7 +447,7 @@ describe('tsconfig.json verifier', () => { ...@@ -446,7 +447,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json', 'tsconfig.json',
`{ "compilerOptions": { "esModuleInterop": false, "moduleResolution": "node16", "module": "node16" } }` `{ "compilerOptions": { "esModuleInterop": false, "moduleResolution": "node16", "module": "node16" } }`
) )
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
const { exitCode, cliOutput } = await next.build() const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('moduleResolution') expect(cliOutput).not.toContain('moduleResolution')
expect(exitCode).toBe(0) expect(exitCode).toBe(0)
...@@ -543,7 +544,7 @@ describe('tsconfig.json verifier', () => { ...@@ -543,7 +544,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json', 'tsconfig.json',
`{ "compilerOptions": { "esModuleInterop": false, "moduleResolution": "bundler" } }` `{ "compilerOptions": { "esModuleInterop": false, "moduleResolution": "bundler" } }`
) )
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
const { exitCode, cliOutput } = await next.build() const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('moduleResolution') expect(cliOutput).not.toContain('moduleResolution')
expect(exitCode).toBe(0) expect(exitCode).toBe(0)
...@@ -640,7 +641,7 @@ describe('tsconfig.json verifier', () => { ...@@ -640,7 +641,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json', 'tsconfig.json',
`{ "compilerOptions": { "target": "es2022" } }` `{ "compilerOptions": { "target": "es2022" } }`
) )
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
const { exitCode, cliOutput } = await next.build() const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('target') expect(cliOutput).not.toContain('target')
expect(exitCode).toBe(0) expect(exitCode).toBe(0)
...@@ -737,7 +738,7 @@ describe('tsconfig.json verifier', () => { ...@@ -737,7 +738,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json', 'tsconfig.json',
`{ "compilerOptions": { "esModuleInterop": false, "module": "node16", "moduleResolution": "node16" } }` `{ "compilerOptions": { "esModuleInterop": false, "module": "node16", "moduleResolution": "node16" } }`
) )
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
const { exitCode, cliOutput } = await next.build() const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('moduleResolution') expect(cliOutput).not.toContain('moduleResolution')
expect(exitCode).toBe(0) expect(exitCode).toBe(0)
...@@ -834,7 +835,7 @@ describe('tsconfig.json verifier', () => { ...@@ -834,7 +835,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json', 'tsconfig.json',
`{ "compilerOptions": { "verbatimModuleSyntax": true } }` `{ "compilerOptions": { "verbatimModuleSyntax": true } }`
) )
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
const { exitCode, cliOutput } = await next.build() const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('isolatedModules') expect(cliOutput).not.toContain('isolatedModules')
expect(exitCode).toBe(0) expect(exitCode).toBe(0)
...@@ -972,7 +973,7 @@ describe('tsconfig.json verifier', () => { ...@@ -972,7 +973,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json', 'tsconfig.json',
`{ "extends": "./tsconfig.base.json" }` `{ "extends": "./tsconfig.base.json" }`
) )
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
const { exitCode, cliOutput } = await next.build() const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('isolatedModules') expect(cliOutput).not.toContain('isolatedModules')
expect(exitCode).toBe(0) expect(exitCode).toBe(0)
...@@ -1028,13 +1029,13 @@ describe('tsconfig.json verifier', () => { ...@@ -1028,13 +1029,13 @@ describe('tsconfig.json verifier', () => {
} }
` `
) )
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
await next.patchFile( await next.patchFile(
'tsconfig.json', 'tsconfig.json',
`{ "extends": "./tsconfig.base.json" }` `{ "extends": "./tsconfig.base.json" }`
) )
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
const { exitCode, cliOutput } = await next.build() const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('moduleResolution') expect(cliOutput).not.toContain('moduleResolution')
...@@ -1090,13 +1091,13 @@ describe('tsconfig.json verifier', () => { ...@@ -1090,13 +1091,13 @@ describe('tsconfig.json verifier', () => {
} }
` `
) )
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
await next.patchFile( await next.patchFile(
'tsconfig.json', 'tsconfig.json',
`{ "extends": "./tsconfig.base.json" }` `{ "extends": "./tsconfig.base.json" }`
) )
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
const { exitCode, cliOutput } = await next.build() const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('moduleResolution') expect(cliOutput).not.toContain('moduleResolution')
...@@ -1115,7 +1116,7 @@ describe('tsconfig.json verifier', () => { ...@@ -1115,7 +1116,7 @@ describe('tsconfig.json verifier', () => {
'tsconfig.json', 'tsconfig.json',
`{ "compilerOptions": { "module": "preserve" } }` `{ "compilerOptions": { "module": "preserve" } }`
) )
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
const { exitCode, cliOutput } = await next.build() const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('moduleResolution') expect(cliOutput).not.toContain('moduleResolution')
expect(cliOutput).not.toContain('esModuleInterop') expect(cliOutput).not.toContain('esModuleInterop')
...@@ -1167,7 +1168,7 @@ describe('tsconfig.json verifier 5.x', () => { ...@@ -1167,7 +1168,7 @@ describe('tsconfig.json verifier 5.x', () => {
'tsconfig.json', 'tsconfig.json',
`{ "compilerOptions": { "esModuleInterop": false, "module": "commonjs" } }` `{ "compilerOptions": { "esModuleInterop": false, "module": "commonjs" } }`
) )
await new Promise((resolve) => setTimeout(resolve, 500)) await waitFor(500)
const { exitCode } = await next.build() const { exitCode } = await next.build()
expect(exitCode).toBe(0) expect(exitCode).toBe(0)
......
/* eslint-env jest */ /* eslint-env jest */
import { wait } from '../../packages/next/src/lib/wait'
import { import {
IntervalsManager, IntervalsManager,
TimeoutsManager, TimeoutsManager,
...@@ -8,13 +9,13 @@ import { ...@@ -8,13 +9,13 @@ import {
// value passed to timer callbacks. // value passed to timer callbacks.
const globalObject = {} as any const globalObject = {} as any
async function waitFor(condition: () => boolean, timeoutMs = 1000) { async function waitForCondition(condition: () => boolean, timeoutMs = 1000) {
const start = Date.now() const start = Date.now()
while (!condition()) { while (!condition()) {
if (Date.now() - start > timeoutMs) { 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', () => { ...@@ -38,8 +39,8 @@ describe('web sandbox TimeoutsManager', () => {
// After they complete naturally, tracking must drop back to zero even // After they complete naturally, tracking must drop back to zero even
// though user code never called clearTimeout. // though user code never called clearTimeout.
await waitFor(() => ran === count) await waitForCondition(() => ran === count)
await waitFor(() => manager.size === 0) await waitForCondition(() => manager.size === 0)
expect(manager.size).toBe(0) expect(manager.size).toBe(0)
}) })
...@@ -50,7 +51,7 @@ describe('web sandbox TimeoutsManager', () => { ...@@ -50,7 +51,7 @@ describe('web sandbox TimeoutsManager', () => {
for (let i = 0; i < 20; i++) { for (let i = 0; i < 20; i++) {
manager.add([globalObject, () => {}, 0]) manager.add([globalObject, () => {}, 0])
} }
await waitFor(() => manager.size === 0) await waitForCondition(() => manager.size === 0)
} }
expect(manager.size).toBe(0) expect(manager.size).toBe(0)
...@@ -72,7 +73,7 @@ describe('web sandbox TimeoutsManager', () => { ...@@ -72,7 +73,7 @@ describe('web sandbox TimeoutsManager', () => {
'b', 'b',
]) ])
await waitFor(() => observedArgs.length > 0) await waitForCondition(() => observedArgs.length > 0)
expect(observedThis).toBe(globalObject) expect(observedThis).toBe(globalObject)
expect(observedArgs).toEqual(['a', 'b']) expect(observedArgs).toEqual(['a', 'b'])
expect(manager.size).toBe(0) expect(manager.size).toBe(0)
...@@ -105,8 +106,8 @@ describe('web sandbox TimeoutsManager', () => { ...@@ -105,8 +106,8 @@ describe('web sandbox TimeoutsManager', () => {
let ran = false let ran = false
const firedId = manager.add([globalObject, () => (ran = true), 0]) const firedId = manager.add([globalObject, () => (ran = true), 0])
const pendingId = manager.add([globalObject, () => {}, 1000]) const pendingId = manager.add([globalObject, () => {}, 1000])
await waitFor(() => ran) await waitForCondition(() => ran)
await waitFor(() => manager.size === 1) await waitForCondition(() => manager.size === 1)
// Matches user code that calls clearTimeout inside the callback (the // Matches user code that calls clearTimeout inside the callback (the
// documented workaround for #95094); must not throw or affect other // documented workaround for #95094); must not throw or affect other
...@@ -129,7 +130,7 @@ describe('web sandbox TimeoutsManager', () => { ...@@ -129,7 +130,7 @@ describe('web sandbox TimeoutsManager', () => {
expect(manager.size).toBe(0) expect(manager.size).toBe(0)
// Give the original delay time to elapse; the callback must not run. // 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) expect(ran).toBe(false)
}) })
...@@ -154,7 +155,7 @@ describe('web sandbox IntervalsManager', () => { ...@@ -154,7 +155,7 @@ describe('web sandbox IntervalsManager', () => {
// Intervals fire repeatedly, so they must remain tracked (unlike one-shot // Intervals fire repeatedly, so they must remain tracked (unlike one-shot
// timeouts) even after several ticks have run. // timeouts) even after several ticks have run.
await waitFor(() => ticks >= 3) await waitForCondition(() => ticks >= 3)
expect(manager.size).toBe(1) expect(manager.size).toBe(1)
manager.remove(id) 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