Unverified Commit 7da98e13 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Convert more tests from createNext -> nextTestSetup (#93799)

## What?

Converts more tests that use `createNext` to `nextTestSetup`

Follow-up to #93767

---------
Co-authored-by: 's avatarCursor <cursoragent@cursor.com>
parent 247bd079
......@@ -105,12 +105,12 @@ we attempt to capture traces of the playwright run to make debugging the failure
A test-trace artifact should be uploaded after the workflow completes which can be downloaded, unzipped,
and then inspected with `pnpm playwright show-trace ./path/to/trace`
To attach the chrome debugger to next the easiest approach is to modify the `createNext` call in your test to pass `--inspect` to next.
To attach the chrome debugger to next the easiest approach is to modify the `nextTestSetup` call in your test to pass `--inspect` to next.
```js
const next = await createNext({
const { next } = nextTestSetup({
...
startArgs: =['--inspect'],
startArgs: ['--inspect'],
})
```
......
import { createNext } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { spawn } from 'child_process'
import { findPort, killApp, retry } from 'next-test-utils'
import webdriver from 'next-webdriver'
import { join } from 'path'
import {
resolveNextTgzFilename,
......@@ -35,18 +36,64 @@ describe('create-next-app default template', () => {
expect(exitCode).toBe(0)
const nextBin = 'node_modules/next/dist/bin/next'
const next = await createNext({
files: join(cwd, projectName),
installCommand: 'true',
skipStart: false,
startCommand: `node ${nextBin} dev`,
startServerTimeout: 60_000,
})
let browser: Awaited<ReturnType<typeof next.browser>> | undefined
const dir = join(cwd, projectName)
const nextBin = join(dir, 'node_modules/next/dist/bin/next')
const port = await findPort()
const server = spawn(
'node',
[nextBin, 'dev', '-p', String(port), '-H', '127.0.0.1'],
{
cwd: dir,
env: { ...process.env, HOSTNAME: '127.0.0.1' },
stdio: ['ignore', 'pipe', 'pipe'],
}
)
// Freshly installed CNA projects (with tailwind, eslint plugins, etc.)
// can take well over the default 10s to boot `next dev`. Give them
// generous headroom so this test isn't flaky on loaded CI machines.
const startServerTimeout = 60_000
let browser: Awaited<ReturnType<typeof webdriver>> | undefined
try {
browser = await next.browser('/')
await new Promise<void>((resolve, reject) => {
const onTimeout = setTimeout(() => {
reject(
new Error(
`next dev did not become ready within ${startServerTimeout}ms`
)
)
}, startServerTimeout)
const onReady = () => {
clearTimeout(onTimeout)
resolve()
}
const handleData = (chunk: Buffer) => {
const msg = chunk.toString()
process.stdout.write(msg)
if (/- Local:|Ready in|✓ Ready/i.test(msg)) {
onReady()
}
}
server.stdout!.on('data', handleData)
server.stderr!.on('data', (chunk: Buffer) => {
process.stderr.write(chunk.toString())
})
server.on('exit', (code) => {
clearTimeout(onTimeout)
reject(
new Error(
`next dev exited before becoming ready (code=${code})`
)
)
})
})
browser = await webdriver(port, '/')
const page = browser
expect(await page.elementByCss('body').text()).toContain('Deploy Now')
......@@ -59,13 +106,22 @@ describe('create-next-app default template', () => {
expect(imagesReady).toBe(true)
})
// In dev, the browser may fire a "preloaded using link preload but
// not used within a few seconds from the window's load event"
// warning for next/font's woff2 files when the stylesheet that
// references them hasn't been applied by the time the browser's
// internal timer fires (relative to window.load). The font is in
// fact used moments later, so this is a benign timing race that
// doesn't reproduce reliably — filter it out.
const messages = (await page.log()).filter(
(log) => log.source === 'warning' || log.source === 'error'
(log) =>
(log.source === 'warning' || log.source === 'error') &&
!/was preloaded using link preload but not used/.test(log.message)
)
expect(messages).toEqual([])
} finally {
await browser?.close()
await next.destroy()
await killApp(server).catch(() => {})
}
})
},
......
import { createNext } from 'e2e-utils'
import { findPort, retry } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('app-dir assetPrefix full URL', () => {
let next, forcedPort
beforeAll(async () => {
forcedPort = ((await findPort()) ?? '54321').toString()
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
forcedPort: 'random',
})
next = await createNext({
files: __dirname,
forcedPort,
nextConfig: {
assetPrefix: `http://localhost:${forcedPort}`,
},
})
beforeAll(async () => {
const port = next.forcedPort
await next.patchFile(
'next.config.js',
`module.exports = { assetPrefix: 'http://localhost:${port}' }`
)
await next.start()
})
afterAll(() => next.destroy())
it('should not break HMR when asset prefix set to full URL', async () => {
const browser = await next.browser('/')
......
import { FileRef, nextTestSetup, createNext } from 'e2e-utils'
import { FileRef, nextTestSetup } from 'e2e-utils'
import { retry, waitFor } from 'next-test-utils'
import path from 'path'
......@@ -6,6 +6,7 @@ describe('app-dir server restart', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
patchFileDelay: 1000,
forcedPort: 'random',
})
it('should reload the page when the server restarts', async () => {
......@@ -34,15 +35,11 @@ describe('app-dir server restart', () => {
})
})
const appPort = next.appPort
await next.destroy()
await next.stop()
// Start a new server instance on the same port
const secondNext = await createNext({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
env: next.env,
forcedPort: appPort,
})
// Start a new server instance on the same port (forcedPort: 'random' was
// resolved to a concrete port in setup() so next.start() reuses it).
await next.start()
// Wait for the new server to be ready
await waitFor(1000)
......@@ -60,7 +57,5 @@ describe('app-dir server restart', () => {
await retry(async () => {
expect(await browser.elementById('counter-value').text()).toBe('Count: 0')
})
await secondNext.destroy()
})
})
......@@ -4,7 +4,7 @@ import {
retry,
waitFor,
} from 'next-test-utils'
import { createNext, nextTestSetup } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
export function runBasicHmrTest(nextConfig: {
basePath: string
......@@ -14,6 +14,7 @@ export function runBasicHmrTest(nextConfig: {
files: __dirname,
nextConfig,
patchFileDelay: 500,
forcedPort: 'random',
})
const { basePath } = nextConfig
......@@ -90,7 +91,7 @@ export function runBasicHmrTest(nextConfig: {
)
})
await next.destroy()
await next.stop()
let reloadPromise = new Promise((resolve) => {
browser.on('request', (req) => {
......@@ -100,13 +101,8 @@ export function runBasicHmrTest(nextConfig: {
})
})
const secondNext = await createNext({
files: __dirname,
nextConfig,
forcedPort: next.appPort,
})
await next.start()
await reloadPromise
await secondNext.destroy()
})
}
import { NextInstance, createNext } from 'e2e-utils'
import { trace } from 'next/dist/trace'
import { nextTestSetup } from 'e2e-utils'
import { PHASE_DEVELOPMENT_SERVER } from 'next/constants'
import { createDefineEnv, loadBindings, HmrTarget } from 'next/dist/build/swc'
import type {
......@@ -121,39 +120,33 @@ export default () => <div>${text}<Client /></div>;`
}
describe('next.rs api writeToDisk multiple times', () => {
let next: NextInstance
afterEach(async () => {
await next?.destroy()
})
it('should allow to write to disk multiple times', async () => {
next = await createNext({
skipStart: true,
files: {
'pages/index.js': pagesIndexCode('hello world'),
'lib/props.js': 'export default {}',
'pages/page-nodejs.js': 'export default () => <div>hello world</div>',
'pages/page-edge.js':
'export default () => <div>hello world</div>\nexport const config = { runtime: "experimental-edge" }',
'pages/api/nodejs.js':
'export default () => Response.json({ hello: "world" })',
'pages/api/edge.js':
'export default () => Response.json({ hello: "world" })\nexport const config = { runtime: "edge" }',
'app/layout.tsx':
'export default function RootLayout({ children }: { children: any }) { return (<html><body>{children}</body></html>)}',
'app/loading.tsx':
'export default function Loading() { return <>Loading</> }',
'app/app/page.tsx': appPageCode('hello world'),
'app/app/client.tsx':
'"use client";\nexport default () => <div>hello world</div>',
'app/app-edge/page.tsx':
'export default () => <div>hello world</div>\nexport const runtime = "edge"',
'app/app-nodejs/page.tsx':
'export default () => <div>hello world</div>',
'app/route-nodejs/route.ts':
'export function GET() { return Response.json({ hello: "world" }) }',
'app/route-edge/route.ts':
'export function GET() { return Response.json({ hello: "world" }) }\nexport const runtime = "edge"',
'server.js': `
const { next } = nextTestSetup({
skipStart: true,
files: {
'pages/index.js': pagesIndexCode('hello world'),
'lib/props.js': 'export default {}',
'pages/page-nodejs.js': 'export default () => <div>hello world</div>',
'pages/page-edge.js':
'export default () => <div>hello world</div>\nexport const config = { runtime: "experimental-edge" }',
'pages/api/nodejs.js':
'export default () => Response.json({ hello: "world" })',
'pages/api/edge.js':
'export default () => Response.json({ hello: "world" })\nexport const config = { runtime: "edge" }',
'app/layout.tsx':
'export default function RootLayout({ children }: { children: any }) { return (<html><body>{children}</body></html>)}',
'app/loading.tsx':
'export default function Loading() { return <>Loading</> }',
'app/app/page.tsx': appPageCode('hello world'),
'app/app/client.tsx':
'"use client";\nexport default () => <div>hello world</div>',
'app/app-edge/page.tsx':
'export default () => <div>hello world</div>\nexport const runtime = "edge"',
'app/app-nodejs/page.tsx': 'export default () => <div>hello world</div>',
'app/route-nodejs/route.ts':
'export function GET() { return Response.json({ hello: "world" }) }',
'app/route-edge/route.ts':
'export function GET() { return Response.json({ hello: "world" }) }\nexport const runtime = "edge"',
'server.js': `
process.title = 'next.rs api run test';
const path = require('path');
const { PHASE_DEVELOPMENT_SERVER } = require('next/constants');
......@@ -263,9 +256,10 @@ main()
});
`,
},
})
},
})
it('should allow to write to disk multiple times', async () => {
const result = spawnSync(
'node',
['--expose-gc', join(next.testDir, 'server.js')],
......@@ -281,41 +275,34 @@ main()
})
describe('next.rs api', () => {
let next: NextInstance
beforeAll(async () => {
await trace('setup next instance').traceAsyncFn(async (rootSpan) => {
next = await createNext({
skipStart: true,
files: {
'pages/index.js': pagesIndexCode('hello world'),
'lib/props.js': 'export default {}',
'pages/page-nodejs.js': 'export default () => <div>hello world</div>',
'pages/page-edge.js':
'export default () => <div>hello world</div>\nexport const config = { runtime: "experimental-edge" }',
'pages/api/nodejs.js':
'export default () => Response.json({ hello: "world" })',
'pages/api/edge.js':
'export default () => Response.json({ hello: "world" })\nexport const config = { runtime: "edge" }',
'app/layout.tsx':
'export default function RootLayout({ children }: { children: any }) { return (<html><body>{children}</body></html>)}',
'app/loading.tsx':
'export default function Loading() { return <>Loading</> }',
'app/app/page.tsx': appPageCode('hello world'),
'app/app/client.tsx':
'"use client";\nexport default () => <div>hello world</div>',
'app/app-edge/page.tsx':
'export default () => <div>hello world</div>\nexport const runtime = "edge"',
'app/app-nodejs/page.tsx':
'export default () => <div>hello world</div>',
'app/route-nodejs/route.ts':
'export function GET() { return Response.json({ hello: "world" }) }',
'app/route-edge/route.ts':
'export function GET() { return Response.json({ hello: "world" }) }\nexport const runtime = "edge"',
},
})
})
const { next } = nextTestSetup({
skipStart: true,
files: {
'pages/index.js': pagesIndexCode('hello world'),
'lib/props.js': 'export default {}',
'pages/page-nodejs.js': 'export default () => <div>hello world</div>',
'pages/page-edge.js':
'export default () => <div>hello world</div>\nexport const config = { runtime: "experimental-edge" }',
'pages/api/nodejs.js':
'export default () => Response.json({ hello: "world" })',
'pages/api/edge.js':
'export default () => Response.json({ hello: "world" })\nexport const config = { runtime: "edge" }',
'app/layout.tsx':
'export default function RootLayout({ children }: { children: any }) { return (<html><body>{children}</body></html>)}',
'app/loading.tsx':
'export default function Loading() { return <>Loading</> }',
'app/app/page.tsx': appPageCode('hello world'),
'app/app/client.tsx':
'"use client";\nexport default () => <div>hello world</div>',
'app/app-edge/page.tsx':
'export default () => <div>hello world</div>\nexport const runtime = "edge"',
'app/app-nodejs/page.tsx': 'export default () => <div>hello world</div>',
'app/route-nodejs/route.ts':
'export function GET() { return Response.json({ hello: "world" }) }',
'app/route-edge/route.ts':
'export function GET() { return Response.json({ hello: "world" }) }\nexport const runtime = "edge"',
},
})
afterAll(() => next.destroy())
let project: Project
let projectUpdateSubscription: AsyncIterableIterator<UpdateInfo>
......
import fs from 'fs-extra'
import webdriver from 'next-webdriver'
import { waitForNoRedbox, check, findPort } from 'next-test-utils'
import { NextInstance } from 'e2e-utils'
import { createNext } from 'e2e-utils'
import { waitForNoRedbox, check } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils'
import stripAnsi from 'strip-ansi'
// TODO: investigate occasional failure
describe.skip('Project Directory Renaming', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
'pages/index.js': `
const { next } = nextTestSetup({
files: {
'pages/index.js': `
export default function Page() {
return <p>hello world</p>
}
`,
},
skipStart: true,
forcedPort: (await findPort()) + '',
})
},
skipStart: true,
forcedPort: 'random',
})
beforeAll(async () => {
await next.start()
})
afterAll(() => next.destroy().catch(() => {}))
it('should detect project dir rename and restart', async () => {
const browser = await webdriver(next.url, '/')
......
import { createNext } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
describe('next start without next build', () => {
it('should show error when there is no production build', async () => {
const next = await createNext({
files: __dirname,
skipStart: true,
startCommand: `pnpm next start`,
serverReadyPattern: /Local:/,
})
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
startCommand: `pnpm next start`,
serverReadyPattern: /Local:/,
})
it('should show error when there is no production build', async () => {
await next.start()
await new Promise<void>((resolve, reject) => {
await new Promise<void>((resolve) => {
next.on('stderr', (msg) => {
if (msg.includes('Could not find a production build in the')) {
resolve()
}
})
})
await next.destroy()
})
})
import path from 'path'
import { createNext, FileRef, nextTestSetup } from 'e2e-utils'
import { FileRef, nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
......@@ -202,24 +202,23 @@ import stripAnsi from 'strip-ansi'
})
} else {
describe('build', () => {
it('should break the build if a page is missing root layout', async () => {
const next = await createNext({
skipStart: true,
files: {
'app/page.js': new FileRef(
path.join(__dirname, 'app/route/page.js')
),
'next.config.js': new FileRef(
path.join(__dirname, 'next.config.js')
),
},
})
const { next } = nextTestSetup({
skipStart: true,
files: {
'app/page.js': new FileRef(
path.join(__dirname, 'app/route/page.js')
),
'next.config.js': new FileRef(
path.join(__dirname, 'next.config.js')
),
},
})
it('should break the build if a page is missing root layout', async () => {
await expect(next.start()).rejects.toThrow('next build failed')
expect(stripAnsi(next.cliOutput)).toInclude(
"page.js doesn't have a root layout. To fix this error, make sure every page has a root layout."
)
await next.destroy()
})
})
}
......
import { createNext } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { findPort } from 'next-test-utils'
import { createTestDataServer } from 'test-data-service/writer'
import { createTestLog } from 'test-log'
......@@ -11,10 +11,13 @@ describe('avoid-popstate-flash', () => {
return
}
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
let server
let next
afterEach(async () => {
await next?.destroy()
afterEach(() => {
server?.close()
})
......@@ -35,10 +38,8 @@ describe('avoid-popstate-flash', () => {
})
const port = await findPort()
server.listen(port)
next = await createNext({
files: __dirname,
env: { TEST_DATA_SERVICE_URL: `http://localhost:${port}` },
})
next.env.TEST_DATA_SERVICE_URL = `http://localhost:${port}`
await next.start()
TestLog.assert(['REQUEST: Static'])
autoresolveRequests = false
......
import { createNext } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
// TODO(NAR-423): Migrate to Cache Components.
describe.skip('search-params', () => {
......@@ -7,20 +7,14 @@ describe.skip('search-params', () => {
return
}
let server
let next
afterEach(async () => {
await next?.destroy()
server?.close()
const { next } = nextTestSetup({
files: __dirname,
})
test(
'updates page data during a nav even if no shared layouts have changed ' +
'(e.g. updating a search param on the current page)',
async () => {
next = await createNext({
files: __dirname,
})
const browser = await next.browser('/')
// Click a link that updates the current page's search params.
......
import { createNext } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { findPort } from 'next-test-utils'
import { createTestDataServer } from 'test-data-service/writer'
import { createTestLog } from 'test-log'
......@@ -11,10 +11,13 @@ describe('stale-prefetch-entry', () => {
return
}
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
let server
let next
afterEach(async () => {
await next?.destroy()
afterEach(() => {
server?.close()
})
......@@ -42,10 +45,8 @@ describe('stale-prefetch-entry', () => {
})
const port = await findPort()
server.listen(port)
next = await createNext({
files: __dirname,
env: { TEST_DATA_SERVICE_URL: `http://localhost:${port}` },
})
next.env.TEST_DATA_SERVICE_URL = `http://localhost:${port}`
await next.start()
TestLog.assert(['REQUEST: Some data [static]'])
autoresolveRequests = false
......
import { NextInstance, createNext, isNextDeploy, isNextDev } from 'e2e-utils'
import { nextTestSetup, isNextDeploy, isNextDev } from 'e2e-utils'
import { findPort } from 'next-test-utils'
import http from 'node:http'
......@@ -13,14 +13,13 @@ describe('ppr-unstable-cache', () => {
return
}
let next: NextInstance | null = null
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
let server: http.Server | null = null
afterEach(async () => {
if (next) {
await next.destroy()
next = null
}
if (server) {
await server.close()
server = null
......@@ -48,10 +47,8 @@ describe('ppr-unstable-cache', () => {
const port = await findPort()
server.listen(port)
next = await createNext({
files: __dirname,
env: { TEST_DATA_SERVER: `http://localhost:${port}/` },
})
next.env.TEST_DATA_SERVER = `http://localhost:${port}/`
await next.start()
expect(generations).toHaveLength(2)
......
import type * as Playwright from 'playwright'
import { isNextDev, isNextDeploy, createNext } from 'e2e-utils'
import { isNextDev, isNextDeploy, nextTestSetup } from 'e2e-utils'
import { createRouterAct } from 'router-act'
import { createTestDataServer } from 'test-data-service/writer'
import { createTestLog } from 'test-log'
......@@ -16,7 +16,11 @@ describe('segment cache (revalidation)', () => {
let dataVersions = new Map()
let TestLog = createTestLog()
let next
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
beforeAll(async () => {
port = await findPort()
server = createTestDataServer(async (key, res) => {
......@@ -34,10 +38,8 @@ describe('segment cache (revalidation)', () => {
})
server.listen(port)
next = await createNext({
files: __dirname,
env: { TEST_DATA_SERVICE_URL: `http://localhost:${port}` },
})
next.env.TEST_DATA_SERVICE_URL = `http://localhost:${port}`
await next.start()
})
beforeEach(async () => {
......@@ -46,7 +48,6 @@ describe('segment cache (revalidation)', () => {
})
afterAll(async () => {
await next?.destroy()
server?.close()
})
......
import { FileRef, createNext, NextInstance } from 'e2e-utils'
import { FileRef, nextTestSetup } from 'e2e-utils'
import { findPort, renderViaHTTP, fetchViaHTTP } from 'next-test-utils'
import { join } from 'path'
import spawn from 'cross-spawn'
describe('next/font/google with proxy', () => {
let next: NextInstance
let proxy: any
let PROXY_PORT: number
let SERVER_PORT: number
if ((global as any).isNextDeploy) {
it('should skip next deploy', () => {})
return
}
const { next } = nextTestSetup({
files: new FileRef(join(__dirname, 'with-proxy')),
skipStart: true,
})
let proxy: any
let SERVER_PORT: number
beforeAll(async () => {
PROXY_PORT = await findPort()
const PROXY_PORT = await findPort()
SERVER_PORT = await findPort()
proxy = spawn('node', [require.resolve('./with-proxy/server.js')], {
......@@ -27,16 +30,12 @@ describe('next/font/google with proxy', () => {
},
})
next = await createNext({
files: new FileRef(join(__dirname, 'with-proxy')),
env: {
http_proxy: 'http://localhost:' + PROXY_PORT,
},
await next.start({
env: { http_proxy: 'http://localhost:' + PROXY_PORT },
})
})
afterAll(async () => {
await next.destroy()
proxy.kill('SIGKILL')
afterAll(() => {
proxy?.kill('SIGKILL')
})
// Reqwest doesn't seem to fully work with https proxy
......
import webdriver, { Playwright } from 'next-webdriver'
import { createNext, nextTestSetup } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
describe('beforeInteractive in document Head', () => {
......@@ -321,28 +320,8 @@ describe('empty strategy in document body', () => {
})
})
describe('experimental.nextScriptWorkers: true with required Partytown dependency for inline script', () => {
let next: NextInstance
// Note: previously we were using `finally` cluase inside of test assertion. However, if the test times out
// exceeding jest.setTimeout() value, the finally clause is not executed and subsequent tests will fail due to
// hanging next instance.
afterEach(async () => {
if (next) {
await next.destroy()
next = undefined
}
})
const createNextApp = async (script) =>
await createNext({
nextConfig: {
experimental: {
nextScriptWorkers: true,
},
},
files: {
'pages/index.js': `
function buildInlineScriptPage(script: string) {
return `
import Script from 'next/script'
export default function Page() {
......@@ -353,20 +332,29 @@ describe('empty strategy in document body', () => {
</>
)
}
`,
},
dependencies: {
'@builder.io/partytown': '0.4.2',
`
}
describe('experimental.nextScriptWorkers: true with required Partytown dependency for inline script (children)', () => {
const { next } = nextTestSetup({
nextConfig: {
experimental: {
nextScriptWorkers: true,
},
})
},
files: {
'pages/index.js': buildInlineScriptPage(
`<Script id="inline-script" strategy="worker">{"document.getElementById('text').textContent += 'abc'"}</Script>`
),
},
dependencies: {
'@builder.io/partytown': '0.4.2',
},
})
it('Inline worker script through children is modified by Partytown to execute on a worker thread', async () => {
let browser: Playwright
next = await createNextApp(
`<Script id="inline-script" strategy="worker">{"document.getElementById('text').textContent += 'abc'"}</Script>`
)
try {
browser = await webdriver(next.url, '/')
......@@ -384,14 +372,28 @@ describe('empty strategy in document body', () => {
if (browser) await browser.close()
}
})
})
describe('experimental.nextScriptWorkers: true with required Partytown dependency for inline script (dangerouslySetInnerHTML)', () => {
const { next } = nextTestSetup({
nextConfig: {
experimental: {
nextScriptWorkers: true,
},
},
files: {
'pages/index.js': buildInlineScriptPage(
`<Script id="inline-script" strategy="worker" dangerouslySetInnerHTML={{__html: "document.getElementById('text').textContent += 'abcd'"}}/>`
),
},
dependencies: {
'@builder.io/partytown': '0.4.2',
},
})
it('Inline worker script through dangerouslySetInnerHtml is modified by Partytown to execute on a worker thread', async () => {
let browser: Playwright
next = await createNextApp(
`<Script id="inline-script" strategy="worker" dangerouslySetInnerHTML={{__html: "document.getElementById('text').textContent += 'abcd'"}}/>`
)
try {
browser = await webdriver(next.url, '/')
......
import net from 'net'
import http from 'http'
import { createNext, NextInstance } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { findPort, retry } from 'next-test-utils'
describe('rewrite-request-smuggling', () => {
......@@ -9,11 +9,15 @@ describe('rewrite-request-smuggling', () => {
return
}
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
let backend: http.Server
let backendPort: number
let intermediary: http.Server
let intermediaryPort: number
let next: NextInstance
const backendRequests: string[] = []
async function sendSmugglingPayload({
......@@ -143,16 +147,12 @@ describe('rewrite-request-smuggling', () => {
intermediary.once('error', reject)
})
next = await createNext({
files: __dirname,
env: {
TEST_INTERMEDIARY_PORT: String(intermediaryPort),
},
await next.start({
env: { TEST_INTERMEDIARY_PORT: String(intermediaryPort) },
})
})
afterAll(async () => {
await next?.destroy()
await new Promise<void>((resolve) => intermediary.close(() => resolve()))
await new Promise<void>((resolve) => backend.close(() => resolve()))
})
......
import { join } from 'path'
import { createNext, nextTestSetup } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import {
check,
fetchViaHTTP,
......@@ -85,14 +85,18 @@ describe('streaming SSR with custom next configs', () => {
if (isNextProd) {
describe('streaming SSR with custom server', () => {
let next
const { next } = nextTestSetup({
files: join(__dirname, 'custom-server'),
skipStart: true,
})
let server
let appPort
beforeAll(async () => {
next = await createNext({
files: join(__dirname, 'custom-server'),
})
await next.stop()
const { exitCode } = await next.build()
if (exitCode !== 0) {
throw new Error(`Failed to build next: ${exitCode}`)
}
const testServer = join(next.testDir, 'server.js')
appPort = await findPort()
......@@ -111,7 +115,6 @@ if (isNextProd) {
)
})
afterAll(async () => {
await next.destroy()
if (server) await killApp(server)
})
it('should render page correctly under custom server', async () => {
......
import { createNext, isNextDeploy } from 'e2e-utils'
import type { NextInstance } from 'e2e-utils'
import { findPort, retry } from 'next-test-utils'
import { isNextDeploy, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
// `experimental.turbopackWorkerAssetPrefix` is turbopack-only.
const isTurbopack = !process.env.IS_WEBPACK_TEST
......@@ -10,7 +9,7 @@ const describeTurbopack =
// CORS so cross-origin script tags from `assetPrefix` can be fetched. Workers
// are NOT covered by CORS — `new Worker(crossOriginUrl)` is rejected
// regardless — so this only unblocks regular script loading.
const corsHeaders = () => ({
const corsHeadersConfig = `
async headers() {
return [
{
......@@ -18,8 +17,7 @@ const corsHeaders = () => ({
headers: [{ key: 'Access-Control-Allow-Origin', value: '*' }],
},
]
},
})
},`
/**
* Real cross-origin setup: the page is served at `http://localhost:PORT/`,
......@@ -33,24 +31,26 @@ const corsHeaders = () => ({
*/
describeTurbopack('turbopack-worker-asset-prefix', () => {
describe('without turbopackWorkerAssetPrefix (cross-origin assetPrefix)', () => {
let next: NextInstance
let forcedPort: string
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
forcedPort: 'random',
})
beforeAll(async () => {
forcedPort = String((await findPort()) ?? '54321')
next = await createNext({
files: __dirname,
forcedPort,
nextConfig: {
assetPrefix: `http://127.0.0.1:${forcedPort}`,
...corsHeaders(),
},
})
const port = next.forcedPort
await next.patchFile(
'next.config.js',
`module.exports = {
assetPrefix: 'http://127.0.0.1:${port}',${corsHeadersConfig}
}`
)
await next.start()
})
afterAll(() => next.destroy())
it('Worker URL inherits assetPrefix and the browser rejects construction', async () => {
const browser = await next.browser('/')
const forcedPort = next.forcedPort
await retry(async () => {
const url = await browser.elementByCss('#worker-ctor-url').text()
......@@ -67,29 +67,31 @@ describeTurbopack('turbopack-worker-asset-prefix', () => {
})
describe('with turbopackWorkerAssetPrefix overriding assetPrefix', () => {
let next: NextInstance
let forcedPort: string
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
forcedPort: 'random',
})
beforeAll(async () => {
forcedPort = String((await findPort()) ?? '54322')
next = await createNext({
files: __dirname,
forcedPort,
nextConfig: {
assetPrefix: `http://127.0.0.1:${forcedPort}`,
experimental: {
// Route Worker URLs through the page's own origin
// (`http://localhost:PORT`) instead of the cross-origin assetPrefix.
turbopackWorkerAssetPrefix: `http://localhost:${forcedPort}`,
},
...corsHeaders(),
},
})
const port = next.forcedPort
await next.patchFile(
'next.config.js',
`module.exports = {
assetPrefix: 'http://127.0.0.1:${port}',
experimental: {
// Route Worker URLs through the page's own origin
// ('http://localhost:PORT') instead of the cross-origin assetPrefix.
turbopackWorkerAssetPrefix: 'http://localhost:${port}',
},${corsHeadersConfig}
}`
)
await next.start()
})
afterAll(() => next.destroy())
it('Worker URL uses the override origin and construction succeeds', async () => {
const browser = await next.browser('/')
const forcedPort = next.forcedPort
await retry(async () => {
const pageOrigin = await browser.elementByCss('#page-origin').text()
......@@ -105,30 +107,32 @@ describeTurbopack('turbopack-worker-asset-prefix', () => {
})
describe('with turbopackWorkerAssetPrefix: "" (literal empty prefix)', () => {
let next: NextInstance
let forcedPort: string
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
forcedPort: 'random',
})
beforeAll(async () => {
forcedPort = String((await findPort()) ?? '54323')
next = await createNext({
files: __dirname,
forcedPort,
nextConfig: {
assetPrefix: `http://127.0.0.1:${forcedPort}`,
experimental: {
// Empty string is a literal empty prefix (only `/_next/` is
// appended). It does NOT fall back to assetPrefix — only
// `undefined` does.
turbopackWorkerAssetPrefix: '',
},
...corsHeaders(),
},
})
const port = next.forcedPort
await next.patchFile(
'next.config.js',
`module.exports = {
assetPrefix: 'http://127.0.0.1:${port}',
experimental: {
// Empty string is a literal empty prefix (only '/_next/' is
// appended). It does NOT fall back to assetPrefix — only
// 'undefined' does.
turbopackWorkerAssetPrefix: '',
},${corsHeadersConfig}
}`
)
await next.start()
})
afterAll(() => next.destroy())
it('Worker URL is a relative /_next/ URL (resolved same-origin)', async () => {
const browser = await next.browser('/')
const forcedPort = next.forcedPort
await retry(async () => {
const pageOrigin = await browser.elementByCss('#page-origin').text()
......
......@@ -236,9 +236,12 @@ const setupTracing = () => {
/**
* Sets up and manages a Next.js instance in the configured
* test mode. The next instance will be isolated from the monorepo
* to prevent relying on modules that shouldn't be
* to prevent relying on modules that shouldn't be.
*
* Internal helper used by `nextTestSetup`. Tests should call
* `nextTestSetup` directly instead of `createNext`.
*/
export async function createNext(
async function createNext(
opts: NextInstanceOpts & { skipStart?: boolean; patchFileDelay?: number }
): Promise<NextInstance> {
try {
......
......@@ -371,7 +371,7 @@ export class NextInstance {
if (nextConfigFile && this.nextConfig) {
throw new Error(
`nextConfig provided on "createNext()" and as a file "${nextConfigFile}", use one or the other to continue`
`nextConfig provided on "nextTestSetup()" and as a file "${nextConfigFile}", use one or the other to continue`
)
}
......@@ -750,7 +750,10 @@ export class NextInstance {
}
}
public async start(options?: { skipBuild?: boolean }): Promise<void> {}
public async start(options?: {
skipBuild?: boolean
env?: Record<string, string>
}): Promise<void> {}
public async stop(
signal: 'SIGINT' | 'SIGTERM' | 'SIGKILL' = 'SIGKILL'
......
......@@ -120,7 +120,7 @@ export class NextDevInstance extends NextInstance {
})
}
public async start() {
public async start(options: { env?: Record<string, string> } = {}) {
if (this.childProcess) {
throw new Error('next already started')
}
......@@ -161,6 +161,7 @@ export class NextDevInstance extends NextInstance {
env: {
...process.env,
...this.env,
...options.env,
NODE_ENV: this.env.NODE_ENV || ('' as any),
PORT: this.forcedPort || '0',
__NEXT_TEST_MODE: 'e2e',
......
......@@ -60,13 +60,15 @@ export class NextStartInstance extends NextInstance {
})
}
public async start(options: { skipBuild?: boolean } = {}) {
public async start(
options: { skipBuild?: boolean; env?: Record<string, string> } = {}
) {
if (this.childProcess) {
throw new Error('next already started')
}
this._cliOutput = ''
const spawnOpts = this.getSpawnOpts()
const spawnOpts = this.getSpawnOpts(options.env)
let startArgs = ['pnpm', 'next', 'start']
......
import { createNext } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
describe('ci-missing-typescript-deps', () => {
it('should show missing TypeScript dependencies error in CI', async () => {
const next = await createNext({
describe('missing typescript dep', () => {
const { next } = nextTestSetup({
files: {
'pages/index.tsx': `
export default function Page() {
......@@ -18,7 +18,8 @@ describe('ci-missing-typescript-deps', () => {
typescript: undefined,
},
})
try {
it('should show missing TypeScript dependencies error in CI', async () => {
let error
await next.start().catch((err) => {
error = err
......@@ -31,13 +32,11 @@ describe('ci-missing-typescript-deps', () => {
expect(next.cliOutput).toContain(`Please install`)
expect(next.cliOutput).not.toContain('Call retries were exceeded')
expect(next.cliOutput).not.toContain('WorkerError')
} finally {
await next.destroy()
}
})
})
it('should not throw an error if beta version of @types/react and @types/react-dom is installed', async () => {
const next = await createNext({
describe('with @types/react beta', () => {
const { next } = nextTestSetup({
files: {
'pages/index.tsx': `
export default function Page() {
......@@ -66,14 +65,13 @@ describe('ci-missing-typescript-deps', () => {
},
},
})
try {
it('should not throw an error if beta version of @types/react and @types/react-dom is installed', async () => {
const nextBuild = await next.build()
expect(nextBuild.cliOutput).toContain(
// matching the part of the success message that isn't colored.
`We detected TypeScript in your project and created`
)
} finally {
await next.destroy()
}
})
})
})
import execa from 'execa'
import { join } from 'path'
import { createNext } from 'e2e-utils'
import { spawn } from 'child_process'
import { fetchViaHTTP, findPort, killApp } from 'next-test-utils'
import {
resolveTestPkgPaths,
serializeTestPkgPathsEnv,
......@@ -90,28 +91,80 @@ export async function tryNextDev({
isApi?: boolean
isEmpty?: boolean
}) {
// The caller wraps this in `useTempDir`, so `cwd` (and the CNA project
// inside it) is already an isolated temp directory that gets removed
// after the test. Running `next build`/`next start` directly inside it
// is safe — `.next/` artifacts are cleaned up with the temp dir.
const dir = join(cwd, projectName)
// CNA installs `eslint-config-next` from the same `packed.tgz` path as
// `next` (both come from `NEXT_PRIVATE_TEST_VERSION`), which causes npm to
// unpack next's tarball into `node_modules/eslint-config-next` and to
// create a `node_modules/.bin/next` shim pointing at that copy. Invoke
// next's bin directly so webpack loaders resolve under `node_modules/next`.
const nextBin = 'node_modules/next/dist/bin/next'
const next = await createNext({
files: dir,
installCommand: 'true',
skipStart: false,
// Freshly installed CNA projects (with tailwind, eslint plugins, etc.)
// can take well over the default 10s to boot `next start`, especially
// under webpack where the built output is larger. Give them generous
// headroom so these tests aren't flaky on loaded CI machines.
startServerTimeout: 60_000,
buildCommand: `node ${nextBin} build`,
startCommand: `node ${nextBin} start`,
const nextBin = join(dir, 'node_modules/next/dist/bin/next')
const buildResult = await execa('node', [nextBin, 'build'], {
cwd: dir,
stdio: 'inherit',
env: { ...process.env },
reject: false,
})
expect(buildResult.exitCode).toBe(0)
const port = await findPort()
const server = spawn(
'node',
[nextBin, 'start', '-p', String(port), '-H', '127.0.0.1'],
{
cwd: dir,
env: { ...process.env, HOSTNAME: '127.0.0.1' },
stdio: ['ignore', 'pipe', 'pipe'],
}
)
// Freshly installed CNA projects (with tailwind, eslint plugins, etc.)
// can take well over the default 10s to boot `next start`, especially
// under webpack where the built output is larger. Give them generous
// headroom so these tests aren't flaky on loaded CI machines.
const startServerTimeout = 60_000
try {
const res = await next.fetch('/')
await new Promise<void>((resolve, reject) => {
const onTimeout = setTimeout(() => {
reject(
new Error(
`next start did not become ready within ${startServerTimeout}ms`
)
)
}, startServerTimeout)
const onReady = () => {
clearTimeout(onTimeout)
resolve()
}
const handleData = (chunk: Buffer) => {
const msg = chunk.toString()
process.stdout.write(msg)
if (/- Local:|Ready in|✓ Ready/i.test(msg)) {
onReady()
}
}
server.stdout!.on('data', handleData)
server.stderr!.on('data', (chunk: Buffer) => {
process.stderr.write(chunk.toString())
})
server.on('exit', (code) => {
clearTimeout(onTimeout)
reject(
new Error(`next start exited before becoming ready (code=${code})`)
)
})
})
const res = await fetchViaHTTP(port, '/')
if (isEmpty || isApi) {
expect(await res.text()).toContain('Hello world!')
} else {
......@@ -127,12 +180,12 @@ export async function tryNextDev({
expect(res.status).toBe(200)
if (!isApp && !isEmpty) {
const apiRes = await next.fetch('/api/hello')
const apiRes = await fetchViaHTTP(port, '/api/hello')
expect(await apiRes.json()).toEqual({ name: 'John Doe' })
expect(apiRes.status).toBe(200)
}
} finally {
await next.destroy()
await killApp(server).catch(() => {})
}
}
......
import { join } from 'path'
import type { ChildProcess } from 'child_process'
import { NextInstance, createNext, FileRef, nextTestSetup } from 'e2e-utils'
import { NextInstance, FileRef, nextTestSetup } from 'e2e-utils'
import {
fetchViaHTTP,
findPort,
......@@ -119,9 +119,6 @@ describe('Graceful Shutdown', () => {
;(process.env.IS_TURBOPACK_TEST && !process.env.TURBOPACK_BUILD
? describe.skip
: describe)('production (standalone mode)', () => {
let next: NextInstance
let serverFile: string
const projectFiles: Record<string, string | FileRef> = {
'next.config.mjs': `export default { output: 'standalone' }`,
}
......@@ -130,15 +127,21 @@ describe('Graceful Shutdown', () => {
projectFiles[file] = new FileRef(join(appDir, file))
}
beforeAll(async () => {
next = await createNext({
files: projectFiles,
dependencies: {
swr: 'latest',
},
})
const { next } = nextTestSetup({
files: projectFiles,
dependencies: {
swr: 'latest',
},
skipStart: true,
})
await next.stop()
let serverFile: string
beforeAll(async () => {
const { exitCode } = await next.build()
if (exitCode !== 0) {
throw new Error(`Failed to build next: ${exitCode}`)
}
await fs.move(
join(next.testDir, '.next/standalone'),
......@@ -180,8 +183,6 @@ describe('Graceful Shutdown', () => {
})
afterEach(() => killApp(app))
afterAll(() => next.destroy())
runTests()
})
})
......
......@@ -2,8 +2,7 @@
import path from 'path'
import fs from 'fs-extra'
import webdriver from 'next-webdriver'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { FileRef, nextTestSetup } from 'e2e-utils'
import {
findPort,
initNextServerScript,
......@@ -12,16 +11,8 @@ import {
} from 'next-test-utils'
describe('pnpm support', () => {
let next: NextInstance | undefined
afterEach(async () => {
try {
await next?.destroy()
} catch (_) {}
})
it('should build with dependencies installed via pnpm', async () => {
next = await createNext({
describe('build with dependencies installed via pnpm', () => {
const { next } = nextTestSetup({
files: {
pages: new FileRef(path.join(__dirname, 'app/pages')),
'next.config.js': new FileRef(
......@@ -37,32 +28,38 @@ describe('pnpm support', () => {
buildCommand: 'pnpm run build',
})
expect(await next.readFile('pnpm-lock.yaml')).toBeTruthy()
it('should build with dependencies installed via pnpm', async () => {
expect(await next.readFile('pnpm-lock.yaml')).toBeTruthy()
expect(next.cliOutput).toMatch(/Compiled successfully/)
expect(next.cliOutput).toMatch(/Compiled successfully/)
const html = await renderViaHTTP(next.url, '/')
expect(html).toContain('Hello World')
const html = await renderViaHTTP(next.url, '/')
expect(html).toContain('Hello World')
const manifest = JSON.parse(
await next.readFile('.next/next-server.js.nft.json')
)
for (const ignore of ['next/dist/pages', '.wasm', 'compiled/@ampproject']) {
let matchingFile
try {
matchingFile = manifest.files.some((file) => file.includes(ignore))
expect(!!matchingFile).toBe(false)
} catch (err) {
require('console').error(
`Found unexpected file in manifest ${matchingFile} matched ${ignore}`
)
throw err
const manifest = JSON.parse(
await next.readFile('.next/next-server.js.nft.json')
)
for (const ignore of [
'next/dist/pages',
'.wasm',
'compiled/@ampproject',
]) {
let matchingFile
try {
matchingFile = manifest.files.some((file) => file.includes(ignore))
expect(!!matchingFile).toBe(false)
} catch (err) {
require('console').error(
`Found unexpected file in manifest ${matchingFile} matched ${ignore}`
)
throw err
}
}
}
})
})
it('should execute client-side JS on each page in output: "standalone"', async () => {
next = await createNext({
describe('standalone mode with client-side JS', () => {
const { next } = nextTestSetup({
files: {
pages: new FileRef(path.join(__dirname, 'app-multi-page/pages')),
'.npmrc': new FileRef(path.join(__dirname, 'app-multi-page/.npmrc')),
......@@ -79,57 +76,60 @@ describe('pnpm support', () => {
},
buildCommand: 'pnpm run build',
})
await next.stop()
expect(next.cliOutput).toMatch(/Compiled successfully/)
let appPort
let server
let browser
try {
appPort = await findPort()
const standaloneDir = path.join(
next.testDir,
'.next/standalone/',
path.basename(next.testDir)
)
it('should execute client-side JS on each page in output: "standalone"', async () => {
await next.stop()
expect(next.cliOutput).toMatch(/Compiled successfully/)
// simulate what happens in a Dockerfile
await fs.remove(path.join(next.testDir, 'node_modules'))
await fs.copy(
path.join(next.testDir, './.next/static'),
path.join(standaloneDir, './.next/static'),
{ overwrite: true }
)
server = await initNextServerScript(
path.join(standaloneDir, 'server.js'),
/- Local:/,
{
...process.env,
PORT: appPort,
},
undefined,
{
cwd: standaloneDir,
}
)
let appPort
let server
let browser
try {
appPort = await findPort()
const standaloneDir = path.join(
next.testDir,
'.next/standalone/',
path.basename(next.testDir)
)
await renderViaHTTP(appPort, '/')
// simulate what happens in a Dockerfile
await fs.remove(path.join(next.testDir, 'node_modules'))
await fs.copy(
path.join(next.testDir, './.next/static'),
path.join(standaloneDir, './.next/static'),
{ overwrite: true }
)
server = await initNextServerScript(
path.join(standaloneDir, 'server.js'),
/- Local:/,
{
...process.env,
PORT: appPort,
},
undefined,
{
cwd: standaloneDir,
}
)
await renderViaHTTP(appPort, '/')
browser = await webdriver(appPort, '/', {
waitHydration: false,
})
expect(await browser.waitForElementByCss('#world').text()).toBe('World')
await browser.close()
browser = await webdriver(appPort, '/', {
waitHydration: false,
})
expect(await browser.waitForElementByCss('#world').text()).toBe('World')
await browser.close()
browser = await webdriver(appPort, '/about', {
waitHydration: false,
})
expect(await browser.waitForElementByCss('#world').text()).toBe('World')
await browser.close()
} finally {
if (server) {
await killApp(server)
browser = await webdriver(appPort, '/about', {
waitHydration: false,
})
expect(await browser.waitForElementByCss('#world').text()).toBe('World')
await browser.close()
} finally {
if (server) {
await killApp(server)
}
}
}
})
})
})
import net from 'net'
import http from 'http'
import { createNext, NextInstance } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { findPort, retry } from 'next-test-utils'
describe('rewrite-request-smuggling', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
const ssrfProbePath = '/secret-upgrade'
const ssrfProbeBody =
'SSRF_CONFIRMED: You reached the internal service at 127.0.0.1'
......@@ -11,7 +16,6 @@ describe('rewrite-request-smuggling', () => {
let backendPort: number
let intermediary: http.Server
let intermediaryPort: number
let next: NextInstance
const backendRequests: string[] = []
async function sendSmugglingPayload({
......@@ -191,16 +195,12 @@ describe('rewrite-request-smuggling', () => {
intermediary.once('error', reject)
})
next = await createNext({
files: __dirname,
env: {
TEST_INTERMEDIARY_PORT: String(intermediaryPort),
},
await next.start({
env: { TEST_INTERMEDIARY_PORT: String(intermediaryPort) },
})
})
afterAll(async () => {
await next?.destroy()
await new Promise<void>((resolve) => intermediary.close(() => resolve()))
await new Promise<void>((resolve) => backend.close(() => resolve()))
})
......
......@@ -2,8 +2,7 @@ import glob from 'glob'
import fs from 'fs-extra'
import { join } from 'path'
import cheerio from 'cheerio'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { FileRef, nextTestSetup } from 'e2e-utils'
import {
createNowRouteMatches,
fetchViaHTTP,
......@@ -15,39 +14,37 @@ import {
import { ChildProcess } from 'child_process'
describe('required server files app router', () => {
let next: NextInstance
const { next } = nextTestSetup({
files: {
app: new FileRef(join(__dirname, 'app')),
lib: new FileRef(join(__dirname, 'lib')),
'cache-handler.js': new FileRef(join(__dirname, 'cache-handler.js')),
'middleware.js': new FileRef(join(__dirname, 'middleware.js')),
'data.txt': new FileRef(join(__dirname, 'data.txt')),
'.env': new FileRef(join(__dirname, '.env')),
'.env.local': new FileRef(join(__dirname, '.env.local')),
'.env.production': new FileRef(join(__dirname, '.env.production')),
},
nextConfig: {
cacheHandler: './cache-handler.js',
cacheMaxMemorySize: 0,
output: 'standalone',
},
skipStart: true,
})
let server: ChildProcess
let appPort: number | string
const setupNext = async ({
nextEnv,
minimalMode,
}: {
nextEnv?: boolean
minimalMode?: boolean
}) => {
beforeAll(async () => {
// test build against environment with next support
process.env.NOW_BUILDER = nextEnv ? '1' : ''
process.env.NOW_BUILDER = '1'
process.env.NEXT_PRIVATE_TEST_HEADERS = '1'
next = await createNext({
files: {
app: new FileRef(join(__dirname, 'app')),
lib: new FileRef(join(__dirname, 'lib')),
'cache-handler.js': new FileRef(join(__dirname, 'cache-handler.js')),
'middleware.js': new FileRef(join(__dirname, 'middleware.js')),
'data.txt': new FileRef(join(__dirname, 'data.txt')),
'.env': new FileRef(join(__dirname, '.env')),
'.env.local': new FileRef(join(__dirname, '.env.local')),
'.env.production': new FileRef(join(__dirname, '.env.production')),
},
nextConfig: {
cacheHandler: './cache-handler.js',
cacheMaxMemorySize: 0,
output: 'standalone',
},
})
await next.stop()
const { exitCode } = await next.build()
if (exitCode !== 0) {
throw new Error(`Failed to build next: ${exitCode}`)
}
await fs.move(
join(next.testDir, '.next/standalone'),
......@@ -70,6 +67,7 @@ describe('required server files app router', () => {
}
}
const minimalMode = true
const testServer = join(next.testDir, 'standalone/server.js')
await fs.writeFile(
testServer,
......@@ -92,15 +90,10 @@ describe('required server files app router', () => {
cwd: next.testDir,
}
)
}
beforeAll(async () => {
await setupNext({ nextEnv: true, minimalMode: true })
})
afterAll(async () => {
delete process.env.NOW_BUILDER
delete process.env.NEXT_PRIVATE_TEST_HEADERS
await next.destroy()
if (server) await killApp(server)
})
......
......@@ -2,8 +2,7 @@ import glob from 'glob'
import fs from 'fs-extra'
import cheerio from 'cheerio'
import { join } from 'path'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { FileRef, nextTestSetup } from 'e2e-utils'
import {
check,
createNowRouteMatches,
......@@ -19,14 +18,50 @@ import nodeFetch from 'node-fetch'
import { ChildProcess } from 'child_process'
describe('required server files i18n', () => {
let next: NextInstance
const { next } = nextTestSetup({
files: {
pages: new FileRef(join(__dirname, 'pages')),
lib: new FileRef(join(__dirname, 'lib')),
'data.txt': new FileRef(join(__dirname, 'data.txt')),
},
// The build script is patched in `beforeAll` below to optionally strip
// the swc native bindings (exercising the wasm fallback path) when the
// @next/swc-wasm-nodejs package is available on the registry.
packageJson: {
scripts: {
build: 'next build',
},
},
installCommand: 'pnpm i',
buildCommand: 'pnpm build',
nextConfig: {
i18n: {
locales: ['en', 'fr'],
defaultLocale: 'en',
},
output: 'standalone',
async rewrites() {
return [
{
source: '/some-catch-all/:path*',
destination: '/',
},
{
source: '/to-dynamic/:path',
destination: '/dynamic/:path',
},
]
},
},
skipStart: true,
})
let server: ChildProcess
let appPort: number | string
let errors = []
let requiredFilesManifest
beforeAll(async () => {
let wasmPkgIsAvailable = false
process.env.NEXT_PRIVATE_TEST_HEADERS = '1'
const res = await nodeFetch(
......@@ -39,46 +74,18 @@ describe('required server files i18n', () => {
)
if (res.status === 200) {
wasmPkgIsAvailable = true
console.warn(`Testing wasm fallback handling`)
await next.patchFile('package.json', (content) => {
const pkg = JSON.parse(content)
pkg.scripts.build = 'rm -rfv node_modules/@next/swc && next build'
return JSON.stringify(pkg, null, 2)
})
}
next = await createNext({
files: {
pages: new FileRef(join(__dirname, 'pages')),
lib: new FileRef(join(__dirname, 'lib')),
'data.txt': new FileRef(join(__dirname, 'data.txt')),
},
packageJson: {
scripts: {
build: wasmPkgIsAvailable
? 'rm -rfv node_modules/@next/swc && next build'
: 'next build',
},
},
installCommand: 'pnpm i',
buildCommand: 'pnpm build',
nextConfig: {
i18n: {
locales: ['en', 'fr'],
defaultLocale: 'en',
},
output: 'standalone',
async rewrites() {
return [
{
source: '/some-catch-all/:path*',
destination: '/',
},
{
source: '/to-dynamic/:path',
destination: '/dynamic/:path',
},
]
},
},
})
await next.stop()
const { exitCode } = await next.build()
if (exitCode !== 0) {
throw new Error(`Failed to build next: ${exitCode}`)
}
requiredFilesManifest = JSON.parse(
await next.readFile('.next/required-server-files.json')
......@@ -133,7 +140,6 @@ describe('required server files i18n', () => {
afterAll(async () => {
delete process.env.NEXT_PRIVATE_TEST_HEADERS
await next.destroy()
if (server) await killApp(server)
})
......
......@@ -3,8 +3,7 @@ import fs from 'fs-extra'
import cheerio from 'cheerio'
import { join } from 'path'
import { nanoid } from 'nanoid'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { FileRef, nextTestSetup } from 'e2e-utils'
import {
check,
createNowRouteMatches,
......@@ -20,7 +19,62 @@ import {
import { ChildProcess } from 'child_process'
describe('required server files', () => {
let next: NextInstance
const { next } = nextTestSetup({
files: {
pages: new FileRef(join(__dirname, 'pages')),
lib: new FileRef(join(__dirname, 'lib')),
'middleware.js': new FileRef(
join(
__dirname,
process.env.TEST_NODE_MIDDLEWARE
? 'middleware-node.js'
: 'middleware.js'
)
),
'instrumentation.js': new FileRef(join(__dirname, 'instrumentation.js')),
'cache-handler.js': new FileRef(join(__dirname, 'cache-handler.js')),
'data.txt': new FileRef(join(__dirname, 'data.txt')),
'.env': new FileRef(join(__dirname, '.env')),
'.env.local': new FileRef(join(__dirname, '.env.local')),
'.env.production': new FileRef(join(__dirname, '.env.production')),
},
nextConfig: {
cacheHandler: './cache-handler.js',
cacheMaxMemorySize: 0,
output: 'standalone',
async rewrites() {
return {
beforeFiles: [],
fallback: [
{
source: '/an-ssg-path',
destination: '/hello.txt',
},
{
source: '/fallback-false/:path',
destination: '/hello.txt',
},
],
afterFiles: [
{
source: '/some-catch-all/:path*',
destination: '/',
},
{
source: '/to-dynamic/post-2',
destination: '/dynamic/post-2?hello=world',
},
{
source: '/to-dynamic/:path',
destination: '/dynamic/:path',
},
],
}
},
},
skipStart: true,
})
let server: ChildProcess
let appPort: number | string
let errors = []
......@@ -28,71 +82,15 @@ describe('required server files', () => {
let requiredFilesManifest
let minimalMode = true
const setupNext = async ({ nextEnv }: { nextEnv?: boolean }) => {
beforeAll(async () => {
// test build against environment with next support
process.env.NOW_BUILDER = nextEnv ? '1' : ''
process.env.NOW_BUILDER = '1'
process.env.NEXT_PRIVATE_TEST_HEADERS = '1'
next = await createNext({
files: {
pages: new FileRef(join(__dirname, 'pages')),
lib: new FileRef(join(__dirname, 'lib')),
'middleware.js': new FileRef(
join(
__dirname,
process.env.TEST_NODE_MIDDLEWARE
? 'middleware-node.js'
: 'middleware.js'
)
),
'instrumentation.js': new FileRef(
join(__dirname, 'instrumentation.js')
),
'cache-handler.js': new FileRef(join(__dirname, 'cache-handler.js')),
'data.txt': new FileRef(join(__dirname, 'data.txt')),
'.env': new FileRef(join(__dirname, '.env')),
'.env.local': new FileRef(join(__dirname, '.env.local')),
'.env.production': new FileRef(join(__dirname, '.env.production')),
},
nextConfig: {
cacheHandler: './cache-handler.js',
cacheMaxMemorySize: 0,
output: 'standalone',
async rewrites() {
return {
beforeFiles: [],
fallback: [
{
source: '/an-ssg-path',
destination: '/hello.txt',
},
{
source: '/fallback-false/:path',
destination: '/hello.txt',
},
],
afterFiles: [
{
source: '/some-catch-all/:path*',
destination: '/',
},
{
source: '/to-dynamic/post-2',
destination: '/dynamic/post-2?hello=world',
},
{
source: '/to-dynamic/:path',
destination: '/dynamic/:path',
},
],
}
},
},
skipStart: true,
})
let { exitCode } = await next.build()
expect(exitCode).toBe(0)
if (exitCode !== 0) {
throw new Error(`Failed to build next: ${exitCode}`)
}
requiredFilesManifest = JSON.parse(
await next.readFile('.next/required-server-files.json')
......@@ -117,10 +115,6 @@ describe('required server files', () => {
await fs.remove(join(next.testDir, '.next/server', file))
}
}
}
beforeAll(async () => {
await setupNext({ nextEnv: true })
})
beforeEach(async () => {
......@@ -168,7 +162,6 @@ describe('required server files', () => {
afterAll(async () => {
delete process.env.NOW_BUILDER
delete process.env.NEXT_PRIVATE_TEST_HEADERS
await next.destroy()
})
it('should resolve correctly when a redirect is returned', async () => {
......
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