Files
vercel__next.js/test/jest-setup-after-env.ts
Andrew Clark 94327e8ade 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.
2026-08-26 10:22:11 -04:00

132 lines
4.3 KiB
TypeScript

import * as matchers from 'jest-extended'
import { installGate } from './lib/gate/runtime'
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)
// 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
if (process.platform === 'win32') {
try {
const testUtils = require('jscodeshift/dist/testUtils')
const fs = require('fs')
const path = require('path')
// Helper to normalize line endings
// - Convert CRLF to LF
// - Remove trailing whitespace from each line (not meaningful for code)
// - Ensure exactly one trailing newline (POSIX convention for text files)
// Using \n*$ to handle case where transform output has no trailing newline
const normalizeLF = (str: string) =>
str
.replace(/\r\n/g, '\n')
.replace(/[ \t]+$/gm, '')
.replace(/\n*$/, '\n')
// Patch runInlineTest to normalize both transform output and expected
testUtils.runInlineTest = function (
module: any,
options: any,
input: any,
expectedOutput: string,
testOptions?: any
) {
// Normalize input source
const normalizedInput =
typeof input === 'object' && input.source
? { ...input, source: normalizeLF(input.source) }
: input
// Normalize expected output
const normalizedExpected = normalizeLF(expectedOutput)
// Run the transform and normalize its output for comparison
const output = testUtils.applyTransform(
module,
options,
normalizedInput,
testOptions
)
const normalizedOutput =
typeof output === 'string' ? normalizeLF(output) : output
// Do the comparison ourselves instead of letting the original do it
// eslint-disable-next-line jest/no-standalone-expect -- called from within test blocks
expect(normalizedOutput).toEqual(normalizedExpected)
return normalizedOutput
}
// Replace defineTest entirely since it uses internal closure references
// that bypass our exports patch
testUtils.defineTest = function (
dirName: string,
transformName: string,
options: any,
testFilePrefix?: string,
testOptions?: { parser?: string }
) {
const testName = testFilePrefix
? `transforms correctly using "${testFilePrefix}" data`
: 'transforms correctly'
describe(transformName, () => {
it(testName, () => {
const fixtureDir = path.join(dirName, '..', '__testfixtures__')
const prefix = testFilePrefix || transformName
const module = require(path.join(dirName, '..', transformName))
// Determine file extension based on parser option
const parser = testOptions?.parser || module.parser
const extension =
parser === 'ts' ? 'ts' : parser === 'tsx' ? 'tsx' : 'js'
const inputPath = path.join(
fixtureDir,
`${prefix}.input.${extension}`
)
const outputPath = path.join(
fixtureDir,
`${prefix}.output.${extension}`
)
const source = normalizeLF(fs.readFileSync(inputPath, 'utf8'))
const expectedOutput = normalizeLF(
fs.readFileSync(outputPath, 'utf8')
)
testUtils.runInlineTest(
module,
options,
{ path: inputPath, source },
expectedOutput,
testOptions
)
})
})
}
} catch {
// jscodeshift not available, skip patching
}
}
// A default max-timeout of 90 seconds is allowed
// per test we should aim to bring this down though
jest.setTimeout((process.platform === 'win32' ? 180 : 60) * 1000)
// Polyfill for `using` https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html
if (!Symbol.dispose) {
Object.defineProperty(Symbol, 'dispose', {
value: Symbol('Symbol.dispose'),
})
}
if (!Symbol.asyncDispose) {
Object.defineProperty(Symbol, 'asyncDispose', {
value: Symbol('Symbol.asyncDispose'),
})
}