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