Unverified Commit 55e64de0 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

test: migrate more conditions to gates (#100422)

**View without whitespace changes**
parent 7748e532
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { gate, retry } from 'next-test-utils'
// These tests send SIGINT/SIGTERM to a local Next.js process and observe whether // These tests send SIGINT/SIGTERM to a local Next.js process and observe whether
// after() finishes before it exits. Vercel manages the deployed process lifecycle, // after() finishes before it exits. Vercel manages the deployed process lifecycle,
// so the test runner cannot trigger and observe this shutdown sequence. // so the test runner cannot trigger and observe this shutdown sequence.
// @force-gate !deploy // @force-gate !deploy
describe('after during server shutdown - next start', () => { describe('after during server shutdown - next start', () => {
const { next, isNextDev } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
skipStart: true, skipStart: true,
}) })
...@@ -20,33 +20,20 @@ describe('after during server shutdown - next start', () => { ...@@ -20,33 +20,20 @@ describe('after during server shutdown - next start', () => {
await next.stop() await next.stop()
}, 10_000) }, 10_000)
if (isNextDev) { it.each(['SIGINT', 'SIGTERM'] as const)(
// `next dev` shuts down the child process that runs the server without waiting for cleanups, 'handles after callbacks when the server receives %s',
// so `after` callbacks won't have the chance to complete async (signal) => {
it.each(['SIGINT', 'SIGTERM'] as const)( await next.render('/')
'does not wait for after callbacks when the server receives %s', await retry(async () => {
async (signal) => { expect(next.cliOutput).toInclude('[after] starting sleep')
await next.render('/') })
await retry(async () => { await next.stop(signal)
expect(next.cliOutput).toInclude('[after] starting sleep') if (await gate('dev')) {
}) // `next dev` shuts down its server child without waiting for cleanups.
await next.stop(signal)
expect(next.cliOutput).not.toInclude('[after] finished sleep') expect(next.cliOutput).not.toInclude('[after] finished sleep')
} } else {
)
}
if (!isNextDev) {
it.each(['SIGINT', 'SIGTERM'] as const)(
'waits for after callbacks when the server receives %s',
async (signal) => {
await next.render('/')
await retry(async () => {
expect(next.cliOutput).toInclude('[after] starting sleep')
})
await next.stop(signal)
expect(next.cliOutput).toInclude('[after] finished sleep') expect(next.cliOutput).toInclude('[after] finished sleep')
} }
) }
} )
}) })
...@@ -11,12 +11,8 @@ import * as path from 'path' ...@@ -11,12 +11,8 @@ import * as path from 'path'
// This suite lives in its own monorepo rather than in // This suite lives in its own monorepo rather than in
// `test/e2e/app-dir/non-root-project-monorepo`, so that skipping it here doesn't // `test/e2e/app-dir/non-root-project-monorepo`, so that skipping it here doesn't
// take that suite's webpack coverage with it. // take that suite's webpack coverage with it.
const testFn = // @force-gate turbopack
process.env.IS_WEBPACK_TEST || process.env.NEXT_RSPACK describe('import-meta-glob-monorepo', () => {
? describe.skip
: describe
testFn('import-meta-glob-monorepo', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: { files: {
apps: new FileRef(path.resolve(__dirname, 'apps')), apps: new FileRef(path.resolve(__dirname, 'apps')),
......
...@@ -68,7 +68,9 @@ const addCacheBustingSearchParam = async ( ...@@ -68,7 +68,9 @@ const addCacheBustingSearchParam = async (
} }
// TODO(NAR-423): Migrate to Cache Components. // TODO(NAR-423): Migrate to Cache Components.
describe.skip('ppr-full', () => { // The legacy route segment configs must be migrated before the fixture can build.
// @force-gate FIXME
describe('ppr-full', () => {
const { next, isNextDev, isNextDeploy } = nextTestSetup({ const { next, isNextDev, isNextDeploy } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
......
import { nextTestSetup, isNextDev } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
// TODO(NAR-423): Migrate to Cache Components. // TODO(NAR-423): Migrate to Cache Components.
describe.skip('search-params', () => { // @force-gate FIXME
if (isNextDev) { // @force-gate prefetching
test('ppr is disabled in dev', () => {}) describe('search-params', () => {
return
}
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { retry } from 'next-test-utils'
// The instrumentation assertion reads local runtime logs.
// @force-gate !deploy
describe('proxy-page-extensions', () => { describe('proxy-page-extensions', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
skipDeployment: true,
}) })
it('should execute proxy.page.ts and set custom header', async () => { it('should execute proxy.page.ts and set custom header', async () => {
......
...@@ -3,17 +3,13 @@ import type { ChildProcess } from 'child_process' ...@@ -3,17 +3,13 @@ import type { ChildProcess } from 'child_process'
import type { Server } from 'http' import type { Server } from 'http'
import { createRouterAct } from 'router-act' import { createRouterAct } from 'router-act'
import { findPort } from 'next-test-utils' import { findPort } from 'next-test-utils'
import { isNextDeploy, isNextDev, nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { createFakeCDN } from './server.mjs' import { createFakeCDN } from './server.mjs'
// This suite runs Next.js behind an in-process fake CDN on local ports.
// @force-gate !deploy
// @force-gate prefetching
describe('segment cache (CDN cache busting)', () => { describe('segment cache (CDN cache busting)', () => {
// Deploy mode exclusion: This suite runs Next.js behind an in-process fake
// CDN on local ports.
if (isNextDev || isNextDeploy) {
test('should not run during dev or deploy test runs', () => {})
return
}
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
skipStart: true, skipStart: true,
......
...@@ -2,16 +2,13 @@ import type * as Playwright from 'playwright' ...@@ -2,16 +2,13 @@ import type * as Playwright from 'playwright'
import type { Server } from 'http' import type { Server } from 'http'
import { createRouterAct } from 'router-act' import { createRouterAct } from 'router-act'
import { findPort } from 'next-test-utils' import { findPort } from 'next-test-utils'
import { isNextStart, nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { join } from 'path' import { join } from 'path'
import { createExportServer } from './server.mjs' import { createExportServer } from './server.mjs'
// Builds and serves the local static export with a custom server-side rewrite.
// @force-gate start
describe('segment cache (output: "export")', () => { describe('segment cache (output: "export")', () => {
if (!isNextStart) {
test('build test should not run during dev test run', () => {})
return
}
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
skipStart: true, skipStart: true,
......
import execa from 'execa' import execa from 'execa'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { getDistDir, retry } from 'next-test-utils' import { gate, getDistDir, retry } from 'next-test-utils'
const strictRouteTypes =
process.env.__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES === 'true'
// TODO(deploy-test-completion): Re-enable this suite in deploy mode. // TODO(deploy-test-completion): Re-enable this suite in deploy mode.
// It likely expects a local build failure instead of a successful deployment. // It likely expects a local build failure instead of a successful deployment.
// @force-gate !deploy // @force-gate !deploy
describe('typed-routes-validator', () => { describe('typed-routes-validator', () => {
const { next, isNextDev, isNextStart } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
files: __dirname, files: __dirname,
skipStart: true, skipStart: true,
}) })
...@@ -72,7 +69,9 @@ describe('typed-routes-validator', () => { ...@@ -72,7 +69,9 @@ describe('typed-routes-validator', () => {
} }
}) })
if (isNextStart) { // Type validation here explicitly runs local production builds.
// @force-gate start
describe('production mode', () => {
it('should pass type checking with valid page exports', async () => { it('should pass type checking with valid page exports', async () => {
await next.patchFile( await next.patchFile(
'app/test-page.tsx', 'app/test-page.tsx',
...@@ -104,7 +103,7 @@ describe('typed-routes-validator', () => { ...@@ -104,7 +103,7 @@ describe('typed-routes-validator', () => {
await next.deleteFile('app/invalid/page.tsx') await next.deleteFile('app/invalid/page.tsx')
expect(exitCode).toBe(1) expect(exitCode).toBe(1)
if (strictRouteTypes) { if (await gate('strictRouteTypes')) {
expect(cliOutput).toMatch( expect(cliOutput).toMatch(
/Type error: Type 'typeof import\(.*' does not satisfy the expected type 'AppPageConfig</ /Type error: Type 'typeof import\(.*' does not satisfy the expected type 'AppPageConfig</
) )
...@@ -147,7 +146,7 @@ describe('typed-routes-validator', () => { ...@@ -147,7 +146,7 @@ describe('typed-routes-validator', () => {
await next.deleteFile('app/invalid/page.tsx') await next.deleteFile('app/invalid/page.tsx')
expect(exitCode).toBe(1) expect(exitCode).toBe(1)
if (strictRouteTypes) { if (await gate('strictRouteTypes')) {
expect(cliOutput).toMatch( expect(cliOutput).toMatch(
/Type error: Type 'typeof import\(.*' does not satisfy the expected type 'AppPageConfig</ /Type error: Type 'typeof import\(.*' does not satisfy the expected type 'AppPageConfig</
) )
...@@ -216,7 +215,7 @@ describe('typed-routes-validator', () => { ...@@ -216,7 +215,7 @@ describe('typed-routes-validator', () => {
await next.deleteFile('app/invalid/route.ts') await next.deleteFile('app/invalid/route.ts')
expect(exitCode).toBe(1) expect(exitCode).toBe(1)
if (strictRouteTypes) { if (await gate('strictRouteTypes')) {
expect(cliOutput).toMatch( expect(cliOutput).toMatch(
/Type error: Type 'typeof import\(.*' does not satisfy the expected type 'RouteHandlerConfig</ /Type error: Type 'typeof import\(.*' does not satisfy the expected type 'RouteHandlerConfig</
) )
...@@ -243,7 +242,7 @@ describe('typed-routes-validator', () => { ...@@ -243,7 +242,7 @@ describe('typed-routes-validator', () => {
await next.deleteFile('app/invalid-2/route.ts') await next.deleteFile('app/invalid-2/route.ts')
expect(exitCode).toBe(1) expect(exitCode).toBe(1)
if (strictRouteTypes) { if (await gate('strictRouteTypes')) {
expect(cliOutput).toMatch( expect(cliOutput).toMatch(
/Type error: Type 'typeof import\(.*' does not satisfy the expected type 'RouteHandlerConfig</ /Type error: Type 'typeof import\(.*' does not satisfy the expected type 'RouteHandlerConfig</
) )
...@@ -290,7 +289,7 @@ describe('typed-routes-validator', () => { ...@@ -290,7 +289,7 @@ describe('typed-routes-validator', () => {
await next.deleteFile('app/invalid/layout.tsx') await next.deleteFile('app/invalid/layout.tsx')
expect(exitCode).toBe(1) expect(exitCode).toBe(1)
if (strictRouteTypes) { if (await gate('strictRouteTypes')) {
expect(cliOutput).toMatch( expect(cliOutput).toMatch(
/Type error: Type 'typeof import\(.*' does not satisfy the expected type 'LayoutConfig</ /Type error: Type 'typeof import\(.*' does not satisfy the expected type 'LayoutConfig</
) )
...@@ -340,7 +339,7 @@ describe('typed-routes-validator', () => { ...@@ -340,7 +339,7 @@ describe('typed-routes-validator', () => {
await next.deleteFile('pages/api/invalid-api.ts') await next.deleteFile('pages/api/invalid-api.ts')
expect(exitCode).toBe(1) expect(exitCode).toBe(1)
if (strictRouteTypes) { if (await gate('strictRouteTypes')) {
expect(cliOutput).toMatch( expect(cliOutput).toMatch(
/Type error: Type 'typeof import\(.*' does not satisfy the expected type 'ApiRouteConfig'/ /Type error: Type 'typeof import\(.*' does not satisfy the expected type 'ApiRouteConfig'/
) )
...@@ -350,5 +349,5 @@ describe('typed-routes-validator', () => { ...@@ -350,5 +349,5 @@ describe('typed-routes-validator', () => {
) )
} }
}) })
} })
}) })
...@@ -8,80 +8,81 @@ import { retry } from '../../../lib/next-test-utils' ...@@ -8,80 +8,81 @@ import { retry } from '../../../lib/next-test-utils'
// reads cli logs // reads cli logs
// @force-gate !deploy // @force-gate !deploy
describe('use cache called after tasky uncached IO', () => { describe('use cache called after tasky uncached IO', () => {
const { next, isNextStart } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
if (isNextStart) { // Prefetching is disabled in dev.
it('does not store an incomplete cache entry in the cache handler', async () => { // @force-gate prefetching
// This is a regression test against for a bug: it('does not store an incomplete cache entry in the cache handler', async () => {
// https://github.com/vercel/next.js/issues/96339 // This is a regression test against for a bug:
// If a cache read was initiated after the prerender was aborted (due to tasky IO), // https://github.com/vercel/next.js/issues/96339
// we'd try filling the cache, immediately abort the fill (because it was tied to // If a cache read was initiated after the prerender was aborted (due to tasky IO),
// renderSignal, which was already aborted), and then save the empty cache entry, // we'd try filling the cache, immediately abort the fill (because it was tied to
// effectively poisoning future reads of that cache. // renderSignal, which was already aborted), and then save the empty cache entry,
// effectively poisoning future reads of that cache.
// Revalidate /uses-cache (and, just to be safe, the cache that it references) // Revalidate /uses-cache (and, just to be safe, the cache that it references)
// so that we have a fresh prerender we can assert on // so that we have a fresh prerender we can assert on
await next.fetch('/revalidate-uses-cache', { method: 'POST' }) await next.fetch('/revalidate-uses-cache', { method: 'POST' })
let page: Playwright.Page let page: Playwright.Page
const browser = await next.browser('/', { const browser = await next.browser('/', {
beforePageLoad(p) { beforePageLoad(p) {
page = p page = p
}, },
}) })
const act = createRouterAct(page) const act = createRouterAct(page)
// Prefetch the page, triggering a fresh prerender // Prefetch the page, triggering a fresh prerender
await act(async () => { await act(async () => {
await browser await browser
.elementByCss('input[data-link-accordion="/uses-cache"]') .elementByCss('input[data-link-accordion="/uses-cache"]')
.click() .click()
}, [ }, [
{ {
// Sanity check: the prefetch should not include the cache // Sanity check: the prefetch should not include the cache
includes: 'cached-data', includes: 'cached-data',
block: 'reject', block: 'reject',
}, },
]) ])
// Wait for the call to the "use cache" function to finish. // Wait for the call to the "use cache" function to finish.
// Before the bugfix, reading the cache would result in an incorrect value // Before the bugfix, reading the cache would result in an incorrect value
// being stored in the cache handler, so we need to make sure the cache // being stored in the cache handler, so we need to make sure the cache
// is finished before we proceed. // is finished before we proceed.
await retry( await retry(
() => { () => {
expect(next.cliOutput).toContain('after-cache-read') expect(next.cliOutput).toContain('after-cache-read')
}, },
5000, 5000,
200 200
) )
await setTimeout(500) await setTimeout(500)
// Navigate to the page. The response should include the cache // Navigate to the page. The response should include the cache
await act( await act(
async () => { async () => {
await browser.elementByCss('a[href="/uses-cache"]').click() await browser.elementByCss('a[href="/uses-cache"]').click()
}, },
{ includes: 'cached-data' } { includes: 'cached-data' }
) )
// The bug manifested as the cache read throwing "Error: Connection closed." // The bug manifested as the cache read throwing "Error: Connection closed."
// If we can observe the cache's value, then everything is ok. // If we can observe the cache's value, then everything is ok.
expect(await browser.elementByCss('#data').text()).toMatch( expect(await browser.elementByCss('#data').text()).toMatch(
/cached-data: \d+/ /cached-data: \d+/
) )
}) })
} else {
it('resolves in dev', async () => { // @force-gate dev
// There's no prefetching in dev, so the best we can do is it('resolves in dev', async () => {
// test that the cache resolves as expected. // There's no prefetching in dev, so the best we can do is
const browser = await next.browser('/uses-cache') // test that the cache resolves as expected.
expect(await browser.elementByCss('#data').text()).toMatch( const browser = await next.browser('/uses-cache')
/cached-data: \d+/ expect(await browser.elementByCss('#data').text()).toMatch(
) /cached-data: \d+/
}) )
} })
}) })
...@@ -11,37 +11,33 @@ describe('fetch failures have good stack traces in edge runtime', () => { ...@@ -11,37 +11,33 @@ describe('fetch failures have good stack traces in edge runtime', () => {
}) })
// TODO: Failure is not specific to Turbopack, edge runtime errors don't have source maps applied. // TODO: Failure is not specific to Turbopack, edge runtime errors don't have source maps applied.
;(process.env.IS_TURBOPACK_TEST && isNextStart ? it.skip : it)( // @gate !(turbopack && start)
'when awaiting `fetch` using an unknown domain, stack traces are preserved', it('when awaiting `fetch` using an unknown domain, stack traces are preserved', async () => {
async () => { const outputIndex = next.cliOutput.length
const outputIndex = next.cliOutput.length const browser = await next.browser('/api/unknown-domain')
const browser = await next.browser('/api/unknown-domain')
if (isNextStart) { if (isNextStart) {
// eslint-disable-next-line jest/no-standalone-expect expect(next.cliOutput.slice(outputIndex)).toMatch(
expect(next.cliOutput.slice(outputIndex)).toMatch( /at.+\/pages\/api\/unknown-domain.js/
/at.+\/pages\/api\/unknown-domain.js/ )
) } else if (isNextDev) {
} else if (isNextDev) { expect(stripAnsi(next.cliOutput.slice(outputIndex))).toContain(
// eslint-disable-next-line jest/no-standalone-expect '⨯ Error [TypeError]: fetch failed' +
expect(stripAnsi(next.cliOutput.slice(outputIndex))).toContain( '\n at anotherFetcher (src/fetcher.js:6:16)' +
'⨯ Error [TypeError]: fetch failed' + '\n at fetcher (src/fetcher.js:2:16)' +
'\n at anotherFetcher (src/fetcher.js:6:16)' + '\n at UnknownDomainEndpoint (pages/api/unknown-domain.js:6:16)' +
'\n at fetcher (src/fetcher.js:2:16)' + '\n 4 |' +
'\n at UnknownDomainEndpoint (pages/api/unknown-domain.js:6:16)' + '\n 5 | async function anotherFetcher(...args) {' +
'\n 4 |' + '\n> 6 | return await fetch(...args)' +
'\n 5 | async function anotherFetcher(...args) {' + '\n | ^' +
'\n> 6 | return await fetch(...args)' + '\n 7 | }' +
'\n | ^' + '\n 8 |' +
'\n 7 | }' + // TODO(veil): Why double error?
'\n 8 |' + '\n⨯ Error [TypeError]: fetch failed'
// TODO(veil): Why double error? )
'\n⨯ Error [TypeError]: fetch failed'
)
// Turbopack produces incorrect mappings in the sourcemap. // Turbopack produces incorrect mappings in the sourcemap.
// eslint-disable-next-line jest/no-standalone-expect await expect(browser).toDisplayRedbox(`
await expect(browser).toDisplayRedbox(`
{ {
"description": "fetch failed", "description": "fetch failed",
"environmentLabel": null, "environmentLabel": null,
...@@ -56,12 +52,12 @@ describe('fetch failures have good stack traces in edge runtime', () => { ...@@ -56,12 +52,12 @@ describe('fetch failures have good stack traces in edge runtime', () => {
], ],
} }
`) `)
}
} }
) })
// TODO: It need to have source maps picked up by node.js // TODO: It need to have source maps picked up by node.js
it.skip('when returning `fetch` using an unknown domain, stack traces are preserved', async () => { // @gate FIXME
it('when returning `fetch` using an unknown domain, stack traces are preserved', async () => {
await next.browser('/api/unknown-domain-no-await') await next.browser('/api/unknown-domain-no-await')
await check( await check(
......
...@@ -8,6 +8,7 @@ import { retry, waitFor } from 'next-test-utils' ...@@ -8,6 +8,7 @@ import { retry, waitFor } from 'next-test-utils'
// It likely mutates files in the isolated local fixture after setup. // It likely mutates files in the isolated local fixture after setup.
// @force-gate !deploy // @force-gate !deploy
// @force-gate dev // @force-gate dev
// @force-gate turbopack
describe('evict-after-snapshot', () => { describe('evict-after-snapshot', () => {
const env = { const env = {
ENABLE_CACHING: '1', ENABLE_CACHING: '1',
...@@ -30,60 +31,49 @@ describe('evict-after-snapshot', () => { ...@@ -30,60 +31,49 @@ describe('evict-after-snapshot', () => {
await waitFor(5000) await waitFor(5000)
} }
// Turbopack-only: eviction requires persistent caching it('should serve correct content after eviction and HMR', async () => {
;(process.env.IS_TURBOPACK_TEST ? it : it.skip)( const browser = await next.browser('/')
'should serve correct content after eviction and HMR', await retry(async () => {
async () => { expect(await browser.elementByCss('p').text()).toBe('hello world')
const browser = await next.browser('/') })
let currentContent = 'hello world'
for (let cycle = 1; cycle <= 3; cycle++) {
await waitForSnapshotAndEviction()
const prevContent = currentContent
const nextContent = `cycle ${cycle}`
await next.patchFile('app/page.tsx', (content) =>
content.replace(prevContent, nextContent)
)
currentContent = nextContent
const expected = currentContent
await retry(async () => { await retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('hello world') expect(await browser.elementByCss('p').text()).toBe(expected)
}) }, 10000)
}
let currentContent = 'hello world' await browser.close()
for (let cycle = 1; cycle <= 3; cycle++) { }, 90000)
await waitForSnapshotAndEviction() it('should handle client component HMR after eviction', async () => {
const browser = await next.browser('/client')
await retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('hello world')
})
const prevContent = currentContent await waitForSnapshotAndEviction()
const nextContent = `cycle ${cycle}`
await next.patchFile('app/page.tsx', (content) =>
content.replace(prevContent, nextContent)
)
currentContent = nextContent
const expected = currentContent await next.patchFile(
'app/client/page.tsx',
(content) => content.replace('hello world', 'hello eviction'),
async () => {
await retry(async () => { await retry(async () => {
expect(await browser.elementByCss('p').text()).toBe(expected) expect(await browser.elementByCss('p').text()).toBe('hello eviction')
}, 10000) }, 10000)
} }
)
await browser.close() await browser.close()
}, }, 90000)
90000
)
;(process.env.IS_TURBOPACK_TEST ? it : it.skip)(
'should handle client component HMR after eviction',
async () => {
const browser = await next.browser('/client')
await retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('hello world')
})
await waitForSnapshotAndEviction()
await next.patchFile(
'app/client/page.tsx',
(content) => content.replace('hello world', 'hello eviction'),
async () => {
await retry(async () => {
expect(await browser.elementByCss('p').text()).toBe(
'hello eviction'
)
}, 10000)
}
)
await browser.close()
},
90000
)
}) })
...@@ -79,32 +79,32 @@ describe('warm-restart task statistics', () => { ...@@ -79,32 +79,32 @@ describe('warm-restart task statistics', () => {
return misses return misses
} }
if (isNextDev) { // @force-gate dev
it('snapshot of tasks with cache misses on warm dev restart', async () => { it('snapshot of tasks with cache misses on warm dev restart', async () => {
// Cycle 1: the harness already auto-started; perform a request so the // Cycle 1: the harness already auto-started; perform a request so the
// SSR/Node chunk work runs and gets persisted on shutdown. // SSR/Node chunk work runs and gets persisted on shutdown.
async function runDevCycle() { async function runDevCycle() {
const browser = await next.browser('/') const browser = await next.browser('/')
// Wait for actual rendered content before declaring "ready". // Wait for actual rendered content before declaring "ready".
await browser.elementByCss('p') await browser.elementByCss('p')
// Settle: the dev server keeps doing background work after first // Settle: the dev server keeps doing background work after first
// paint (HMR socket handshake, tail compilation). A fixed sleep // paint (HMR socket handshake, tail compilation). A fixed sleep
// is the least-bad option here since next.js doesn't expose // is the least-bad option here since next.js doesn't expose
// turbopack's internal idle signal. If this proves flaky in CI, // turbopack's internal idle signal. If this proves flaky in CI,
// raise the value. // raise the value.
await waitFor(2000) await waitFor(2000)
await browser.close() await browser.close()
} }
await runDevCycle() await runDevCycle()
await stop() await stop()
// Cycle 2: warm. // Cycle 2: warm.
await next.start() await next.start()
await runDevCycle() await runDevCycle()
await stop() await stop()
const missed = await readMissedTaskNames() const missed = await readMissedTaskNames()
expect(missed).toMatchInlineSnapshot(` expect(missed).toMatchInlineSnapshot(`
[ [
"<turbopack_browser::ecmascript::list::content::EcmascriptDevChunkListContent as dyn turbopack_core::version::VersionedContent>::update", "<turbopack_browser::ecmascript::list::content::EcmascriptDevChunkListContent as dyn turbopack_core::version::VersionedContent>::update",
"next_api::project::Project::hmr_update", "next_api::project::Project::hmr_update",
...@@ -114,21 +114,21 @@ describe('warm-restart task statistics', () => { ...@@ -114,21 +114,21 @@ describe('warm-restart task statistics', () => {
"turbopack_core::version::VersionState::get", "turbopack_core::version::VersionState::get",
] ]
`) `)
}, 180_000) }, 180_000)
} else {
it('snapshot of tasks with cache misses on warm build', async () => {
// In start mode the harness auto-runs `next build` then `next start`.
// The build is cycle 1. We stop the server (we don't care about it)
// and run a second build manually for the warm measurement.
await stop()
const result = await (next as any).build() // @force-gate start
if (result.exitCode !== 0) { it('snapshot of tasks with cache misses on warm build', async () => {
throw new Error(`next build exited with ${result.exitCode}`) // In start mode the harness auto-runs `next build` then `next start`.
} // The build is cycle 1. We stop the server (we don't care about it)
// and run a second build manually for the warm measurement.
await stop()
const missed = await readMissedTaskNames() const result = await (next as any).build()
expect(missed).toMatchInlineSnapshot(`[]`) if (result.exitCode !== 0) {
}, 240_000) throw new Error(`next build exited with ${result.exitCode}`)
} }
const missed = await readMissedTaskNames()
expect(missed).toMatchInlineSnapshot(`[]`)
}, 240_000)
}) })
...@@ -326,36 +326,38 @@ describe('Legacy Image Component basePath Tests', () => { ...@@ -326,36 +326,38 @@ describe('Legacy Image Component basePath Tests', () => {
) )
}) })
if (isNextDev) { // Image validation errors are development diagnostics.
it('should show missing src error', async () => { // @force-gate dev
const browser = await next.browser('/docs/missing-src') it('should show missing src error', async () => {
const browser = await next.browser('/docs/missing-src')
await waitForNoRedbox(browser) await waitForNoRedbox(browser)
await retry(async () => { await retry(async () => {
const logs = (await browser.log()).map((log) => log.message).join('\n') const logs = (await browser.log()).map((log) => log.message).join('\n')
expect(logs).toMatch(/Image is missing required "src" property/gm) expect(logs).toMatch(/Image is missing required "src" property/gm)
})
}) })
})
it('should show invalid src error', async () => { // @force-gate dev
const browser = await next.browser('/docs/invalid-src') it('should show invalid src error', async () => {
const browser = await next.browser('/docs/invalid-src')
await waitForRedbox(browser) await waitForRedbox(browser)
expect(await getRedboxHeader(browser)).toContain( expect(await getRedboxHeader(browser)).toContain(
'Invalid src prop (https://google.com/test.png) on `next/image`, hostname "google.com" is not configured under images in your `next.config.js`' 'Invalid src prop (https://google.com/test.png) on `next/image`, hostname "google.com" is not configured under images in your `next.config.js`'
) )
}) })
it('should show invalid src error when protocol-relative', async () => { // @force-gate dev
const browser = await next.browser('/docs/invalid-src-proto-relative') it('should show invalid src error when protocol-relative', async () => {
const browser = await next.browser('/docs/invalid-src-proto-relative')
await waitForRedbox(browser) await waitForRedbox(browser)
expect(await getRedboxHeader(browser)).toContain( expect(await getRedboxHeader(browser)).toContain(
'Failed to parse src "//assets.example.com/img.jpg" on `next/image`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)' 'Failed to parse src "//assets.example.com/img.jpg" on `next/image`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)'
) )
}) })
}
it('should correctly ignore prose styles', async () => { it('should correctly ignore prose styles', async () => {
const browser = await next.browser('/docs/prose') const browser = await next.browser('/docs/prose')
...@@ -376,24 +378,23 @@ describe('Legacy Image Component basePath Tests', () => { ...@@ -376,24 +378,23 @@ describe('Legacy Image Component basePath Tests', () => {
expect(getRatio(computedWidth, computedHeight)).toBeCloseTo(1, 1) expect(getRatio(computedWidth, computedHeight)).toBeCloseTo(1, 1)
}) })
if (!isNextDev) { // @force-gate prod
it('should correctly rotate image', async () => { it('should correctly rotate image', async () => {
const browser = await next.browser('/docs/rotated') const browser = await next.browser('/docs/rotated')
const id = 'exif-rotation-image' const id = 'exif-rotation-image'
await retry(async () => { await retry(async () => {
const result = await browser.eval( const result = await browser.eval(
`document.getElementById(${JSON.stringify(id)}).naturalWidth` `document.getElementById(${JSON.stringify(id)}).naturalWidth`
) )
expect(result).toBeGreaterThan(0) expect(result).toBeGreaterThan(0)
}) })
await new Promise((resolve) => setTimeout(resolve, 1000)) await new Promise((resolve) => setTimeout(resolve, 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')
expect(getRatio(computedWidth, computedHeight)).toBeCloseTo(0.5625, 1) expect(getRatio(computedWidth, computedHeight)).toBeCloseTo(0.5625, 1)
}) })
}
}) })
...@@ -99,36 +99,38 @@ describe('Image Component basePath Tests', () => { ...@@ -99,36 +99,38 @@ describe('Image Component basePath Tests', () => {
}) })
}) })
if (isNextDev) { // Image validation errors are development diagnostics.
it('should show missing src error', async () => { // @force-gate dev
const browser = await next.browser('/docs/missing-src') it('should show missing src error', async () => {
const browser = await next.browser('/docs/missing-src')
await waitForNoRedbox(browser) await waitForNoRedbox(browser)
await retry(async () => { await retry(async () => {
const logs = (await browser.log()).map((log) => log.message).join('\n') const logs = (await browser.log()).map((log) => log.message).join('\n')
expect(logs).toMatch(/Image is missing required "src" property/gm) expect(logs).toMatch(/Image is missing required "src" property/gm)
})
}) })
})
it('should show invalid src error', async () => { // @force-gate dev
const browser = await next.browser('/docs/invalid-src') it('should show invalid src error', async () => {
const browser = await next.browser('/docs/invalid-src')
await waitForRedbox(browser) await waitForRedbox(browser)
expect(await getRedboxHeader(browser)).toContain( expect(await getRedboxHeader(browser)).toContain(
'Invalid src prop (https://google.com/test.png) on `next/image`, hostname "google.com" is not configured under images in your `next.config.js`' 'Invalid src prop (https://google.com/test.png) on `next/image`, hostname "google.com" is not configured under images in your `next.config.js`'
) )
}) })
it('should show invalid src error when protocol-relative', async () => { // @force-gate dev
const browser = await next.browser('/docs/invalid-src-proto-relative') it('should show invalid src error when protocol-relative', async () => {
const browser = await next.browser('/docs/invalid-src-proto-relative')
await waitForRedbox(browser) await waitForRedbox(browser)
expect(await getRedboxHeader(browser)).toContain( expect(await getRedboxHeader(browser)).toContain(
'Failed to parse src "//assets.example.com/img.jpg" on `next/image`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)' 'Failed to parse src "//assets.example.com/img.jpg" on `next/image`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)'
) )
}) })
}
it('should correctly ignore prose styles', async () => { it('should correctly ignore prose styles', async () => {
const browser = await next.browser('/docs/prose') const browser = await next.browser('/docs/prose')
......
...@@ -25,7 +25,9 @@ function createTemporaryFixture(fixtureName: string) { ...@@ -25,7 +25,9 @@ function createTemporaryFixture(fixtureName: string) {
return dir return dir
} }
describe.skip('next test', () => { // TODO: Re-enable the experimental-test suite.
// @force-gate FIXME
describe('next test', () => {
const { next: basicExample } = nextTestSetup({ const { next: basicExample } = nextTestSetup({
files: new FileRef(join(__dirname, 'basic-example')), files: new FileRef(join(__dirname, 'basic-example')),
dependencies: { dependencies: {
...@@ -93,7 +95,8 @@ describe.skip('next test', () => { ...@@ -93,7 +95,8 @@ describe.skip('next test', () => {
}) })
// TODO: fix the playwright download issue // TODO: fix the playwright download issue
it.skip('should execute playwright tests', async () => { // @gate FIXME
it('should execute playwright tests', async () => {
const { stdout } = spawnSync('pnpm', ['next', 'experimental-test'], { const { stdout } = spawnSync('pnpm', ['next', 'experimental-test'], {
cwd: basicExample.testDir, cwd: basicExample.testDir,
encoding: 'utf-8', encoding: 'utf-8',
......
...@@ -2,95 +2,93 @@ import { FileRef, nextTestSetup } from 'e2e-utils' ...@@ -2,95 +2,93 @@ import { FileRef, nextTestSetup } from 'e2e-utils'
import { join } from 'path' import { join } from 'path'
// Not supported when using webpack. // Not supported when using webpack.
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)( // @force-gate turbopack
'postcss-config-ts', describe('postcss-config-ts', () => {
() => { describe('postcss.config.ts', () => {
describe('postcss.config.ts', () => { const { next } = nextTestSetup({
const { next } = nextTestSetup({ files: new FileRef(join(__dirname, 'postcss-config')),
files: new FileRef(join(__dirname, 'postcss-config')), })
})
it('works with postcss.config.ts files', async () => { it('works with postcss.config.ts files', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
try { try {
const text = await browser.elementByCss('#test').text() const text = await browser.elementByCss('#test').text()
expect(text).toBe('Hello World') expect(text).toBe('Hello World')
// The CSS has `color: red` but the PostCSS plugin transforms it to green. // The CSS has `color: red` but the PostCSS plugin transforms it to green.
// If this is green, it proves the TypeScript PostCSS config was loaded and applied. // If this is green, it proves the TypeScript PostCSS config was loaded and applied.
const color = await browser const color = await browser
.elementByCss('#test') .elementByCss('#test')
.getComputedCss('color') .getComputedCss('color')
expect(color).toBe('rgb(0, 128, 0)') expect(color).toBe('rgb(0, 128, 0)')
} finally { } finally {
await browser.close() await browser.close()
} }
})
}) })
})
describe('.postcssrc.ts', () => { describe('.postcssrc.ts', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: new FileRef(join(__dirname, 'postcssrc')), files: new FileRef(join(__dirname, 'postcssrc')),
}) })
it('works with .postcssrc.ts files', async () => { it('works with .postcssrc.ts files', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
try { try {
const text = await browser.elementByCss('#test').text() const text = await browser.elementByCss('#test').text()
expect(text).toBe('Hello World') expect(text).toBe('Hello World')
// The CSS has `color: red` but the PostCSS plugin transforms it to green. // The CSS has `color: red` but the PostCSS plugin transforms it to green.
// If this is green, it proves the TypeScript PostCSS config was loaded and applied. // If this is green, it proves the TypeScript PostCSS config was loaded and applied.
const color = await browser const color = await browser
.elementByCss('#test') .elementByCss('#test')
.getComputedCss('color') .getComputedCss('color')
expect(color).toBe('rgb(0, 128, 0)') expect(color).toBe('rgb(0, 128, 0)')
} finally { } finally {
await browser.close() await browser.close()
} }
})
}) })
})
describe('postcss.config.mts', () => { describe('postcss.config.mts', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: new FileRef(join(__dirname, 'postcss-config-mts')), files: new FileRef(join(__dirname, 'postcss-config-mts')),
}) })
it('works with postcss.config.mts files', async () => { it('works with postcss.config.mts files', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
try { try {
const text = await browser.elementByCss('#test').text() const text = await browser.elementByCss('#test').text()
expect(text).toBe('Hello World') expect(text).toBe('Hello World')
// The CSS has `color: red` but the PostCSS plugin transforms it to green. // The CSS has `color: red` but the PostCSS plugin transforms it to green.
// If this is green, it proves the TypeScript PostCSS config was loaded and applied. // If this is green, it proves the TypeScript PostCSS config was loaded and applied.
const color = await browser const color = await browser
.elementByCss('#test') .elementByCss('#test')
.getComputedCss('color') .getComputedCss('color')
expect(color).toBe('rgb(0, 128, 0)') expect(color).toBe('rgb(0, 128, 0)')
} finally { } finally {
await browser.close() await browser.close()
} }
})
}) })
})
describe('postcss.config.cts', () => { describe('postcss.config.cts', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: new FileRef(join(__dirname, 'postcss-config-cts')), files: new FileRef(join(__dirname, 'postcss-config-cts')),
}) })
it('works with postcss.config.cts files', async () => { it('works with postcss.config.cts files', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
try { try {
const text = await browser.elementByCss('#test').text() const text = await browser.elementByCss('#test').text()
expect(text).toBe('Hello World') expect(text).toBe('Hello World')
// The CSS has `color: red` but the PostCSS plugin transforms it to green. // The CSS has `color: red` but the PostCSS plugin transforms it to green.
// If this is green, it proves the TypeScript PostCSS config was loaded and applied. // If this is green, it proves the TypeScript PostCSS config was loaded and applied.
const color = await browser const color = await browser
.elementByCss('#test') .elementByCss('#test')
.getComputedCss('color') .getComputedCss('color')
expect(color).toBe('rgb(0, 128, 0)') expect(color).toBe('rgb(0, 128, 0)')
} finally { } finally {
await browser.close() await browser.close()
} }
})
}) })
} })
) })
...@@ -8,7 +8,7 @@ import { RouteKind } from 'next/dist/server/route-kind' ...@@ -8,7 +8,7 @@ import { RouteKind } from 'next/dist/server/route-kind'
// Assertions don't apply to deploy mode (output differs vs. local Next.js server). // Assertions don't apply to deploy mode (output differs vs. local Next.js server).
// @force-gate !deploy // @force-gate !deploy
describe('Fallback path encoding', () => { describe('Fallback path encoding', () => {
const { next, isNextDev, isNextStart } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
...@@ -44,119 +44,119 @@ describe('Fallback path encoding', () => { ...@@ -44,119 +44,119 @@ describe('Fallback path encoding', () => {
const modePaths = ['fallback-blocking', 'fallback-false', 'fallback-true'] const modePaths = ['fallback-blocking', 'fallback-false', 'fallback-true']
if (isNextStart) { // Inspects files produced by the local production build.
it('should output paths correctly', async () => { // @force-gate start
const pagesDir = join(next.testDir, '.next/server/pages') it('should output paths correctly', async () => {
for (const path of prerenderedPaths) { const pagesDir = join(next.testDir, '.next/server/pages')
for (const mode of modePaths) { for (const path of prerenderedPaths) {
expect(fs.existsSync(join(pagesDir, mode, path + '.html'))).toBe(true) for (const mode of modePaths) {
expect(fs.existsSync(join(pagesDir, mode, path + '.json'))).toBe(true) expect(fs.existsSync(join(pagesDir, mode, path + '.html'))).toBe(true)
} expect(fs.existsSync(join(pagesDir, mode, path + '.json'))).toBe(true)
} }
}) }
} })
if (isNextStart) {
it('should handle non-prerendered paths correctly', async () => {
const newUrlPaths = [
'%2Fanother-post%2F',
'%2Banother-post%2B',
'%3Fanother-post%3F',
'%26another-post%26',
encodeURIComponent('商業日語商業日語'),
]
const newPrerenderedPaths = [
'%2Fanother-post%2F',
'+another-post+',
'%3Fanother-post%3F',
'&another-post&',
'商業日語商業日語',
]
for (const mode of modePaths) { // Checks the local ISR artifacts written for fallback requests.
for (let i = 0; i < newUrlPaths.length; i++) { // @force-gate start
const testSlug = newUrlPaths[i] it('should handle non-prerendered paths correctly', async () => {
const newUrlPaths = [
'%2Fanother-post%2F',
'%2Banother-post%2B',
'%3Fanother-post%3F',
'%26another-post%26',
encodeURIComponent('商業日語商業日語'),
]
const newPrerenderedPaths = [
'%2Fanother-post%2F',
'+another-post+',
'%3Fanother-post%3F',
'&another-post&',
'商業日語商業日語',
]
const res = await next.fetch( for (const mode of modePaths) {
`/_next/data/${next.buildId}/${mode}/${testSlug}.json` for (let i = 0; i < newUrlPaths.length; i++) {
) const testSlug = newUrlPaths[i]
const res = await next.fetch(
`/_next/data/${next.buildId}/${mode}/${testSlug}.json`
)
if (mode === 'fallback-false') {
expect(res.status).toBe(404)
} else {
expect(res.status).toBe(200)
const { pageProps: props } = await res.json()
expect(props.params).toEqual({
slug: decodeURIComponent(testSlug),
})
if (mode === 'fallback-false') { const prerenderedPath = newPrerenderedPaths[i]
expect(res.status).toBe(404) await retry(async () => {
} else { expect(
expect(res.status).toBe(200) fs.existsSync(
join(
const { pageProps: props } = await res.json() next.testDir,
next.getPrerenderFilePath(
expect(props.params).toEqual({ `/${mode}/${prerenderedPath}`,
slug: decodeURIComponent(testSlug), '.html',
}) {
router: 'pages',
const prerenderedPath = newPrerenderedPaths[i] route: {
await retry(async () => { kind: RouteKind.PAGES,
expect( sourceRoute: `/${mode}/[slug]`,
fs.existsSync( },
join( }
next.testDir,
next.getPrerenderFilePath(
`/${mode}/${prerenderedPath}`,
'.html',
{
router: 'pages',
route: {
kind: RouteKind.PAGES,
sourceRoute: `/${mode}/[slug]`,
},
}
)
) )
) )
).toBe(true) )
}) ).toBe(true)
await retry(async () => { })
expect( await retry(async () => {
fs.existsSync( expect(
join( fs.existsSync(
next.testDir, join(
next.getPrerenderFilePath( next.testDir,
`/${mode}/${prerenderedPath}`, next.getPrerenderFilePath(
'.json', `/${mode}/${prerenderedPath}`,
{ '.json',
router: 'pages', {
route: { router: 'pages',
kind: RouteKind.PAGES, route: {
sourceRoute: `/${mode}/[slug]`, kind: RouteKind.PAGES,
}, sourceRoute: `/${mode}/[slug]`,
} },
) }
) )
) )
).toBe(true) )
}) ).toBe(true)
})
const browser = await next.browser(`/${mode}/${testSlug}`) const browser = await next.browser(`/${mode}/${testSlug}`)
expect( expect(
JSON.parse(await browser.elementByCss('#props').text()).params JSON.parse(await browser.elementByCss('#props').text()).params
).toEqual({ ).toEqual({
slug: decodeURIComponent(testSlug), slug: decodeURIComponent(testSlug),
}) })
const browserRouter = JSON.parse( const browserRouter = JSON.parse(
await browser.elementByCss('#router').text() await browser.elementByCss('#router').text()
) )
expect(browserRouter.pathname).toBe(`/${mode}/[slug]`) expect(browserRouter.pathname).toBe(`/${mode}/[slug]`)
expect(browserRouter.asPath).toBe(`/${mode}/${testSlug}`) expect(browserRouter.asPath).toBe(`/${mode}/${testSlug}`)
expect(browserRouter.query).toEqual({ expect(browserRouter.query).toEqual({
slug: decodeURIComponent(testSlug), slug: decodeURIComponent(testSlug),
}) })
}
} }
} }
}) }
} })
it('should respond with the prerendered pages correctly', async () => { it('should respond with the prerendered pages correctly', async () => {
for (let i = 0; i < urlPaths.length; i++) { for (let i = 0; i < urlPaths.length; i++) {
......
This diff is collapsed.
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { gate, retry } from 'next-test-utils'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
const strictRouteTypes =
process.env.__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES === 'true'
// Deploy mode exclusion: This suite reads local build artifacts that deployments do not expose. // Deploy mode exclusion: This suite reads local build artifacts that deployments do not expose.
// This test is skipped because it relies on `next.readFile` // This test is skipped because it relies on `next.readFile`
// @force-gate !deploy // @force-gate !deploy
...@@ -39,7 +36,7 @@ describe('tsconfig module: preserve', () => { ...@@ -39,7 +36,7 @@ describe('tsconfig module: preserve', () => {
expect(output).not.toContain('esModuleInterop') expect(output).not.toContain('esModuleInterop')
expect(output).not.toContain('resolveJsonModule') expect(output).not.toContain('resolveJsonModule')
if (strictRouteTypes) { if (await gate('strictRouteTypes')) {
expect(await next.readFile('tsconfig.json')).toMatchInlineSnapshot(` expect(await next.readFile('tsconfig.json')).toMatchInlineSnapshot(`
"{ "{
"compilerOptions": { "compilerOptions": {
......
...@@ -6,12 +6,13 @@ import { retry } from 'next-test-utils' ...@@ -6,12 +6,13 @@ import { retry } from 'next-test-utils'
// process over a local TCP socket. When connecting to that local port is // process over a local TCP socket. When connecting to that local port is
// denied (e.g. a sandbox without a usable loopback interface), the build should // denied (e.g. a sandbox without a usable loopback interface), the build should
// fail with an actionable diagnostic rather than an internal compiler error. // fail with an actionable diagnostic rather than an internal compiler error.
// The preload denies connections in a local child process, not a deployment.
// @force-gate !deploy
// @force-gate turbopack // @force-gate turbopack
describe('turbopack css node process connect failure', () => { describe('turbopack css node process connect failure', () => {
const { next, isNextDev } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
files: path.join(__dirname, 'fixture'), files: path.join(__dirname, 'fixture'),
skipStart: true, skipStart: true,
skipDeployment: true,
}) })
it('reports an actionable error when the CSS side process cannot use a local port', async () => { it('reports an actionable error when the CSS side process cannot use a local port', async () => {
......
...@@ -5,49 +5,48 @@ const jsContent = `export const nope = 'nope' ...@@ -5,49 +5,48 @@ const jsContent = `export const nope = 'nope'
throw new Error('please dont execute me') throw new Error('please dont execute me')
` `
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)( // Import attributes for text/bytes require Turbopack.
'turbopack-import-with-type', // @force-gate turbopack
() => { describe('turbopack-import-with-type', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
// Testing this together on one route ensures we also avoid weird duplicate module ident things // Testing this together on one route ensures we also avoid weird duplicate module ident things
it('supports import with type: text, type: bytes, and type: json', async () => { it('supports import with type: text, type: bytes, and type: json', async () => {
const response = JSON.parse(await next.render('/api')) const response = JSON.parse(await next.render('/api'))
expect(response).toEqual({ expect(response).toEqual({
text: { text: {
typeofString: true, typeofString: true,
length: 12, length: 12,
content: 'hello world\n', content: 'hello world\n',
}, },
jsAsText: { jsAsText: {
typeofString: true, typeofString: true,
content: jsContent, content: jsContent,
}, },
bytes: { bytes: {
instanceofUint8Array: true, instanceofUint8Array: true,
length: 18, length: 18,
content: 'this is some data\n', content: 'this is some data\n',
}, },
jsAsBytes: { jsAsBytes: {
instanceofUint8Array: true, instanceofUint8Array: true,
content: jsContent, content: jsContent,
}, },
configuredAsJsAsBytes: { configuredAsJsAsBytes: {
instanceofUint8Array: true, instanceofUint8Array: true,
content: content:
"throw new Error('this file is configured as ecmascript but imported as bytes')\n", "throw new Error('this file is configured as ecmascript but imported as bytes')\n",
}, },
json: { json: {
typeofObject: true, typeofObject: true,
content: { hello: 'world' }, content: { hello: 'world' },
}, },
jsonAsText: { jsonAsText: {
typeofString: true, typeofString: true,
content: '{ "hello": "world" }\n', content: '{ "hello": "world" }\n',
}, },
})
}) })
} })
) })
import { runTests } from './utils' import { runTests } from './utils'
// Skip in Turbopack as Yarn PnP is not supported. // Skip in Turbopack as Yarn PnP is not supported.
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)('yarn PnP', () => { // @force-gate !turbopack
describe('yarn PnP', () => {
runTests('mdx-pages', '/', ['Look, a button', 'Hello']) runTests('mdx-pages', '/', ['Look, a button', 'Hello'])
}) })
...@@ -119,6 +119,10 @@ export const conditions: Record<string, Condition> = { ...@@ -119,6 +119,10 @@ export const conditions: Record<string, Condition> = {
'links prefetch — disabled in dev, the usual reason a suite skips it', 'links prefetch — disabled in dev, the usual reason a suite skips it',
() => getGateTestContext().mode !== 'dev' () => getGateTestContext().mode !== 'dev'
), ),
prerelease: staticCondition(
'the installed Next.js version is a prerelease',
() => require('next/package.json').version.includes('-')
),
bundler: staticCondition( bundler: staticCondition(
"the bundler under test: 'turbopack' | 'rspack' | 'webpack'", "the bundler under test: 'turbopack' | 'rspack' | 'webpack'",
...@@ -193,6 +197,10 @@ export const conditions: Record<string, Condition> = { ...@@ -193,6 +197,10 @@ export const conditions: Record<string, Condition> = {
'Cache Components are enabled for the fixture', 'Cache Components are enabled for the fixture',
(config) => config.cacheComponents (config) => config.cacheComponents
), ),
strictRouteTypes: lazyCondition(
'strict route type validation is enabled for the fixture',
(config) => config.experimental?.strictRouteTypes
),
partialPrefetchingGlobal: lazyCondition( partialPrefetchingGlobal: lazyCondition(
'Partial Prefetching is enabled globally for the fixture (does not check `export const prefetch = "partial"`)', 'Partial Prefetching is enabled globally for the fixture (does not check `export const prefetch = "partial"`)',
(config) => config.partialPrefetching (config) => config.partialPrefetching
......
...@@ -151,6 +151,14 @@ describe('@gate runtime', () => { ...@@ -151,6 +151,14 @@ describe('@gate runtime', () => {
}) })
describe('lazy conditions', () => { describe('lazy conditions', () => {
it('reads strict route types from the resolved config', async () => {
fixtureWith({ experimental: { strictRouteTypes: true } })
await expect(gate('strictRouteTypes')).resolves.toBe(true)
fixtureWith({ experimental: { strictRouteTypes: false } })
await expect(gate('strictRouteTypes')).resolves.toBe(false)
})
it('reads the running fixture’s resolved config', async () => { it('reads the running fixture’s resolved config', async () => {
const getResolvedConfig = fixtureWith({ cacheComponents: true }) const getResolvedConfig = fixtureWith({ cacheComponents: true })
// cacheComponents is on, so `!cacheComponents` is false: a passing body // cacheComponents is on, so `!cacheComponents` is false: a passing body
...@@ -263,6 +271,30 @@ describe('@gate runtime', () => { ...@@ -263,6 +271,30 @@ describe('@gate runtime', () => {
}) })
describe('@force-gate', () => { describe('@force-gate', () => {
it('recognizes prerelease and stable Next.js versions at collection', async () => {
const nextPackage = require('next/package.json')
const original = nextPackage.version
const prerelease = parseGate('prerelease', true)
expect(prerelease.needsResolvedConfig).toBe(false)
try {
nextPackage.version = '16.0.0-canary.1'
await expect(
__testing.decideGates([prerelease])
).resolves.toMatchObject({
type: 'run',
})
nextPackage.version = '16.0.0'
await expect(
__testing.decideGates([prerelease])
).resolves.toMatchObject({
type: 'force-pass',
})
} finally {
nextPackage.version = original
}
})
it('accepts a lazy condition, classified for runtime resolution', () => { it('accepts a lazy condition, classified for runtime resolution', () => {
const gate = parseGate('!cacheComponents', true) const gate = parseGate('!cacheComponents', true)
expect(gate.force).toBe(true) expect(gate.force).toBe(true)
......
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