Unverified Commit 94327e8a authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Port React's @gate test directive to the e2e harness (#96228)

The test suite has accumulated a bunch of patterns for disabling tests
that are known to fail under some configuration: `it.skip`, `if
(isNextDev) { test('skipped in dev mode', () => {}); return }`, whole
describes toggled off by checking `process.env.__NEXT_CACHE_COMPONENTS`.
These all have the same flaw: nothing tells you when the thing you
skipped starts working. The test stays disabled forever, and the
workaround it was guarding rots along with it.

React solves this with the `@gate` pragma, and this PR ports it to the
Next.js e2e harness:

```ts
// Blocked on the optimization that marks a route as fully static when
// no dynamic params are referenced in Server Components.
// @gate !cacheComponents
it('navigates to a page with a lazily-generated static param', async () => {
  // body unchanged
})
```

The test still runs. If the condition is false and the test fails, the
failure is absorbed and the suite stays green. If it _passes_, the suite
fails: the gate is stale, delete it. So instead of a skip that hides a
fixed bug indefinitely, you get a CI failure the day the fix lands.

When the condition is static, the inversion is Jest's own `test.failing`
under the hood. A lazy condition isn't known until the fixture's
resolved config is read inside the body, so those tests invert at
runtime instead.

`// @force-gate <condition>` skips for real — for tests that can't even
be attempted (prefetching is disabled in dev, deploy has no local build
output, the fixture won't build under the condition), and for tests of a
new API, where the disabled state can only throw and running it proves
nothing:

```ts
// Prefetching is disabled in dev, so this suite has nothing to test.
// @force-gate prefetching
describe('segment cache prefetch scheduling', () => {
  // ...
})
```

There's no staleness check in that case, so this is a judgment call:
prefer `@gate` when the off state fails for a meaningful reason — the
flag changes behavior that already exists — and `@force-gate` when the
body can only throw because the API doesn't exist. A static condition
(mode, bundler) resolves at collection time into a normal Jest skip. A
lazy condition resolves at runtime, and when a lazy force-gate on a
describe is false, we skip the fixture build entirely — that's what
makes it usable for suites whose fixtures are build-incompatible with
the condition. (One caveat: Jest has no way to skip a test that's
already running, so these report as passing with a warning in the log,
not as skipped.)

Conditions live in a hand-written registry. I considered deriving the
lazy ones from the config schema automatically, but a gate is a claim
about which dimension of the test matrix explains a failure, and I'd
rather each of those claims be spelled out with a description.
Referencing an undeclared name fails the suite at collection time, so a
typo can't silently disable a gate.

The important design decision for lazy conditions is that they read the
fixture's _resolved_ config, never `process.env`. The env var isn't the
truth: `__NEXT_CACHE_COMPONENTS=true` only applies when the fixture
doesn't set `cacheComponents` itself, and config resolution implies
flags the fixture never mentions (`cacheComponents: true` alone turns on
`experimental.ppr`). Resolution happens in a child process, because
in-process `loadConfig` would leak the fixture's `.env` files into the
Jest worker. Suites with no lazy gate never pay for any of this.

The condition expression is parsed using a small grammar (also ported
from the React repo). An expression that doesn't parse fails the suite:

```ts
// @gate mode === 'start' && !cacheComponents
// @gate !(turbopack || rspack)
```

There's also a runtime version, mirroring React's `gate(flags =>
flags.enableFoo)`, for tests that run under both states but assert
differently (and for `it.each`, where the pragma can't attach):

```ts
import { gate } from 'next-test-utils'

it('renders the fallback', async () => {
  if (await gate((conditions) => conditions.cacheComponents)) {
    // PPR: the fallback is part of the static shell
  } else {
    // fully dynamic: the fallback streams in
  }
})
```

It also accepts the pragma expression language as a string: `await
gate('cacheComponents && !dev')`.

Docs are in `test/lib/gate/README.md`; `test/unit/gate/` covers the
transform, the expression language, and the runtime.
parent ae622d6c
This diff is collapsed.
...@@ -438,6 +438,7 @@ Use skills for conditional, deep workflows. Keep baseline iteration/build/test p ...@@ -438,6 +438,7 @@ Use skills for conditional, deep workflows. Keep baseline iteration/build/test p
- `$react-sync` - build a local React checkout and sync it into Next.js for testing - `$react-sync` - build a local React checkout and sync it into Next.js for testing
- `$runtime-debug` - runtime-bundle/module-resolution regression reproduction and verification - `$runtime-debug` - runtime-bundle/module-resolution regression reproduction and verification
- `$next-rspack` - @next/rspack-core and @next/rspack-binding maintenance (rspack/ directory) - `$next-rspack` - @next/rspack-core and @next/rspack-binding maintenance (rspack/ directory)
- `$gate-tests` - `@gate`/`@force-gate` test directives: replacing `it.skip`/fake-green skips, conditions, variant-shard fixtures
- `$authoring-skills` - how to create and maintain skills in `.agents/skills/` - `$authoring-skills` - how to create and maintain skills in `.agents/skills/`
## Context-Efficient Workflows ## Context-Efficient Workflows
......
const nextJest = require('next/jest') const nextJest = require('next/jest')
const { withGateTransformer } = require('./test/lib/gate/jest-transformer')
const createJestConfig = nextJest() const createJestConfig = nextJest()
...@@ -89,4 +90,11 @@ if (enableTestReport) { ...@@ -89,4 +90,11 @@ if (enableTestReport) {
} }
// createJestConfig is exported in this way to ensure that next/jest can load the Next.js config which is async // createJestConfig is exported in this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig) const createConfig = createJestConfig(customJestConfig)
module.exports = async function createConfigWithGates() {
// `withGateTransformer` chains the `@gate` pragma rewrite in front of the
// SWC transformer that `next/jest` configured, keeping next/jest's SWC
// options as the single source of truth. See test/lib/gate/.
return withGateTransformer(await createConfig())
}
...@@ -56,6 +56,35 @@ while [ $# -gt 0 ]; do ...@@ -56,6 +56,35 @@ while [ $# -gt 0 ]; do
shift shift
done done
# `__NEXT_TEST_AXIS` names the alternate flag configurations of the test
# matrix. Axes are lettered (`A`, `B`, …) — a fixed enumeration a fixture opts
# into, not a boolean, and not one of the buckets test *sharding* splits a run
# into. CI runs the suites once plainly and once per axis, and a fixture keys
# an experimental flag on an axis to cover both states of the flag — enabled
# by default, disabled on that axis:
#
# experimental: {
# concurrentRouterQueue: process.env.__NEXT_TEST_AXIS !== 'A',
# }
#
# paired with a `// @gate concurrentRouterQueue` on the affected tests: a
# plain run — including a local run with no special env — exercises the
# feature, and the axis run covers the off state (see
# test/lib/gate/README.md).
#
# For now there is a single axis, `A`, and it is an alias for
# `__NEXT_CACHE_COMPONENTS` (the `--experimental` run) rather than a CI
# dimension of its own. That works because most experiments hard-code
# `cacheComponents: true` in their fixture anyway — the cache-components env
# default only applies to fixtures that don't set it themselves, so for these
# fixtures that run is free to double as the axis run. Setting either name
# implies the other.
if [ -n "${__NEXT_TEST_AXIS:-}" ]; then
export __NEXT_CACHE_COMPONENTS=true
elif [ "${__NEXT_CACHE_COMPONENTS:-}" = "true" ]; then
export __NEXT_TEST_AXIS=A
fi
# Resolves to `node_modules/.bin/jest` via `$PATH`. This relies on being # Resolves to `node_modules/.bin/jest` via `$PATH`. This relies on being
# invoked through pnpm (or another package runner), which prepends the # invoked through pnpm (or another package runner), which prepends the
# workspace's `node_modules/.bin/` to `$PATH` before running the script. # workspace's `node_modules/.bin/` to `$PATH` before running the script.
......
...@@ -17,6 +17,7 @@ describe('concurrent-router-queue', () => { ...@@ -17,6 +17,7 @@ describe('concurrent-router-queue', () => {
files: __dirname, files: __dirname,
}) })
// Not gated: a clean hydration is expected in both states of the flag.
it('hydrates cleanly without invoking the forked entry points', async () => { it('hydrates cleanly without invoking the forked entry points', async () => {
// `pushErrorAsConsoleLog` records uncaught page errors into the console // `pushErrorAsConsoleLog` records uncaught page errors into the console
// log capture, which works in both dev and start modes. // log capture, which works in both dev and start modes.
...@@ -29,6 +30,10 @@ describe('concurrent-router-queue', () => { ...@@ -29,6 +30,10 @@ describe('concurrent-router-queue', () => {
expect(errors).toEqual([]) expect(errors).toEqual([])
}) })
// The stubs only throw when the fork is active; with the flag off, the
// sequential router handles the navigation and the test fails its
// expectations — which is what the gate asserts on the axis-A run.
// @gate concurrentRouterQueue
it('fails loudly on link navigation', async () => { it('fails loudly on link navigation', async () => {
const browser = await next.browser('/', { pushErrorAsConsoleLog: true }) const browser = await next.browser('/', { pushErrorAsConsoleLog: true })
await browser.waitForElementByCss('#invoke-action') await browser.waitForElementByCss('#invoke-action')
...@@ -55,6 +60,7 @@ describe('concurrent-router-queue', () => { ...@@ -55,6 +60,7 @@ describe('concurrent-router-queue', () => {
expect(await browser.hasElementByCssSelector('#target-page')).toBe(false) expect(await browser.hasElementByCssSelector('#target-page')).toBe(false)
}) })
// @gate concurrentRouterQueue
it('fails loudly on server action invocation', async () => { it('fails loudly on server action invocation', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
await browser.waitForElementByCss('#invoke-action') await browser.waitForElementByCss('#invoke-action')
......
...@@ -2,8 +2,15 @@ ...@@ -2,8 +2,15 @@
* @type {import('next').NextConfig} * @type {import('next').NextConfig}
*/ */
const nextConfig = { const nextConfig = {
// Pin every dimension except the one under test.
cacheComponents: true,
experimental: { experimental: {
concurrentRouterQueue: true, // Keyed on test axis A (see scripts/run-jest.sh) so the suite covers
// both states. Enabled by default — a plain run exercises the fork with
// no special env — and disabled on axis A, where the
// `@gate concurrentRouterQueue` tests assert the sequential router is
// back in charge.
concurrentRouterQueue: process.env.__NEXT_TEST_AXIS !== 'A',
}, },
} }
......
...@@ -4,7 +4,14 @@ ...@@ -4,7 +4,14 @@
const nextConfig = { const nextConfig = {
cacheComponents: true, cacheComponents: true,
experimental: { experimental: {
useOffline: true, // Keyed on test axis A (see scripts/run-jest.sh). Enabled by default —
// a plain run exercises the hook with no special env — and disabled on
// axis A, where the `@force-gate useOffline` on the suite skips the
// fixture build entirely: `useOffline()` is a new API that is inert when
// disabled (it always reports online), so the off state has nothing to
// assert and would only fail by timing out. The keying turns a redundant
// duplicate run into a near-free skip.
useOffline: process.env.__NEXT_TEST_AXIS !== 'A',
varyParams: true, varyParams: true,
optimisticRouting: true, optimisticRouting: true,
cachedNavigations: true, cachedNavigations: true,
......
...@@ -3,16 +3,13 @@ import type * as Playwright from 'playwright' ...@@ -3,16 +3,13 @@ import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act' import { createRouterAct } from 'router-act'
import { retry } from 'next-test-utils' import { retry } from 'next-test-utils'
// @force-gate prefetching
// @force-gate useOffline
describe('useOffline', () => { describe('useOffline', () => {
const { next, isNextDev } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
if (isNextDev) {
test('skipped in dev mode', () => {})
return
}
// Uses Playwright's built-in network emulation, which fires the browser's // Uses Playwright's built-in network emulation, which fires the browser's
// native offline/online events and blocks all requests at the network layer. // native offline/online events and blocks all requests at the network layer.
async function goOffline(page: Playwright.Page) { async function goOffline(page: Playwright.Page) {
......
import * as matchers from 'jest-extended' import * as matchers from 'jest-extended'
import { installGate } from './lib/gate/runtime'
expect.extend(matchers) expect.extend(matchers)
// Installs the `_test_gate` global that `// @gate` pragmas compile to, and
// wraps `it`/`test` so a gate on a `describe` reaches the tests inside it.
// See test/lib/gate/runtime.ts.
installGate()
// Patch jscodeshift testUtils to normalize line endings (fixes Windows CRLF issues) // Patch jscodeshift testUtils to normalize line endings (fixes Windows CRLF issues)
// The issue: jscodeshift's printer (recast) outputs CRLF on Windows, but test fixtures use LF // The issue: jscodeshift's printer (recast) outputs CRLF on Windows, but test fixtures use LF
// We need to patch both defineTest (which uses internal closure references) and runInlineTest // We need to patch both defineTest (which uses internal closure references) and runInlineTest
......
import path from 'path' import path from 'path'
import assert from 'assert' import assert from 'assert'
import { flushAllTraces, setGlobal, trace } from 'next/dist/trace' import { flushAllTraces, setGlobal, trace } from 'next/dist/trace'
import { PHASE_DEVELOPMENT_SERVER } from 'next/constants' import {
PHASE_DEVELOPMENT_SERVER,
PHASE_PRODUCTION_BUILD,
} from 'next/constants'
import { NextInstance, NextInstanceOpts } from '../next-modes/base' import { NextInstance, NextInstanceOpts } from '../next-modes/base'
import { NextDevInstance } from '../next-modes/next-dev' import { NextDevInstance } from '../next-modes/next-dev'
import { NextStartInstance } from '../next-modes/next-start' import { NextStartInstance } from '../next-modes/next-start'
import { NextDeployInstance } from '../next-modes/next-deploy' import { NextDeployInstance } from '../next-modes/next-deploy'
import { shouldUseTurbopack } from '../next-test-utils' import { shouldUseTurbopack } from '../next-test-utils'
import { setGateTestContext, type GateTestMode } from '../gate/test-context'
import { clearFixture, registerFixture } from '../gate/state'
import { loadResolvedConfig } from '../gate/load-resolved-config'
import {
getActiveDescribeGates,
hasLazyForceGate,
findLazyForceSkip,
} from '../gate/runtime'
export type { NextInstance } export type { NextInstance }
export type { Playwright } from '../browsers/playwright' export type { Playwright } from '../browsers/playwright'
...@@ -177,6 +188,19 @@ export const itTurbopack = ...@@ -177,6 +188,19 @@ export const itTurbopack =
export const isReact18 = export const isReact18 =
parseInt(process.env.NEXT_TEST_REACT_VERSION || '', 10) === 18 parseInt(process.env.NEXT_TEST_REACT_VERSION || '', 10) === 18
// Publish the statically-known shape of this run for `// @gate` pragmas. See
// test/lib/gate/conditions.ts.
setGateTestContext({
mode: testMode as GateTestMode,
bundler: isRspack
? 'rspack'
: !isNextTestWasm && shouldUseTurbopack()
? 'turbopack'
: 'webpack',
react18: isReact18,
wasm: isNextTestWasm,
})
if (!testMode) { if (!testMode) {
throw new Error( throw new Error(
`No 'NEXT_TEST_MODE' set in environment, this is required for e2e-utils` `No 'NEXT_TEST_MODE' set in environment, this is required for e2e-utils`
...@@ -284,10 +308,17 @@ async function createNext( ...@@ -284,10 +308,17 @@ async function createNext(
nextInstance.on('destroy', () => { nextInstance.on('destroy', () => {
nextInstance = undefined nextInstance = undefined
clearFixture()
}) })
await nextInstance.setup(rootSpan) await nextInstance.setup(rootSpan)
// Lazy `// @gate` conditions read this fixture's resolved next.config.
// Registering the instance (not a snapshot) before `start()` keeps
// `skipStart` suites and rebuild flows working: nothing is resolved until
// a gate actually asks. See test/lib/gate/README.md.
registerFixture(nextInstance)
if (!opts.skipStart) { if (!opts.skipStart) {
await rootSpan await rootSpan
.traceChild('start next instance') .traceChild('start next instance')
...@@ -338,16 +369,86 @@ export function nextTestSetup( ...@@ -338,16 +369,86 @@ export function nextTestSetup(
} }
} }
// A lazy `@force-gate` on the enclosing `describe` (e.g. `!cacheComponents`)
// gates the *build*, not just the test bodies: some fixtures can't build
// under the condition at all. Snapshot the describe's gates now, while the
// describe body is still being collected — the stack is empty by `beforeAll`.
// Suites that manage their own build (`skipStart`) are left untouched.
const describeGates = getActiveDescribeGates()
// Deploy's "build" is a remote deployment we can't gate this way, and suites
// that pass `skipStart` build manually — leave both to their own handling.
const buildForceGated =
!options.skipStart && !isNextDeploy && hasLazyForceGate(describeGates)
let next: NextInstance | undefined let next: NextInstance | undefined
if (!skipped) { if (!skipped) {
beforeAll(async () => { beforeAll(async () => {
next = await createNext(options) if (!buildForceGated) {
next = await createNext(options)
return
}
// Try to decide the force-gate against the *source* fixture first,
// before paying for the fixture setup (which includes a dependency
// install when the run is isolated). The config resolver falls back to
// the repo's own `next` when the directory has no install, and the env
// mirrors what `getSpawnOpts` hands every fixture child process. An
// inline `files` object has no directory to resolve against, and any
// resolution failure (e.g. a config that imports from the fixture's
// own node_modules) falls through to the instance-based decision below.
if (typeof options.files === 'string') {
const config = await loadResolvedConfig({
dir: options.files,
phase: isNextDev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_BUILD,
env: {
...process.env,
...options.env,
NODE_ENV: (options.env?.NODE_ENV ||
'') as NodeJS.ProcessEnv['NODE_ENV'],
PORT: '0',
__NEXT_TEST_MODE: 'e2e',
},
}).catch(() => null)
const earlySkip = config && findLazyForceSkip(describeGates, config)
if (earlySkip) {
// No instance ever exists on this path, so register the resolved
// config directly for the per-test force-pass decisions.
registerFixture({ getResolvedConfig: async () => config })
require('console').warn(
` ⚠ suite build skipped by \`@force-gate ${earlySkip.source}\` ` +
`(decided from the source fixture; setup skipped)`
)
return
}
}
// Set the fixture up (so its config is resolvable) without building, then
// resolve the force-gate. If it's false, skip the build entirely — the
// inherited gate makes every test force-pass, so nothing touches `next`.
const instance = await createNext({ ...options, skipStart: true })
next = instance
const config = await instance.getResolvedConfig()
const forceSkip = findLazyForceSkip(describeGates, config)
if (forceSkip) {
require('console').warn(
` ⚠ suite build skipped by \`@force-gate ${forceSkip.source}\``
)
return
}
try {
await instance.start()
} catch (err) {
await instance.destroy().catch(() => {})
next = undefined
throw err
}
}) })
afterAll(async () => { afterAll(async () => {
// Gracefully destroy the instance if `createNext` success. // Gracefully destroy the instance if `createNext` success.
// If next instance is not available, it's likely beforeAll hook failed and unnecessarily throws another error // If next instance is not available, it's likely beforeAll hook failed and unnecessarily throws another error
// by attempting to destroy on undefined. // by attempting to destroy on undefined.
await next?.destroy() await next?.destroy()
// The early force-skip path registers a config source without an
// instance (an instance clears itself on destroy).
if (!next) clearFixture()
}) })
} }
......
This diff is collapsed.
/**
* The `@gate` condition registry.
*
* Every name that may appear inside a `// @gate` / `// @force-gate` pragma has
* to be declared here. Referencing an undeclared name fails the whole test
* suite at collection time, so a typo can never silently disable a gate.
*
* The registry is deliberately hand-written rather than derived from the
* `next.config` schema: a gate is a claim about which *test-matrix dimension*
* explains a failure, and that claim is worth spelling out. Keep the list small
* and meaningful.
*
* ## The two tiers
*
* **`staticCondition`** — the value is known before any test runs (run mode,
* bundler, React version). These are the only conditions `@force-gate` accepts,
* because a real Jest skip has to be decided while tests are being collected.
*
* **`lazyCondition`** — a predicate over the *resolved* `next.config` of the
* fixture the suite booted (`NextInstance.getResolvedConfig()`). The value is
* read the first time a gate asks for it, which is inside the test body,
* because nothing about the fixture exists at collection time.
*
* Read the resolved config, never `process.env`: `__NEXT_CACHE_COMPONENTS=true`
* (set by the `--experimental` shard in `scripts/run-jest.sh`) is only applied
* when the fixture has not set `cacheComponents` itself, and resolution implies
* flags a fixture never mentions — `cacheComponents: true` alone turns on
* `experimental.ppr` and `experimental.cachedNavigations`.
*
* ## Adding a condition
*
* 1. Pick a bare name that reads well after `@gate` and `!`.
* 2. Add it below with a one-line description of what it means.
* 3. For a lazy condition, read the key off the resolved config — remember that
* some keys moved out of `experimental` (`config.cacheComponents`) while
* others are still under it (`config.experimental.ppr`), and that some
* normalize to an object rather than a boolean
* (`experimental.prefetchInlining`). Returning the raw value is fine:
* expressions coerce by truthiness, and `===` comparisons see the raw value.
*
* Values do not have to be booleans. `mode` and `bundler` are strings so that
* `// @gate mode === 'deploy'` works.
*/
import type { ResolvedNextConfig } from './resolved-config'
import { getGateTestContext } from './test-context'
export type ConditionValue = unknown
export type StaticCondition = {
kind: 'static'
description: string
value: () => ConditionValue
}
export type LazyCondition = {
kind: 'lazy'
description: string
value: (config: ResolvedNextConfig) => ConditionValue
}
export type Condition = StaticCondition | LazyCondition
function staticCondition(
description: string,
value: () => ConditionValue
): StaticCondition {
return { kind: 'static', description, value }
}
function lazyCondition(
description: string,
value: (config: ResolvedNextConfig) => ConditionValue
): LazyCondition {
return { kind: 'lazy', description, value }
}
export const conditions: Record<string, Condition> = {
// --- static: the shape of this test run -----------------------------------
mode: staticCondition(
"the e2e run mode: 'dev' | 'start' | 'deploy'",
() => getGateTestContext().mode
),
dev: staticCondition(
'running `next dev`',
() => getGateTestContext().mode === 'dev'
),
start: staticCondition(
'running `next build` + `next start`',
() => getGateTestContext().mode === 'start'
),
deploy: staticCondition(
'running against a real deployment',
() => getGateTestContext().mode === 'deploy'
),
// Semantic aliases for `!dev`. A gate is a claim about *why* a suite cannot
// run, so prefer the name that states the reason over the bare mode check.
prod: staticCondition(
'the app was built with `next build` (`start` or `deploy`)',
() => getGateTestContext().mode !== 'dev'
),
prefetching: staticCondition(
'links prefetch — disabled in dev, the usual reason a suite skips it',
() => getGateTestContext().mode !== 'dev'
),
bundler: staticCondition(
"the bundler under test: 'turbopack' | 'rspack' | 'webpack'",
() => getGateTestContext().bundler
),
turbopack: staticCondition(
'bundling with Turbopack',
() => getGateTestContext().bundler === 'turbopack'
),
rspack: staticCondition(
'bundling with Rspack',
() => getGateTestContext().bundler === 'rspack'
),
webpack: staticCondition(
'bundling with webpack',
() => getGateTestContext().bundler === 'webpack'
),
react18: staticCondition(
'the fixture installs React 18 instead of the default React version',
() => getGateTestContext().react18
),
wasm: staticCondition(
'using the wasm SWC binary (`NEXT_TEST_WASM`)',
() => getGateTestContext().wasm
),
ci: staticCondition('running in CI (`NEXT_TEST_CI`)', () =>
Boolean(process.env.NEXT_TEST_CI)
),
// Always false, so `// @gate FIXME` marks a test as a known failure without
// inventing a condition for it. Mirrors the same convention in React's
// scripts/jest/TestFlags.js. Prefer a real condition whenever one exists —
// these two say "we know this is broken" and nothing about why.
FIXME: staticCondition('known failure, no condition attached', () => false),
TODO: staticCondition('known failure, no condition attached', () => false),
// --- lazy: the fixture's resolved next.config ------------------------------
cacheComponents: lazyCondition(
'Cache Components are enabled for the fixture',
(config) => config.cacheComponents
),
ppr: lazyCondition(
'partial prerendering is enabled (implied by `cacheComponents`)',
(config) => config.experimental?.ppr
),
cachedNavigations: lazyCondition(
'client navigations are cached (implied by `cacheComponents`)',
(config) => config.experimental?.cachedNavigations
),
optimisticRouting: lazyCondition(
'optimistic routing is enabled',
(config) => config.experimental?.optimisticRouting
),
concurrentRouterQueue: lazyCondition(
'the concurrent router queue fork is enabled',
(config) => config.experimental?.concurrentRouterQueue
),
dynamicOnHover: lazyCondition(
'dynamic prefetches are triggered on hover',
(config) => config.experimental?.dynamicOnHover
),
useOffline: lazyCondition(
'the `useOffline()` hook is enabled for the fixture',
(config) => config.experimental?.useOffline
),
prefetchInlining: lazyCondition(
'prefetches are inlined into the HTML payload; resolves to an object ' +
'(`{maxSize, maxBundleSize}`) or `false`',
(config) => config.experimental?.prefetchInlining
),
output: lazyCondition(
"`output` in the resolved config: 'standalone' | 'export' | undefined",
(config) => config.output
),
basePath: lazyCondition(
'the fixture serves the app from a base path (a string, `` when unset)',
(config) => config.basePath
),
trailingSlash: lazyCondition(
'URLs are normalized to a trailing slash',
(config) => config.trailingSlash
),
}
export function isDeclared(name: string): boolean {
return Object.prototype.hasOwnProperty.call(conditions, name)
}
export function getCondition(name: string): Condition {
if (!isDeclared(name)) {
throw new Error(
`\`@gate\` references an undeclared condition "${name}".\n\n` +
`Declare it in test/lib/gate/conditions.ts, or fix the typo. ` +
`Declared conditions: ${Object.keys(conditions).sort().join(', ')}.`
)
}
return conditions[name]
}
/**
* The tiny expression language used inside a `// @gate` pragma.
*
* ```
* expression → binary ( ( "||" | "&&" ) binary )* ;
* binary → unary ( ( "==" | "!=" | "===" | "!==" ) unary )* ;
* unary → "!" unary | primary ;
* primary → NAME | STRING | BOOLEAN | "(" expression ")" ;
* ```
*
* This mirrors the grammar React uses for its own `@gate` pragmas
* (`scripts/babel/transform-test-gate-pragma.js` in facebook/react), so
* pragmas read the same in both repos:
*
* ```
* // @gate !dev
* // @gate mode === 'start' && !cacheComponents
* ```
*
* `NAME` is a condition declared in `./conditions.ts`. Unlike React, the
* expression is parsed at *runtime* rather than compiled by the transform,
* which keeps the source rewrite trivial and lets the runtime report the
* pragma text verbatim in error messages.
*/
export type ExprNode =
| { type: 'literal'; value: string | boolean }
| { type: 'condition'; name: string }
| { type: 'not'; argument: ExprNode }
| { type: 'logical'; op: '&&' | '||'; left: ExprNode; right: ExprNode }
| { type: 'compare'; op: '=='; left: ExprNode; right: ExprNode }
| { type: 'compare'; op: '!='; left: ExprNode; right: ExprNode }
export type ParsedExpression = {
node: ExprNode
/** Every condition name referenced by the expression, deduplicated. */
names: string[]
}
type Token =
| { type: 'name'; name: string }
| { type: 'string'; value: string }
| { type: 'boolean'; value: boolean }
| { type: '&&' | '||' | '==' | '!=' | '!' | '(' | ')' }
const NAME_RE = /[a-zA-Z_$][0-9a-zA-Z_$]*/y
function tokenize(source: string): Token[] {
const tokens: Token[] = []
let i = 0
while (i < source.length) {
const char = source[i]
if (char === '"' || char === "'") {
let value = ''
i++
while (i < source.length && source[i] !== char) value += source[i++]
if (source[i] !== char) {
throw new SyntaxError(
`Unterminated string in \`${source}\` (missing closing ${char}).`
)
}
i++
tokens.push({ type: 'string', value })
continue
}
if (/\s/.test(char)) {
i++
continue
}
const next3 = source.slice(i, i + 3)
if (next3 === '===') {
tokens.push({ type: '==' })
i += 3
continue
}
if (next3 === '!==') {
tokens.push({ type: '!=' })
i += 3
continue
}
const next2 = source.slice(i, i + 2)
if (next2 === '&&' || next2 === '||' || next2 === '==' || next2 === '!=') {
tokens.push({ type: next2 })
i += 2
continue
}
if (char === '(' || char === ')' || char === '!') {
tokens.push({ type: char })
i++
continue
}
NAME_RE.lastIndex = i
const match = NAME_RE.exec(source)
if (match) {
const name = match[0]
if (name === 'true' || name === 'false') {
tokens.push({ type: 'boolean', value: name === 'true' })
} else {
tokens.push({ type: 'name', name })
}
i += name.length
continue
}
throw new SyntaxError(
`Unexpected character ${JSON.stringify(char)} in \`${source}\`.`
)
}
return tokens
}
/** Parses a pragma condition, collecting the condition names it references. */
export function parse(source: string): ParsedExpression {
const tokens = tokenize(source)
const names = new Set<string>()
let i = 0
function expression(): ExprNode {
let left = binary()
for (;;) {
const token = tokens[i]
if (token && (token.type === '&&' || token.type === '||')) {
i++
left = { type: 'logical', op: token.type, left, right: binary() }
continue
}
return left
}
}
function binary(): ExprNode {
let left = unary()
for (;;) {
const token = tokens[i]
if (token && (token.type === '==' || token.type === '!=')) {
i++
left = { type: 'compare', op: token.type, left, right: unary() }
continue
}
return left
}
}
function unary(): ExprNode {
if (tokens[i]?.type === '!') {
i++
return { type: 'not', argument: unary() }
}
return primary()
}
function primary(): ExprNode {
const token = tokens[i]
if (!token) {
throw new SyntaxError(`Unexpected end of expression in \`${source}\`.`)
}
switch (token.type) {
case 'boolean':
case 'string':
i++
return { type: 'literal', value: token.value }
case 'name':
i++
names.add(token.name)
return { type: 'condition', name: token.name }
case '(': {
i++
const inner = expression()
if (tokens[i]?.type !== ')') {
throw new SyntaxError(`Missing closing \`)\` in \`${source}\`.`)
}
i++
return inner
}
default:
throw new SyntaxError(`Unexpected \`${token.type}\` in \`${source}\`.`)
}
}
const node = expression()
if (i !== tokens.length) {
throw new SyntaxError(
`Unexpected \`${tokens[i].type}\` after a complete expression in ` +
`\`${source}\`.`
)
}
return { node, names: [...names] }
}
function evaluateNode(
node: ExprNode,
read: (name: string) => unknown
): unknown {
switch (node.type) {
case 'literal':
return node.value
case 'condition':
return read(node.name)
case 'not':
return !evaluateNode(node.argument, read)
case 'logical':
return node.op === '&&'
? evaluateNode(node.left, read) && evaluateNode(node.right, read)
: evaluateNode(node.left, read) || evaluateNode(node.right, read)
case 'compare': {
const left = evaluateNode(node.left, read)
const right = evaluateNode(node.right, read)
return node.op === '==' ? left === right : left !== right
}
default:
throw new Error(`Unknown @gate expression node: ${JSON.stringify(node)}`)
}
}
/**
* Evaluates a parsed expression. Condition values are coerced by truthiness in
* boolean position, so `@gate prefetchInlining` works for a condition whose
* value is `false | {maxSize: number}`, and `@gate output === 'export'` works
* for string-valued conditions.
*/
export function evaluate(
node: ExprNode,
read: (name: string) => unknown
): boolean {
return Boolean(evaluateNode(node, read))
}
// @ts-check
/**
* Jest transformer that rewrites `// @gate` pragmas (see
* `./pragma-transform.js`) and then delegates to the transformer `next/jest`
* would have used on its own (SWC).
*
* It is wired up by `jest.config.js` via `withGateTransformer()`, which takes
* the transformer entry `next/jest` produced and nests it inside this one, so
* there is still exactly one source of truth for the SWC options.
*/
const crypto = require('crypto')
const fs = require('fs')
const path = require('path')
const { rewrite } = require('./pragma-transform')
const IS_TEST_FILE = /\.test\.(js|jsx|ts|tsx|mjs)$/
/** The transform key `next/jest` uses for its SWC transformer. */
const TRANSFORM_KEY = '^.+\\.(js|jsx|ts|tsx|mjs)$'
/**
* Hash of this transformer's own sources, mixed into `getCacheKey` so that
* editing the pragma rewrite invalidates Jest's transform cache. Jest's
* built-in fallback only hashes the file contents and the serialized config,
* neither of which changes when this directory does.
*/
const SELF_VERSION = (() => {
const hash = crypto.createHash('sha1')
for (const file of ['jest-transformer.js', 'pragma-transform.js']) {
hash.update(fs.readFileSync(path.join(__dirname, file)))
}
return hash.digest('hex').slice(0, 16)
})()
/**
* @typedef {{ innerTransformer: string, innerOptions: unknown }} GateTransformerConfig
*/
/** @type {(inputOptions: GateTransformerConfig) => import('@jest/transform').SyncTransformer} */
function createTransformer(inputOptions) {
if (!inputOptions?.innerTransformer) {
throw new Error(
'test/lib/gate/jest-transformer.js must be configured through ' +
'`withGateTransformer()` in jest.config.js.'
)
}
const innerModule = require(inputOptions.innerTransformer)
const inner = innerModule.createTransformer(inputOptions.innerOptions)
return {
process(src, filename, jestOptions) {
const rewritten = IS_TEST_FILE.test(filename)
? rewrite(src, filename)
: src
return inner.process(rewritten, filename, jestOptions)
},
getCacheKey(src, filename, options) {
const base = inner.getCacheKey
? inner.getCacheKey(src, filename, options)
: crypto.createHash('sha1').update(src).update(filename).digest('hex')
return `${base}:gate-${SELF_VERSION}`
},
}
}
/**
* Wraps the transformer entry produced by `next/jest` so `@gate` pragmas are
* rewritten before SWC compiles the file.
*
* @template {{ transform?: Record<string, unknown> }} T
* @param {T} config a resolved Jest config from `next/jest`
* @returns {T}
*/
function withGateTransformer(config) {
const existing = config.transform?.[TRANSFORM_KEY]
if (!Array.isArray(existing) || typeof existing[0] !== 'string') {
throw new Error(
`withGateTransformer: expected next/jest to define a transformer tuple ` +
`for ${TRANSFORM_KEY}, found ${JSON.stringify(existing)}. ` +
`next/jest's transform shape changed — update ` +
`test/lib/gate/jest-transformer.js.`
)
}
const [innerTransformer, innerOptions] = existing
return {
...config,
transform: {
...config.transform,
[TRANSFORM_KEY]: [
require.resolve('./jest-transformer.js'),
{ innerTransformer, innerOptions },
],
},
}
}
module.exports = { createTransformer, withGateTransformer, TRANSFORM_KEY }
// @ts-check
/**
* Resolves a fixture's `next.config` and prints it as JSON.
*
* Run as a child process by `./load-resolved-config.ts`, with the fixture's cwd
* and the fixture's exact spawn env. It has to be out of process for two
* reasons:
*
* 1. `loadConfig` calls `loadEnvConfig`, which **mutates the caller's
* `process.env`** from the fixture's `.env*` files. Doing that inside a Jest
* worker would leak fixture env into every other test in the file.
* 2. Resolution reads env vars from the *calling* process
* (`__NEXT_CACHE_COMPONENTS`, `__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS`, ...),
* and the fixture runs with an env that is not the Jest worker's whenever a
* suite passes `nextTestSetup({ env })`.
*
* Usage: node load-config-child.js <dir> <phase>
*/
const MARKER = '__NEXT_GATE_RESOLVED_CONFIG__'
/**
* Deep-copies `value` into something `JSON.stringify` can handle: drops
* functions and symbols, stringifies regexps, and replaces cycles with
* `'[Circular]'`. Anything a `@gate` condition wants to read is plain data.
*
* @param {unknown} value
* @param {WeakSet<object>} [seen]
* @returns {unknown}
*/
function toJsonSafe(value, seen = new WeakSet()) {
if (value === null || typeof value !== 'object') {
if (typeof value === 'function' || typeof value === 'symbol') {
return undefined
}
if (typeof value === 'bigint') return String(value)
return value
}
if (value instanceof RegExp) return String(value)
if (value instanceof Date) return value.toISOString()
if (seen.has(value)) return '[Circular]'
seen.add(value)
if (Array.isArray(value)) {
return value.map((item) => toJsonSafe(item, seen))
}
/** @type {Record<string, unknown>} */
const result = {}
for (const [key, item] of Object.entries(value)) {
const converted = toJsonSafe(item, seen)
if (converted !== undefined) result[key] = converted
}
return result
}
/**
* Prefer the `next` the fixture itself installed, so the config is resolved by
* the same code the fixture builds with.
*
* @param {string} dir
*/
function requireConfigLoader(dir) {
try {
return require(require.resolve('next/dist/server/config', { paths: [dir] }))
} catch {
return require('next/dist/server/config')
}
}
async function main() {
const [dir, phase] = process.argv.slice(2)
if (!dir || !phase) {
throw new Error('usage: load-config-child.js <dir> <phase>')
}
const loadConfig = requireConfigLoader(dir).default
const config = await loadConfig(phase, dir, { silent: true })
process.stdout.write(MARKER + JSON.stringify(toJsonSafe(config)))
}
// Guarded so the parent can `require` this file just to read `MARKER`.
if (require.main === module) {
main().catch((err) => {
console.error(err)
process.exit(1)
})
}
module.exports = { MARKER, toJsonSafe }
import spawn from 'cross-spawn'
import path from 'path'
import type { ResolvedNextConfig } from './resolved-config'
const { MARKER } = require('./load-config-child.js')
const CHILD_SCRIPT = path.join(__dirname, 'load-config-child.js')
const TIMEOUT_MS = 60 * 1000
export type LoadResolvedConfigOptions = {
/** The fixture's test directory. */
dir: string
/** `PHASE_PRODUCTION_BUILD` / `PHASE_DEVELOPMENT_SERVER`. */
phase: string
/** The fixture's spawn env, from `NextInstance.getSpawnOpts()`. */
env?: NodeJS.ProcessEnv
}
/**
* Resolves a fixture's `next.config` in a child process. Costs ~0.15s, and is
* only ever paid by a suite that actually has a lazy `@gate`.
*/
export function loadResolvedConfig({
dir,
phase,
env,
}: LoadResolvedConfigOptions): Promise<ResolvedNextConfig> {
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, [CHILD_SCRIPT, dir, phase], {
cwd: dir,
env,
stdio: ['ignore', 'pipe', 'pipe'],
})
let stdout = ''
let stderr = ''
child.stdout!.on('data', (chunk) => (stdout += chunk))
child.stderr!.on('data', (chunk) => (stderr += chunk))
const timeout = setTimeout(() => {
child.kill('SIGKILL')
reject(
new Error(
`Timed out after ${TIMEOUT_MS}ms resolving the next.config of ${dir} ` +
`for a \`@gate\` condition.`
)
)
}, TIMEOUT_MS)
child.on('error', (error) => {
clearTimeout(timeout)
reject(error)
})
child.on('close', (code) => {
clearTimeout(timeout)
const start = stdout.indexOf(MARKER)
if (code !== 0 || start === -1) {
reject(
new Error(
`Failed to resolve the next.config of ${dir} for a \`@gate\` ` +
`condition (phase ${phase}, exit code ${code}).\n${stderr}`
)
)
return
}
try {
resolve(JSON.parse(stdout.slice(start + MARKER.length)))
} catch (error) {
reject(error)
}
})
})
}
// @ts-check
/**
* Source-to-source rewrite of `// @gate` / `// @force-gate` pragmas.
*
* ```
* // @gate !cacheComponents
* it('does a thing', async () => {})
* ```
*
* becomes
*
* ```
* // @gate !cacheComponents
* _test_gate([{"force":false,"source":"!cacheComponents"}],"it")('does a thing', async () => {})
* ```
*
* `_test_gate` is installed as a global by `test/lib/gate/runtime.ts` and
* returns a curried `it`-alike, so the original `(name, fn, timeout)` arguments
* flow through untouched.
*
* This is deliberately a regex rewrite and not an AST transform: the only
* edited bytes are on the `it(` / `describe(` line itself, so the line numbers
* of every other line are preserved exactly. That matters because Jest writes
* `toMatchInlineSnapshot()` results back by line/column, and because stack
* traces should still point at the original source.
*/
/**
* A pragma block is one or more consecutive `// @gate` lines *immediately*
* followed by an `it` / `test` / `fit` / `describe` call. Anything else (a
* pragma in a JSDoc block, a pragma with a blank line under it, a pragma over
* `it.each`) is not matched, and is reported as an error by `rewrite()` rather
* than silently ignored.
*/
const PRAGMA_BLOCK =
/((?:^[ \t]*\/\/[ \t]*@(?:force-)?gate\b[^\n]*\n)+)([ \t]*)(it|test|fit|describe)((?:\.only)?)([ \t]*\()/gm
/** Matches a single pragma line and captures `force` + the condition source. */
const PRAGMA_LINE = /^[ \t]*\/\/[ \t]*@(force-)?gate\b[ \t]*([^\n]*)$/
/** Cheap detector used to find pragmas the block regex did not consume. */
const PRAGMA_LINE_LOOSE = /^[ \t]*\/\/[ \t]*@(?:force-)?gate\b/
/**
* A skipped (or todo) test call. A skip *without* a pragma flows through
* untouched, but a pragma on one is ambiguous — should the gate re-enable the
* test, or does the skip win? — so it gets a dedicated error instead of the
* generic misplaced-pragma one.
*/
const SKIPPED_CALL =
/^[ \t]*(?:xit|xtest|xdescribe|(?:it|test|describe)\.skip|(?:it|test)\.todo)[ \t]*[(.]/
/**
* @param {string} src
* @returns {number[]} 0-based index of the first character of each line
*/
function getLineStarts(src) {
const starts = [0]
for (let i = 0; i < src.length; i++) {
if (src[i] === '\n') starts.push(i + 1)
}
return starts
}
/**
* @param {number[]} lineStarts
* @param {number} offset
* @returns {number} 1-based line number containing `offset`
*/
function getLineNumber(lineStarts, offset) {
let low = 0
let high = lineStarts.length - 1
while (low < high) {
const mid = (low + high + 1) >> 1
if (lineStarts[mid] <= offset) low = mid
else high = mid - 1
}
return low + 1
}
/**
* Rewrites every `@gate` / `@force-gate` pragma block in `src`.
*
* Throws if the file contains a pragma-looking comment that would not have any
* effect — a silently-inert gate is the worst possible failure mode for a
* feature whose entire purpose is to not lie about coverage.
*
* @param {string} src
* @param {string} [filename]
* @returns {string}
*/
function rewrite(src, filename) {
// Cheap bail-out for the ~2000 files with no pragma. `@force-gate` does not
// contain the substring `@gate`, so both spellings have to be checked.
if (!src.includes('@gate') && !src.includes('@force-gate')) return src
const lineStarts = getLineStarts(src)
/** @type {Set<number>} 1-based line numbers consumed by a match */
const consumed = new Set()
const output = src.replace(
PRAGMA_BLOCK,
/**
* @param {string} _all
* @param {string} pragmaLines
* @param {string} indent
* @param {string} callee
* @param {string} only
* @param {string} openParen
* @param {number} offset
*/
(_all, pragmaLines, indent, callee, only, openParen, offset) => {
const firstLine = getLineNumber(lineStarts, offset)
const gates = []
const lines = pragmaLines.split('\n')
// The trailing element is '' because `pragmaLines` ends with a newline.
for (let i = 0; i < lines.length - 1; i++) {
consumed.add(firstLine + i)
const match = PRAGMA_LINE.exec(lines[i])
if (!match) {
// Not reachable: PRAGMA_BLOCK already matched these lines.
throw new Error(`Unparsable @gate pragma: ${lines[i]}`)
}
const source = match[2].trim()
if (!source) {
throw new Error(
`${describeLocation(filename, firstLine + i)}: \`@${
match[1] ? 'force-gate' : 'gate'
}\` needs a condition, e.g. \`// @gate !cacheComponents\`.`
)
}
gates.push({ force: Boolean(match[1]), source })
}
return (
pragmaLines +
indent +
`_test_gate(${JSON.stringify(gates)},${JSON.stringify(
callee + only
)})` +
openParen
)
}
)
assertNoInertPragmas(src, consumed, filename)
return output
}
/**
* @param {string} src
* @param {Set<number>} consumed
* @param {string | undefined} filename
*/
function assertNoInertPragmas(src, consumed, filename) {
const lines = src.split('\n')
for (let i = 0; i < lines.length; i++) {
if (!PRAGMA_LINE_LOOSE.test(lines[i])) continue
if (consumed.has(i + 1)) continue
// Walk past the rest of the pragma block to the line it tried to gate.
let target = i + 1
while (target < lines.length && PRAGMA_LINE_LOOSE.test(lines[target])) {
target++
}
if (target < lines.length && SKIPPED_CALL.test(lines[target])) {
throw new Error(
`${describeLocation(filename, i + 1)}: a \`@gate\` pragma on a ` +
`skipped test is ambiguous.\n\n` +
` ${lines[i].trim()}\n ${lines[target].trim()}\n\n` +
`Either remove the skip and let the gate decide (a false condition ` +
`absorbs the failure), or keep the plain skip and remove the ` +
`pragma.`
)
}
throw new Error(
`${describeLocation(filename, i + 1)}: this \`@gate\` pragma has no ` +
`effect.\n\n` +
` ${lines[i].trim()}\n\n` +
`A pragma must sit on the line(s) immediately above an ` +
`\`it(\`, \`test(\`, \`fit(\`, \`describe(\`, \`it.only(\`, ` +
`\`test.only(\` or \`describe.only(\` call — with no blank line in ` +
`between. \`it.each\` and \`it.failing\` are not supported. If this ` +
`comment is prose rather than a pragma, reword it so it does not ` +
`start with \`@gate\`.`
)
}
}
/**
* @param {string | undefined} filename
* @param {number} line
*/
function describeLocation(filename, line) {
return `${filename ?? '<unknown>'}:${line}`
}
module.exports = { rewrite }
/**
* A JSON-safe snapshot of a fixture's resolved `NextConfigComplete`, as
* produced by `NextInstance.getResolvedConfig()`.
*
* It is intentionally loosely typed. The snapshot round-trips through JSON, so
* functions (`webpack`, `generateBuildId`) and other non-serializable values
* are gone, and lazy conditions in `./conditions.ts` may want to read keys that
* only exist after resolution and are absent from the public `NextConfig` type.
*/
export type ResolvedNextConfig = {
experimental?: Record<string, unknown>
[key: string]: unknown
}
This diff is collapsed.
/**
* The seam between the gate runtime and the Next.js fixture a suite booted.
*
* A fixture is registered by `createNext()` as soon as it is set up, and
* unregistered when it is destroyed. Registering the *instance* rather than a
* config snapshot is what keeps `skipStart: true` suites and `next.build()` /
* restart flows working: nothing is resolved until a gate actually asks, by
* which point the fixture is up.
*
* Suites with no lazy `@gate` therefore pay nothing at all.
*/
import type { ResolvedNextConfig } from './resolved-config'
/**
* The part of `NextInstance` the gate runtime needs. Structural, so this module
* stays independent of `test/lib/next-modes/base.ts`.
*/
export type GateConfigSource = {
getResolvedConfig(): Promise<ResolvedNextConfig>
}
let activeFixture: GateConfigSource | null = null
export function registerFixture(fixture: GateConfigSource): void {
activeFixture = fixture
}
export function clearFixture(): void {
activeFixture = null
}
export function hasFixture(): boolean {
return activeFixture !== null
}
/**
* Resolves the running fixture's config for a lazy condition. Memoization lives
* on the instance, so repeated gates in one file resolve it once.
*/
export function getResolvedConfigForGates(): Promise<ResolvedNextConfig> {
if (!activeFixture) {
throw new Error(
`This \`@gate\` condition is resolved from the running Next.js ` +
`fixture's config, but no fixture is registered. Is this suite using ` +
`\`nextTestSetup()\`? Conditions that are known up front (\`dev\`, ` +
`\`turbopack\`, ...) do not need one.`
)
}
return activeFixture.getResolvedConfig()
}
/**
* The statically-known shape of the current test run, published by `e2e-utils`
* when it is imported and read by the static conditions in `./conditions.ts`.
*
* `e2e-utils` derives all of this at module scope (from `NEXT_TEST_MODE`, the
* test's folder, and the bundler env vars), and a test file imports `e2e-utils`
* before any `_test_gate(...)` call runs, so the context is always populated by
* the time a gate is evaluated in an e2e suite.
*
* It lives in its own module so that the gate runtime — which is loaded for
* every Jest project, including unit tests — never has to import `e2e-utils`
* and its side effects.
*/
export type GateTestMode = 'dev' | 'start' | 'deploy'
export type GateTestBundler = 'turbopack' | 'rspack' | 'webpack'
export type GateTestContext = {
mode: GateTestMode
bundler: GateTestBundler
react18: boolean
wasm: boolean
}
let current: GateTestContext | null = null
export function setGateTestContext(context: GateTestContext): void {
current = context
}
export function getGateTestContext(): GateTestContext {
if (!current) {
throw new Error(
`This \`@gate\` condition describes the e2e test run (mode, bundler, ` +
`React version), but no run context has been recorded. Conditions ` +
`like \`dev\` and \`turbopack\` are only available to suites that ` +
`import \`e2e-utils\`.`
)
}
return current
}
/** Test-only. */
export function clearGateTestContext(): void {
current = null
}
...@@ -22,6 +22,9 @@ import type { Playwright } from '../browsers/playwright' ...@@ -22,6 +22,9 @@ import type { Playwright } from '../browsers/playwright'
import escapeStringRegexp from 'escape-string-regexp' import escapeStringRegexp from 'escape-string-regexp'
import * as JSON5 from 'json5' import * as JSON5 from 'json5'
import { Page, Response } from 'playwright' import { Page, Response } from 'playwright'
import { PHASE_PRODUCTION_BUILD } from 'next/constants'
import { loadResolvedConfig } from '../gate/load-resolved-config'
import type { ResolvedNextConfig } from '../gate/resolved-config'
type Event = 'stdout' | 'stderr' | 'error' | 'destroy' type Event = 'stdout' | 'stderr' | 'error' | 'destroy'
export type InstallCommand = export type InstallCommand =
...@@ -111,6 +114,7 @@ export class NextInstance { ...@@ -111,6 +114,7 @@ export class NextInstance {
public serverReadyPattern: RegExp = /✓ Ready in / public serverReadyPattern: RegExp = /✓ Ready in /
patchFileDelay: number = 0 patchFileDelay: number = 0
public deleteWorkspaceFile: boolean = false public deleteWorkspaceFile: boolean = false
private _resolvedConfig?: Promise<ResolvedNextConfig>
constructor(opts: NextInstanceOpts) { constructor(opts: NextInstanceOpts) {
this.env = {} this.env = {}
...@@ -531,6 +535,60 @@ export class NextInstance { ...@@ -531,6 +535,60 @@ export class NextInstance {
}) })
} }
/**
* The phase this fixture's `next.config` should be resolved for. `next dev`
* overrides it; deploy mode resolves the production-build phase locally,
* which is a best-effort approximation of the remote build.
*/
protected get configPhase(): string {
return PHASE_PRODUCTION_BUILD
}
/**
* This fixture's **resolved** `next.config` — i.e. the output of
* `loadConfig`, not the config file. Resolution implies flags the fixture
* never mentions (`cacheComponents: true` turns on `experimental.ppr`) and
* honours the env the fixture actually runs with.
*
* Used by `// @gate` conditions (see test/lib/gate/README.md). Memoized per
* instance and resolved lazily, so a suite that never asks pays nothing; a
* suite that rewrites its own `next.config` mid-run keeps the first answer.
*/
public getResolvedConfig(): Promise<ResolvedNextConfig> {
return (this._resolvedConfig ??= loadResolvedConfig({
dir: this.testDir,
phase: this.configPhase,
env: this.getSpawnOpts().env,
}))
}
/**
* The options every child process of this fixture is spawned with — its cwd,
* and the exact env `next build` / `next dev` / `next start` see.
*
* Anything that inspects the fixture out of process (e.g. resolving its
* `next.config`) has to use this env, because config resolution reads env
* vars from the calling process and a suite may pass its own via
* `nextTestSetup({ env })`.
*/
protected getSpawnOpts(
env?: Record<string, string>
): import('child_process').SpawnOptions {
return {
cwd: this.testDir,
stdio: ['ignore', 'pipe', 'pipe'],
shell: false,
env: {
...process.env,
...this.env,
...env,
NODE_ENV: this.env.NODE_ENV || ('' as any),
PORT: this.forcedPort ?? '0',
__NEXT_TEST_MODE: 'e2e',
},
}
}
protected setServerReadyTimeout( protected setServerReadyTimeout(
reject: (reason?: unknown) => void, reject: (reason?: unknown) => void,
ms: number ms: number
......
import spawn from 'cross-spawn' import spawn from 'cross-spawn'
import { Span } from 'next/dist/trace' import { Span } from 'next/dist/trace'
import { NextInstance } from './base' import { NextInstance } from './base'
import { PHASE_DEVELOPMENT_SERVER } from 'next/constants'
import { retry, waitFor } from 'next-test-utils' import { retry, waitFor } from 'next-test-utils'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
import { quote as shellQuote } from 'shell-quote' import { quote as shellQuote } from 'shell-quote'
...@@ -12,6 +13,10 @@ export class NextDevInstance extends NextInstance { ...@@ -12,6 +13,10 @@ export class NextDevInstance extends NextInstance {
return 'development' return 'development'
} }
protected get configPhase() {
return PHASE_DEVELOPMENT_SERVER
}
public async setup(parentSpan: Span) { public async setup(parentSpan: Span) {
super.setup(parentSpan) super.setup(parentSpan)
await super.createTestDir({ parentSpan }) await super.createTestDir({ parentSpan })
...@@ -61,24 +66,6 @@ export class NextDevInstance extends NextInstance { ...@@ -61,24 +66,6 @@ export class NextDevInstance extends NextInstance {
return buildArgs return buildArgs
} }
private getSpawnOpts(
env?: Record<string, string>
): import('child_process').SpawnOptions {
return {
cwd: this.testDir,
stdio: ['ignore', 'pipe', 'pipe'],
shell: false,
env: {
...process.env,
...this.env,
...env,
NODE_ENV: this.env.NODE_ENV || ('' as any),
PORT: this.forcedPort || '0',
__NEXT_TEST_MODE: 'e2e',
},
}
}
public async build( public async build(
options: { env?: Record<string, string>; args?: string[] } = {} options: { env?: Record<string, string>; args?: string[] } = {}
) { ) {
......
...@@ -266,24 +266,6 @@ export class NextStartInstance extends NextInstance { ...@@ -266,24 +266,6 @@ export class NextStartInstance extends NextInstance {
return buildArgs return buildArgs
} }
private getSpawnOpts(
env?: Record<string, string>
): import('child_process').SpawnOptions {
return {
cwd: this.testDir,
stdio: ['ignore', 'pipe', 'pipe'],
shell: false,
env: {
...process.env,
...this.env,
...env,
NODE_ENV: this.env.NODE_ENV || ('' as any),
PORT: this.forcedPort ?? '0',
__NEXT_TEST_MODE: 'e2e',
},
}
}
public async build( public async build(
options: { env?: Record<string, string>; args?: string[] } = {} options: { env?: Record<string, string>; args?: string[] } = {}
) { ) {
......
...@@ -43,6 +43,9 @@ import { RequiredServerFilesManifest } from 'next/dist/build' ...@@ -43,6 +43,9 @@ import { RequiredServerFilesManifest } from 'next/dist/build'
export { shouldUseTurbopack } export { shouldUseTurbopack }
// The runtime counterpart of the `// @gate` pragma. See test/lib/gate/README.md.
export { gate } from './gate/runtime'
export const nextServer = server export const nextServer = server
export const pkg = _pkg export const pkg = _pkg
......
import { evaluate, parse } from '../../lib/gate/expr'
const run = (source: string, values: Record<string, unknown> = {}) =>
evaluate(parse(source).node, (name) => values[name])
describe('@gate expression language', () => {
it('reads a bare condition by truthiness', () => {
expect(run('a', { a: true })).toBe(true)
expect(run('a', { a: false })).toBe(false)
expect(run('a', {})).toBe(false)
// A condition whose resolved value is an object (e.g. prefetchInlining).
expect(run('a', { a: { maxSize: 2048 } })).toBe(true)
})
it('supports negation', () => {
expect(run('!a', { a: false })).toBe(true)
expect(run('!!a', { a: false })).toBe(false)
})
it('supports && and ||', () => {
expect(run('a && b', { a: true, b: true })).toBe(true)
expect(run('a && b', { a: true, b: false })).toBe(false)
expect(run('a || b', { a: false, b: true })).toBe(true)
expect(run('!a && b', { a: false, b: true })).toBe(true)
})
it('supports parentheses', () => {
expect(run('!(a && b)', { a: true, b: false })).toBe(true)
expect(run('!a && (b || c)', { a: false, b: false, c: true })).toBe(true)
})
it('compares against string literals', () => {
expect(run("mode === 'start'", { mode: 'start' })).toBe(true)
expect(run("mode === 'start'", { mode: 'dev' })).toBe(false)
expect(run('mode !== "dev"', { mode: 'start' })).toBe(true)
expect(run("mode == 'dev'", { mode: 'dev' })).toBe(true)
})
it('compares against booleans', () => {
expect(run('a === false', { a: false })).toBe(true)
expect(run('a === true', { a: undefined })).toBe(false)
})
it('collects the referenced condition names, deduplicated', () => {
expect(parse("!a && (b || a) && c === 'x'").names).toEqual(['a', 'b', 'c'])
expect(parse("mode === 'dev'").names).toEqual(['mode'])
})
it.each([
['', 'Unexpected end of expression'],
['a &&', 'Unexpected end of expression'],
['(a', 'Missing closing `)`'],
['a b', 'after a complete expression'],
["'unterminated", 'Unterminated string'],
['a # b', 'Unexpected character'],
])('reports a syntax error for %p', (source, message) => {
expect(() => parse(source)).toThrow(message)
})
})
/* eslint-env jest */
const { rewrite } = require('../../lib/gate/pragma-transform')
// NOTE: fixtures are built by joining arrays of lines instead of using template
// literals. A template literal containing a `// @gate` line directly above an
// `it(` line would itself be rewritten when *this* file is transformed, since
// the rewrite is intentionally a line-oriented regex over the raw source.
const src = (...lines: string[]) => lines.join('\n') + '\n'
describe('@gate pragma transform', () => {
it('leaves files without a pragma untouched (identity, not a copy)', () => {
const input = src("it('a', () => {})")
expect(rewrite(input, 'x.test.ts')).toBe(input)
})
it('rewrites a single pragma over `it`', () => {
const out = rewrite(
src('// @gate !cacheComponents', "it('a', () => {})"),
'x.test.ts'
)
expect(out).toBe(
src(
'// @gate !cacheComponents',
`_test_gate([{"force":false,"source":"!cacheComponents"}],"it")('a', () => {})`
)
)
})
it('preserves indentation and line count', () => {
const input = src(
'describe(() => {',
' // @gate dev',
" it('a', () => {",
' expect(1).toBe(1)',
' })',
'})'
)
const out = rewrite(input, 'x.test.ts')
expect(out.split('\n')).toHaveLength(input.split('\n').length)
expect(out.split('\n')[2]).toBe(
` _test_gate([{"force":false,"source":"dev"}],"it")('a', () => {`
)
// Every line other than the rewritten call site is byte-identical.
const inLines = input.split('\n')
const outLines = out.split('\n')
for (let i = 0; i < inLines.length; i++) {
if (i === 2) continue
expect(outLines[i]).toBe(inLines[i])
}
})
it('combines consecutive pragmas', () => {
const out = rewrite(
src('// @gate dev', '// @force-gate turbopack', "test('a', () => {})"),
'x.test.ts'
)
expect(out.split('\n')[2]).toBe(
`_test_gate([{"force":false,"source":"dev"},{"force":true,"source":"turbopack"}],"test")('a', () => {})`
)
})
it('rewrites a `@force-gate`-only file (no `@gate` substring)', () => {
// Guards the cheap bail-out: `@force-gate` does not contain `@gate`.
const input = src(
'// @force-gate !cacheComponents',
"describe('s', () => {})"
)
expect(input.includes('@gate')).toBe(false)
const out = rewrite(input, 'x.test.ts')
expect(out.split('\n')[1]).toBe(
`_test_gate([{"force":true,"source":"!cacheComponents"}],"describe")('s', () => {})`
)
})
it.each([
['it', 'it'],
['test', 'test'],
['fit', 'fit'],
['describe', 'describe'],
['it.only', 'it.only'],
['test.only', 'test.only'],
['describe.only', 'describe.only'],
])('supports %s', (callee, kind) => {
const out = rewrite(src('// @gate dev', `${callee}('a', () => {})`), 'x.ts')
expect(out.split('\n')[1]).toBe(
`_test_gate([{"force":false,"source":"dev"}],${JSON.stringify(
kind
)})('a', () => {})`
)
})
it('keeps the condition source verbatim, including quotes', () => {
const out = rewrite(
src("// @gate mode === 'start' && !turbopack", "it('a', () => {})"),
'x.test.ts'
)
expect(out.split('\n')[1]).toBe(
`_test_gate([{"force":false,"source":"mode === 'start' && !turbopack"}],"it")('a', () => {})`
)
})
describe('inert pragmas are hard errors', () => {
it('rejects a pragma separated from the call by a blank line', () => {
expect(() =>
rewrite(src('// @gate dev', '', "it('a', () => {})"), 'x.test.ts')
).toThrow('this `@gate` pragma has no effect')
})
it('rejects a pragma inside a JSDoc block', () => {
expect(() =>
rewrite(
src('/**', ' * some docs', ' */', '// @gate dev', 'const x = 1'),
'x.test.ts'
)
).toThrow('this `@gate` pragma has no effect')
})
it('rejects a pragma over it.each', () => {
expect(() =>
rewrite(src('// @gate dev', 'it.each([1])("a", () => {})'), 'x.test.ts')
).toThrow('this `@gate` pragma has no effect')
})
it('rejects a pragma over it.skip as ambiguous', () => {
expect(() =>
rewrite(src('// @gate dev', "it.skip('a', () => {})"), 'x.test.ts')
).toThrow('a `@gate` pragma on a skipped test is ambiguous')
})
it('rejects a pragma over xit / xdescribe / it.todo as ambiguous', () => {
for (const call of [
"xit('a', () => {})",
"xdescribe('a', () => {})",
"it.todo('a')",
"describe.skip('a', () => {})",
]) {
expect(() => rewrite(src('// @gate dev', call), 'x.test.ts')).toThrow(
'a `@gate` pragma on a skipped test is ambiguous'
)
}
})
it('rejects a stacked pragma block over a skip, pointing at the first pragma', () => {
expect(() =>
rewrite(
src('// @force-gate !dev', '// @gate dev', "xit('a', () => {})"),
'x.test.ts'
)
).toThrow(/x\.test\.ts:1[\s\S]*ambiguous/)
})
it('leaves a skip without a pragma alone', () => {
const input = src(
'// @gate dev',
"it('gated', () => {})",
"xit('skipped', () => {})",
"it.skip('also skipped', () => {})"
)
const out = rewrite(input, 'x.test.ts')
expect(out).toContain("xit('skipped', () => {})")
expect(out).toContain("it.skip('also skipped', () => {})")
})
it('reports the file and line', () => {
expect(() =>
rewrite(src('const x = 1', '// @gate dev', 'const y = 2'), 'x.test.ts')
).toThrow('x.test.ts:2')
})
it('rejects a pragma with no condition', () => {
expect(() =>
rewrite(src('// @gate', "it('a', () => {})"), 'x.test.ts')
).toThrow('needs a condition')
})
})
it('does not match prose comments that merely mention the word', () => {
const input = src(
'// Use @gate to mark a known failure.',
"it('a', () => {})"
)
expect(rewrite(input, 'x.test.ts')).toBe(input)
})
})
This diff is collapsed.
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