mirror of
https://github.com/vercel/next.js.git
synced 2026-09-20 02:25:18 +08:00
94327e8ade
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.
79 lines
3.6 KiB
TypeScript
79 lines
3.6 KiB
TypeScript
import { nextTestSetup } from 'e2e-utils'
|
|
import { retry } from 'next-test-utils'
|
|
|
|
const NOT_IMPLEMENTED_ERROR =
|
|
'Not implemented: this behavior is not yet supported when ' +
|
|
'`experimental.concurrentRouterQueue` is enabled.'
|
|
|
|
// `experimental.concurrentRouterQueue` swaps the router's entry-point modules
|
|
// (the navigator and the callServer action door) for the concurrent
|
|
// implementations at the bundler level. The concurrent implementations are
|
|
// currently stubs that throw a single distinctive error from every operation,
|
|
// so this suite verifies the fork wiring: the app boots on the concurrent
|
|
// modules without touching them, and every old-world entry point fails
|
|
// loudly instead of silently running the sequential implementation.
|
|
describe('concurrent-router-queue', () => {
|
|
const { next } = nextTestSetup({
|
|
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 () => {
|
|
// `pushErrorAsConsoleLog` records uncaught page errors into the console
|
|
// log capture, which works in both dev and start modes.
|
|
const browser = await next.browser('/', { pushErrorAsConsoleLog: true })
|
|
expect(await browser.elementByCss('#home').text()).toBe('home')
|
|
// Hydration is complete once the client components are interactive.
|
|
await browser.waitForElementByCss('#invoke-action')
|
|
// Nothing at boot may call into the stubs (or fail in any other way).
|
|
const errors = (await browser.log()).filter((log) => log.source === 'error')
|
|
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 () => {
|
|
const browser = await next.browser('/', { pushErrorAsConsoleLog: true })
|
|
await browser.waitForElementByCss('#invoke-action')
|
|
|
|
await browser.elementByCss('#to-target-page').click()
|
|
|
|
// The stub throws synchronously inside the click handler, which surfaces
|
|
// as an uncaught page error. Wait for it to confirm the click was
|
|
// processed.
|
|
await retry(async () => {
|
|
const errors = (await browser.log()).filter(
|
|
(log) =>
|
|
log.source === 'error' && log.message.includes(NOT_IMPLEMENTED_ERROR)
|
|
)
|
|
expect(errors.length).toBeGreaterThan(0)
|
|
})
|
|
|
|
// No navigation happened, soft or hard: Link calls preventDefault()
|
|
// before dispatching, and the stub throws before any router state or
|
|
// pending-URL bookkeeping, so there is no fallback hard navigation.
|
|
expect(new URL(await browser.url()).pathname).toBe('/')
|
|
// The home page is still rendered; the target page never appears.
|
|
expect(await browser.elementByCss('#home').text()).toBe('home')
|
|
expect(await browser.hasElementByCssSelector('#target-page')).toBe(false)
|
|
})
|
|
|
|
// @gate concurrentRouterQueue
|
|
it('fails loudly on server action invocation', async () => {
|
|
const browser = await next.browser('/')
|
|
await browser.waitForElementByCss('#invoke-action')
|
|
|
|
await browser.elementByCss('#invoke-action').click()
|
|
|
|
// callServer is async, so the stub surfaces as a rejection of the promise
|
|
// returned to the action caller, which the fixture renders. The result
|
|
// element is empty (and hidden) until the rejection renders, so
|
|
// elementByCss waits for it to appear.
|
|
expect(await browser.elementByCss('#action-result').text()).toBe(
|
|
`rejected: ${NOT_IMPLEMENTED_ERROR}`
|
|
)
|
|
})
|
|
})
|