Unverified Commit c6320ed8 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Replace createNextDescribe with nextTestSetup (#64817)

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

I took some time and [wrote a
codemod](https://gist.github.com/wyattjoh/0d4464427506cb02062a4729ca906b62)
that replaces the old usage of the `createNextDescribe` with the new
`nextTestSetup`. You'll likely have to turn on hiding of whitespace in
order to review, but this should primarily introduce no changes to the
test structure other than using the new mechanism now.

Closes NEXT-3178
parent a6a61171
import path from 'path'
import { outdent } from 'outdent'
import { FileRef, createNextDescribe } from 'e2e-utils'
import { FileRef, nextTestSetup } from 'e2e-utils'
import {
check,
getRedboxDescription,
......@@ -10,41 +10,40 @@ import {
retry,
} from 'next-test-utils'
createNextDescribe(
'Error overlay - RSC runtime errors',
{
describe('Error overlay - RSC runtime errors', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'rsc-runtime-errors')),
},
({ next }) => {
it('should show runtime errors if invalid client API from node_modules is executed', async () => {
await next.patchFile(
'app/server/page.js',
outdent`
})
it('should show runtime errors if invalid client API from node_modules is executed', async () => {
await next.patchFile(
'app/server/page.js',
outdent`
import { callClientApi } from 'client-package'
export default function Page() {
callClientApi()
return 'page'
}
`
)
)
const browser = await next.browser('/server')
const browser = await next.browser('/server')
await check(
async () => ((await hasRedbox(browser)) ? 'success' : 'fail'),
/success/
)
const errorDescription = await getRedboxDescription(browser)
await check(
async () => ((await hasRedbox(browser)) ? 'success' : 'fail'),
/success/
)
const errorDescription = await getRedboxDescription(browser)
expect(errorDescription).toContain(
`Error: useState only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/react-client-hook-in-server-component`
)
})
expect(errorDescription).toContain(
`Error: useState only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/react-client-hook-in-server-component`
)
})
it('should show runtime errors if invalid server API from node_modules is executed', async () => {
await next.patchFile(
'app/client/page.js',
outdent`
it('should show runtime errors if invalid server API from node_modules is executed', async () => {
await next.patchFile(
'app/client/page.js',
outdent`
'use client'
import { callServerApi } from 'server-package'
export default function Page() {
......@@ -52,101 +51,100 @@ createNextDescribe(
return 'page'
}
`
)
)
const browser = await next.browser('/client')
const browser = await next.browser('/client')
await check(
async () => ((await hasRedbox(browser)) ? 'success' : 'fail'),
/success/
)
const errorDescription = await getRedboxDescription(browser)
await check(
async () => ((await hasRedbox(browser)) ? 'success' : 'fail'),
/success/
)
const errorDescription = await getRedboxDescription(browser)
expect(errorDescription).toContain(
'Error: `cookies` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context'
)
})
expect(errorDescription).toContain(
'Error: `cookies` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context'
)
})
it('should show source code for jsx errors from server component', async () => {
await next.patchFile(
'app/server/page.js',
outdent`
it('should show source code for jsx errors from server component', async () => {
await next.patchFile(
'app/server/page.js',
outdent`
export default function Page() {
return <div>{alert('warn')}</div>
}
`
)
)
const browser = await next.browser('/server')
await check(
async () => ((await hasRedbox(browser)) ? 'success' : 'fail'),
/success/
)
const browser = await next.browser('/server')
await check(
async () => ((await hasRedbox(browser)) ? 'success' : 'fail'),
/success/
)
const errorDescription = await getRedboxDescription(browser)
const errorDescription = await getRedboxDescription(browser)
expect(errorDescription).toContain(`Error: alert is not defined`)
})
expect(errorDescription).toContain(`Error: alert is not defined`)
})
it('should show the userland code error trace when fetch failed error occurred', async () => {
await next.patchFile(
'app/server/page.js',
outdent`
it('should show the userland code error trace when fetch failed error occurred', async () => {
await next.patchFile(
'app/server/page.js',
outdent`
export default async function Page() {
await fetch('http://locahost:3000/xxxx')
return 'page'
}
`
)
const browser = await next.browser('/server')
await check(
async () => ((await hasRedbox(browser)) ? 'success' : 'fail'),
/success/
)
const source = await getRedboxSource(browser)
// Can show the original source code
expect(source).toContain('app/server/page.js')
expect(source).toContain(`await fetch('http://locahost:3000/xxxx')`)
})
it('should contain nextjs version check in error overlay', async () => {
await next.patchFile(
'app/server/page.js',
outdent`
)
const browser = await next.browser('/server')
await check(
async () => ((await hasRedbox(browser)) ? 'success' : 'fail'),
/success/
)
const source = await getRedboxSource(browser)
// Can show the original source code
expect(source).toContain('app/server/page.js')
expect(source).toContain(`await fetch('http://locahost:3000/xxxx')`)
})
it('should contain nextjs version check in error overlay', async () => {
await next.patchFile(
'app/server/page.js',
outdent`
export default function Page() {
throw new Error('test')
}
`
)
const browser = await next.browser('/server')
await retry(async () => {
expect(await hasRedbox(browser)).toBe(true)
})
const versionText = await getVersionCheckerText(browser)
await expect(versionText).toMatch(/Next.js \([\w.-]+\)/)
})
)
const browser = await next.browser('/server')
it('should not show the bundle layer info in the file trace', async () => {
await next.patchFile(
'app/server/page.js',
outdent`
await retry(async () => {
expect(await hasRedbox(browser)).toBe(true)
})
const versionText = await getVersionCheckerText(browser)
await expect(versionText).toMatch(/Next.js \([\w.-]+\)/)
})
it('should not show the bundle layer info in the file trace', async () => {
await next.patchFile(
'app/server/page.js',
outdent`
export default function Page() {
throw new Error('test')
}
`
)
const browser = await next.browser('/server')
await retry(async () => {
expect(await hasRedbox(browser)).toBe(true)
})
const source = await getRedboxSource(browser)
expect(source).toContain('app/server/page.js')
expect(source).not.toContain('//app/server/page.js')
// Does not contain webpack traces in file path
expect(source).not.toMatch(/webpack(-internal:)?\/\//)
)
const browser = await next.browser('/server')
await retry(async () => {
expect(await hasRedbox(browser)).toBe(true)
})
}
)
const source = await getRedboxSource(browser)
expect(source).toContain('app/server/page.js')
expect(source).not.toContain('//app/server/page.js')
// Does not contain webpack traces in file path
expect(source).not.toMatch(/webpack(-internal:)?\/\//)
})
})
/* eslint-env jest */
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { getRedboxComponentStack, hasRedbox } from 'next-test-utils'
import path from 'path'
createNextDescribe(
'Component Stack in error overlay',
{
describe('Component Stack in error overlay', () => {
const { next } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'component-stack'),
},
({ next }) => {
it('should show a component stack on hydration error', async () => {
const browser = await next.browser('/')
})
expect(await hasRedbox(browser)).toBe(true)
it('should show a component stack on hydration error', async () => {
const browser = await next.browser('/')
if (process.env.TURBOPACK) {
expect(await getRedboxComponentStack(browser)).toMatchInlineSnapshot(`
expect(await hasRedbox(browser)).toBe(true)
if (process.env.TURBOPACK) {
expect(await getRedboxComponentStack(browser)).toMatchInlineSnapshot(`
"...
<App>
<Mismatch>
......@@ -26,8 +25,8 @@ createNextDescribe(
"server"
"client""
`)
} else {
expect(await getRedboxComponentStack(browser)).toMatchInlineSnapshot(`
} else {
expect(await getRedboxComponentStack(browser)).toMatchInlineSnapshot(`
"<Mismatch>
<main>
<Component>
......@@ -36,7 +35,6 @@ createNextDescribe(
"server"
"client""
`)
}
})
}
)
}
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'app-dir - app routes errors',
{
describe('app-dir - app routes errors', () => {
const { next } = nextTestSetup({
files: __dirname,
},
({ next }) => {
describe('bad lowercase exports', () => {
it.each([
['get'],
['head'],
['options'],
['post'],
['put'],
['delete'],
['patch'],
])(
'should print an error when using lowercase %p in dev',
async (method: string) => {
await next.fetch('/lowercase/' + method)
})
await check(() => {
expect(next.cliOutput).toContain(
`Detected lowercase method '${method}' in`
)
expect(next.cliOutput).toContain(
`Export the uppercase '${method.toUpperCase()}' method name to fix this error.`
)
expect(next.cliOutput).toMatch(
/Detected lowercase method '.+' in '.+\/route\.js'\. Export the uppercase '.+' method name to fix this error\./
)
return 'yes'
}, 'yes')
}
)
})
}
)
describe('bad lowercase exports', () => {
it.each([
['get'],
['head'],
['options'],
['post'],
['put'],
['delete'],
['patch'],
])(
'should print an error when using lowercase %p in dev',
async (method: string) => {
await next.fetch('/lowercase/' + method)
await check(() => {
expect(next.cliOutput).toContain(
`Detected lowercase method '${method}' in`
)
expect(next.cliOutput).toContain(
`Export the uppercase '${method.toUpperCase()}' method name to fix this error.`
)
expect(next.cliOutput).toMatch(
/Detected lowercase method '.+' in '.+\/route\.js'\. Export the uppercase '.+' method name to fix this error\./
)
return 'yes'
}, 'yes')
}
)
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import {
getRedboxCallStack,
hasRedbox,
......@@ -7,9 +7,8 @@ import {
getRedboxSource,
} from 'next-test-utils'
createNextDescribe(
'app dir - dynamic error trace',
{
describe('app dir - dynamic error trace', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
dependencies: {
swr: 'latest',
......@@ -25,18 +24,18 @@ createNextDescribe(
startCommand: (global as any).isNextDev ? 'pnpm dev' : 'pnpm start',
buildCommand: 'pnpm build',
skipDeployment: true,
},
({ next }) => {
it('should show the error trace', async () => {
const browser = await next.browser('/')
await hasRedbox(browser)
await expandCallStack(browser)
const callStack = await getRedboxCallStack(browser)
})
if (skipped) return
expect(callStack).toContain('node_modules/headers-lib/index.mjs')
it('should show the error trace', async () => {
const browser = await next.browser('/')
await hasRedbox(browser)
await expandCallStack(browser)
const callStack = await getRedboxCallStack(browser)
const source = await getRedboxSource(browser)
expect(source).toContain('app/lib.js')
})
}
)
expect(callStack).toContain('node_modules/headers-lib/index.mjs')
const source = await getRedboxSource(browser)
expect(source).toContain('app/lib.js')
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { hasRedbox } from 'next-test-utils'
createNextDescribe(
'develop - app-dir - edge errros hmr',
{
describe('develop - app-dir - edge errros hmr', () => {
const { next } = nextTestSetup({
files: __dirname,
},
({ next }) => {
it('should recover from build errors when server component error', async () => {
const browser = await next.browser('/')
const clientComponentSource = await next.readFile('app/comp.server.js')
})
await next.patchFile('app/comp.server.js', (content) => {
return content.replace('{/* < */}', '<') // uncomment
})
it('should recover from build errors when server component error', async () => {
const browser = await next.browser('/')
const clientComponentSource = await next.readFile('app/comp.server.js')
expect(await hasRedbox(browser)).toBe(true)
await next.patchFile('app/comp.server.js', clientComponentSource)
expect(await hasRedbox(browser)).toBe(false)
await next.patchFile('app/comp.server.js', (content) => {
return content.replace('{/* < */}', '<') // uncomment
})
it('should recover from build errors when client component error', async () => {
const browser = await next.browser('/')
const clientComponentSource = await next.readFile('app/comp.client.js')
expect(await hasRedbox(browser)).toBe(true)
await next.patchFile('app/comp.client.js', (content) => {
return content.replace('{/* < */}', '<') // uncomment
})
await next.patchFile('app/comp.server.js', clientComponentSource)
expect(await hasRedbox(browser)).toBe(true)
expect(await hasRedbox(browser)).toBe(false)
})
await next.patchFile('app/comp.client.js', clientComponentSource)
it('should recover from build errors when client component error', async () => {
const browser = await next.browser('/')
const clientComponentSource = await next.readFile('app/comp.client.js')
expect(await hasRedbox(browser)).toBe(false)
await next.patchFile('app/comp.client.js', (content) => {
return content.replace('{/* < */}', '<') // uncomment
})
}
)
expect(await hasRedbox(browser)).toBe(true)
await next.patchFile('app/comp.client.js', clientComponentSource)
expect(await hasRedbox(browser)).toBe(false)
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { hasRedbox } from 'next-test-utils'
createNextDescribe(
'HMR Move File',
{
describe('HMR Move File', () => {
const { next } = nextTestSetup({
files: __dirname,
},
({ next }) => {
it('should work when moving a component to another directory', async () => {
const browser = await next.browser('/')
expect(await browser.elementByCss('#hello-world-button').text()).toBe(
'hello world'
)
})
await next.renameFile('app/button.tsx', 'app/button2.tsx')
await next.patchFile('app/page.tsx', (content) =>
content.replace('./button', './button2')
)
it('should work when moving a component to another directory', async () => {
const browser = await next.browser('/')
expect(await browser.elementByCss('#hello-world-button').text()).toBe(
'hello world'
)
expect(await hasRedbox(browser)).toBe(false)
await next.renameFile('app/button.tsx', 'app/button2.tsx')
await next.patchFile('app/page.tsx', (content) =>
content.replace('./button', './button2')
)
expect(await browser.elementByCss('#hello-world-button').text()).toBe(
'hello world'
)
})
}
)
expect(await hasRedbox(browser)).toBe(false)
expect(await browser.elementByCss('#hello-world-button').text()).toBe(
'hello world'
)
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
createNextDescribe(
'multiple-compiles-single-route',
{
describe('multiple-compiles-single-route', () => {
const { next } = nextTestSetup({
files: __dirname,
},
({ next }) => {
// Recommended for tests that check HTML. Cheerio is a HTML parser that has a jQuery like API.
it('should not compile additional matching paths', async () => {
const logs: string[] = []
next.on('stdout', (log) => {
logs.push(log)
})
await next.render('/about')
// Check if `/[slug]` is mentioned in the logs as being compiled
expect(logs.some((log) => log.includes('/[slug]'))).toBe(false)
})
// Recommended for tests that check HTML. Cheerio is a HTML parser that has a jQuery like API.
it('should not compile additional matching paths', async () => {
const logs: string[] = []
next.on('stdout', (log) => {
logs.push(log)
})
}
)
await next.render('/about')
// Check if `/[slug]` is mentioned in the logs as being compiled
expect(logs.some((log) => log.includes('/[slug]'))).toBe(false)
})
})
import { type BrowserInterface } from 'next-webdriver'
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'Strict Mode enabled by default',
{
describe('Strict Mode enabled by default', () => {
const { next } = nextTestSetup({
files: __dirname,
},
({ next }) => {
// experimental react is having issues with this use effect
// @acdlite will take a look
// TODO: remove this after react fixes the issue in experimental build.
if (process.env.__NEXT_EXPERIMENTAL_PPR) {
it('skip test for PPR', () => {})
return
}
// Recommended for tests that need a full browser
it('should work using browser', async () => {
const browser: BrowserInterface = await next.browser('/')
await check(async () => {
const text = await browser.elementByCss('p').text()
return text === '2' ? 'success' : `failed: ${text}`
}, 'success')
})
})
// experimental react is having issues with this use effect
// @acdlite will take a look
// TODO: remove this after react fixes the issue in experimental build.
if (process.env.__NEXT_EXPERIMENTAL_PPR) {
it('skip test for PPR', () => {})
return
}
)
// Recommended for tests that need a full browser
it('should work using browser', async () => {
const browser: BrowserInterface = await next.browser('/')
await check(async () => {
const text = await browser.elementByCss('p').text()
return text === '2' ? 'success' : `failed: ${text}`
}, 'success')
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check, waitFor } from 'next-test-utils'
const envFile = '.env.development.local'
createNextDescribe(
`app-dir-hmr`,
{
describe(`app-dir-hmr`, () => {
const { next } = nextTestSetup({
files: __dirname,
},
({ next }) => {
describe('filesystem changes', () => {
it('should not continously poll when hitting a not found page', async () => {
let requestCount = 0
})
const browser = await next.browser('/does-not-exist', {
beforePageLoad(page) {
page.on('request', (request) => {
const url = new URL(request.url())
if (url.pathname === '/does-not-exist') {
requestCount++
}
})
},
})
const body = await browser.elementByCss('body').text()
expect(body).toContain('404')
describe('filesystem changes', () => {
it('should not continously poll when hitting a not found page', async () => {
let requestCount = 0
await waitFor(3000)
expect(requestCount).toBe(1)
const browser = await next.browser('/does-not-exist', {
beforePageLoad(page) {
page.on('request', (request) => {
const url = new URL(request.url())
if (url.pathname === '/does-not-exist') {
requestCount++
}
})
},
})
const body = await browser.elementByCss('body').text()
expect(body).toContain('404')
it('should not break when renaming a folder', async () => {
const browser = await next.browser('/folder')
const text = await browser.elementByCss('h1').text()
expect(text).toBe('Hello')
await waitFor(3000)
// Rename folder
await next.renameFolder('app/folder', 'app/folder-renamed')
expect(requestCount).toBe(1)
})
try {
// Should be 404 in a few seconds
await check(async () => {
const body = await browser.elementByCss('body').text()
expect(body).toContain('404')
return 'success'
}, 'success')
it('should not break when renaming a folder', async () => {
const browser = await next.browser('/folder')
const text = await browser.elementByCss('h1').text()
expect(text).toBe('Hello')
// The new page should be rendered
const newHTML = await next.render('/folder-renamed')
expect(newHTML).toContain('Hello')
} finally {
// Rename it back
await next.renameFolder('app/folder-renamed', 'app/folder')
}
})
// Rename folder
await next.renameFolder('app/folder', 'app/folder-renamed')
it('should update server components pages when env files is changed (nodejs)', async () => {
const envContent = await next.readFile(envFile)
const browser = await next.browser('/env/node')
expect(await browser.elementByCss('p').text()).toBe('mac')
await next.patchFile(envFile, 'MY_DEVICE="ipad"')
try {
// Should be 404 in a few seconds
await check(async () => {
const body = await browser.elementByCss('body').text()
expect(body).toContain('404')
return 'success'
}, 'success')
try {
await check(async () => {
expect(await browser.elementByCss('p').text()).toBe('ipad')
return 'success'
}, /success/)
} finally {
await next.patchFile(envFile, envContent)
}
})
// The new page should be rendered
const newHTML = await next.render('/folder-renamed')
expect(newHTML).toContain('Hello')
} finally {
// Rename it back
await next.renameFolder('app/folder-renamed', 'app/folder')
}
})
it('should update server components pages when env files is changed (edge)', async () => {
const envContent = await next.readFile(envFile)
const browser = await next.browser('/env/edge')
expect(await browser.elementByCss('p').text()).toBe('mac')
await next.patchFile(envFile, 'MY_DEVICE="ipad"')
it('should update server components pages when env files is changed (nodejs)', async () => {
const envContent = await next.readFile(envFile)
const browser = await next.browser('/env/node')
expect(await browser.elementByCss('p').text()).toBe('mac')
await next.patchFile(envFile, 'MY_DEVICE="ipad"')
try {
await check(async () => {
expect(await browser.elementByCss('p').text()).toBe('ipad')
return 'success'
}, /success/)
} finally {
await next.patchFile(envFile, envContent)
}
})
try {
await check(async () => {
expect(await browser.elementByCss('p').text()).toBe('ipad')
return 'success'
}, /success/)
} finally {
await next.patchFile(envFile, envContent)
}
})
it('should have no unexpected action error for hmr', async () => {
expect(next.cliOutput).not.toContain('Unexpected action')
})
it('should update server components pages when env files is changed (edge)', async () => {
const envContent = await next.readFile(envFile)
const browser = await next.browser('/env/edge')
expect(await browser.elementByCss('p').text()).toBe('mac')
await next.patchFile(envFile, 'MY_DEVICE="ipad"')
try {
await check(async () => {
expect(await browser.elementByCss('p').text()).toBe('ipad')
return 'success'
}, /success/)
} finally {
await next.patchFile(envFile, envContent)
}
})
it('should have no unexpected action error for hmr', async () => {
expect(next.cliOutput).not.toContain('Unexpected action')
})
}
)
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'app-render-error-log',
{
describe('app-render-error-log', () => {
const { next } = nextTestSetup({
files: __dirname,
},
({ next }) => {
it('should log the correct values on app-render error', async () => {
const outputIndex = next.cliOutput.length
await next.fetch('/')
await check(() => next.cliOutput.slice(outputIndex), /at Page/)
const cliOutput = next.cliOutput.slice(outputIndex)
await check(() => cliOutput, /digest:/)
expect(cliOutput).toInclude('Error: boom')
expect(cliOutput).toInclude('at fn2 (./app/fn.ts')
expect(cliOutput).toMatch(/at (Module\.)?fn1 \(\.\/app\/fn\.ts/)
expect(cliOutput).toInclude('at Page (./app/page.tsx')
expect(cliOutput).not.toInclude('webpack-internal')
})
it('should log the correct values on app-render error with edge runtime', async () => {
const outputIndex = next.cliOutput.length
await next.fetch('/edge')
await check(() => next.cliOutput.slice(outputIndex), /at EdgePage/)
const cliOutput = next.cliOutput.slice(outputIndex)
await check(() => cliOutput, /digest:/)
expect(cliOutput).toInclude('Error: boom')
expect(cliOutput).toInclude('at fn2 (./app/fn.ts')
expect(cliOutput).toMatch(/at (Module\.)?fn1 \(\.\/app\/fn\.ts/)
expect(cliOutput).toInclude('at EdgePage (./app/edge/page.tsx')
expect(cliOutput).not.toInclude('webpack-internal')
})
}
)
})
it('should log the correct values on app-render error', async () => {
const outputIndex = next.cliOutput.length
await next.fetch('/')
await check(() => next.cliOutput.slice(outputIndex), /at Page/)
const cliOutput = next.cliOutput.slice(outputIndex)
await check(() => cliOutput, /digest:/)
expect(cliOutput).toInclude('Error: boom')
expect(cliOutput).toInclude('at fn2 (./app/fn.ts')
expect(cliOutput).toMatch(/at (Module\.)?fn1 \(\.\/app\/fn\.ts/)
expect(cliOutput).toInclude('at Page (./app/page.tsx')
expect(cliOutput).not.toInclude('webpack-internal')
})
it('should log the correct values on app-render error with edge runtime', async () => {
const outputIndex = next.cliOutput.length
await next.fetch('/edge')
await check(() => next.cliOutput.slice(outputIndex), /at EdgePage/)
const cliOutput = next.cliOutput.slice(outputIndex)
await check(() => cliOutput, /digest:/)
expect(cliOutput).toInclude('Error: boom')
expect(cliOutput).toInclude('at fn2 (./app/fn.ts')
expect(cliOutput).toMatch(/at (Module\.)?fn1 \(\.\/app\/fn\.ts/)
expect(cliOutput).toInclude('at EdgePage (./app/edge/page.tsx')
expect(cliOutput).not.toInclude('webpack-internal')
})
})
import { join } from 'path'
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'asset-prefix',
{
describe('asset-prefix', () => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixture'),
},
({ next }) => {
it('should load the app properly without reloading', async () => {
const browser = await next.browser('/')
await browser.eval(`window.__v = 1`)
})
expect(await browser.elementByCss('div').text()).toBe('Hello World')
it('should load the app properly without reloading', async () => {
const browser = await next.browser('/')
await browser.eval(`window.__v = 1`)
await check(async () => {
const logs = await browser.log()
const hasError = logs.some((log) =>
log.message.includes('Failed to fetch')
)
return hasError ? 'error' : 'success'
}, 'success')
expect(await browser.elementByCss('div').text()).toBe('Hello World')
expect(await browser.eval(`window.__v`)).toBe(1)
})
}
)
await check(async () => {
const logs = await browser.log()
const hasError = logs.some((log) =>
log.message.includes('Failed to fetch')
)
return hasError ? 'error' : 'success'
}, 'success')
expect(await browser.eval(`window.__v`)).toBe(1)
})
})
import { join } from 'path'
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { hasRedbox } from 'next-test-utils'
// Skipped in Turbopack, will be added later.
;(process.env.TURBOPACK ? describe.skip : describe)(
'Skipped in Turbopack',
() => {
createNextDescribe(
'optimizePackageImports - mui',
{
describe('optimizePackageImports - mui', () => {
const { next } = nextTestSetup({
env: {
NEXT_TEST_MODE: '1',
},
......@@ -18,31 +18,30 @@ import { hasRedbox } from 'next-test-utils'
'@emotion/react': '11.11.1',
'@emotion/styled': '11.11.0',
},
},
({ next }) => {
it('should support MUI', async () => {
let logs = ''
next.on('stdout', (log) => {
logs += log
})
})
it('should support MUI', async () => {
let logs = ''
next.on('stdout', (log) => {
logs += log
})
// Ensure that MUI is working
const $ = await next.render$('/mui')
expect(await $('#button').text()).toContain('button')
expect(await $('#typography').text()).toContain('typography')
// Ensure that MUI is working
const $ = await next.render$('/mui')
expect(await $('#button').text()).toContain('button')
expect(await $('#typography').text()).toContain('typography')
const browser = await next.browser('/mui')
expect(await hasRedbox(browser)).toBe(false)
const browser = await next.browser('/mui')
expect(await hasRedbox(browser)).toBe(false)
const modules = [...logs.matchAll(/\((\d+) modules\)/g)]
expect(modules.length).toBeGreaterThanOrEqual(1)
for (const [, moduleCount] of modules) {
// Ensure that the number of modules is less than 1500 - otherwise we're
// importing the entire library.
expect(parseInt(moduleCount)).toBeLessThan(1500)
}
})
}
)
const modules = [...logs.matchAll(/\((\d+) modules\)/g)]
expect(modules.length).toBeGreaterThanOrEqual(1)
for (const [, moduleCount] of modules) {
// Ensure that the number of modules is less than 1500 - otherwise we're
// importing the entire library.
expect(parseInt(moduleCount)).toBeLessThan(1500)
}
})
})
}
)
import { join } from 'path'
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { hasRedbox } from 'next-test-utils'
createNextDescribe(
'optimizePackageImports - mui',
{
describe('optimizePackageImports - mui', () => {
const { next } = nextTestSetup({
env: {
NEXT_TEST_MODE: '1',
},
......@@ -16,12 +15,11 @@ createNextDescribe(
'@remixicon/react': '^4.2.0',
'@tremor/react': '^3.14.1',
},
},
({ next }) => {
it('should work', async () => {
// Without barrel optimization, the reproduction breaks.
const browser = await next.browser('/')
expect(await hasRedbox(browser)).toBe(false)
})
}
)
})
it('should work', async () => {
// Without barrel optimization, the reproduction breaks.
const browser = await next.browser('/')
expect(await hasRedbox(browser)).toBe(false)
})
})
import { join } from 'path'
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
// Skipped in Turbopack, will be added later.
;(process.env.TURBOPACK ? describe.skip : describe)(
'Skipped in Turbopack',
() => {
createNextDescribe(
'optimizePackageImports - basic',
{
describe('optimizePackageImports - basic', () => {
const { next } = nextTestSetup({
env: {
NEXT_TEST_MODE: '1',
},
......@@ -18,114 +17,113 @@ import { createNextDescribe } from 'e2e-utils'
'@visx/visx': '3.3.0',
'recursive-barrel': '1.0.0',
},
},
({ next }) => {
it('app - should render the icons correctly without creating all the modules', async () => {
let logs = ''
next.on('stdout', (log) => {
logs += log
})
const html = await next.render('/')
// Ensure the icons are rendered
expect(html).toContain('<svg xmlns="http://www.w3.org/2000/svg"')
const modules = [
...logs.matchAll(
/Compiled (\/[\w-]*)*\s*in \d+(\.\d+)?(s|ms) \((\d+) modules\)/g
),
]
expect(modules.length).toBeGreaterThanOrEqual(1)
for (const [, , , , moduleCount] of modules) {
// Ensure that the number of modules is less than 1000 - otherwise we're
// importing the entire library.
expect(parseInt(moduleCount)).toBeLessThan(1000)
}
})
})
it('pages - should render the icons correctly without creating all the modules', async () => {
let logs = ''
next.on('stdout', (log) => {
logs += log
})
const html = await next.render('/pages-route')
// Ensure the icons are rendered
expect(html).toContain('<svg xmlns="http://www.w3.org/2000/svg"')
const modules = [
...logs.matchAll(
/Compiled (\/[\w-]+)*\s*in \d+(\.\d+)?(s|ms) \((\d+) modules\)/g
),
]
expect(modules.length).toBeGreaterThanOrEqual(1)
for (const [, , , , moduleCount] of modules) {
// Ensure that the number of modules is less than 1000 - otherwise we're
// importing the entire library.
expect(parseInt(moduleCount)).toBeLessThan(1000)
}
it('app - should render the icons correctly without creating all the modules', async () => {
let logs = ''
next.on('stdout', (log) => {
logs += log
})
it('app - should optimize recursive wildcard export mapping', async () => {
let logs = ''
next.on('stdout', (log) => {
logs += log
})
await next.render('/recursive-barrel-app')
const modules = [...logs.matchAll(/\((\d+) modules\)/g)]
expect(modules.length).toBeGreaterThanOrEqual(1)
for (const [, moduleCount] of modules) {
// Ensure that the number of modules is less than 1000 - otherwise we're
// importing the entire library.
expect(parseInt(moduleCount)).toBeLessThan(1000)
}
const html = await next.render('/')
// Ensure the icons are rendered
expect(html).toContain('<svg xmlns="http://www.w3.org/2000/svg"')
const modules = [
...logs.matchAll(
/Compiled (\/[\w-]*)*\s*in \d+(\.\d+)?(s|ms) \((\d+) modules\)/g
),
]
expect(modules.length).toBeGreaterThanOrEqual(1)
for (const [, , , , moduleCount] of modules) {
// Ensure that the number of modules is less than 1000 - otherwise we're
// importing the entire library.
expect(parseInt(moduleCount)).toBeLessThan(1000)
}
})
it('pages - should render the icons correctly without creating all the modules', async () => {
let logs = ''
next.on('stdout', (log) => {
logs += log
})
it('pages - should optimize recursive wildcard export mapping', async () => {
let logs = ''
next.on('stdout', (log) => {
logs += log
})
await next.render('/recursive-barrel')
const modules = [...logs.matchAll(/\((\d+) modules\)/g)]
expect(modules.length).toBeGreaterThanOrEqual(1)
for (const [, moduleCount] of modules) {
// Ensure that the number of modules is less than 1000 - otherwise we're
// importing the entire library.
expect(parseInt(moduleCount)).toBeLessThan(1000)
}
const html = await next.render('/pages-route')
// Ensure the icons are rendered
expect(html).toContain('<svg xmlns="http://www.w3.org/2000/svg"')
const modules = [
...logs.matchAll(
/Compiled (\/[\w-]+)*\s*in \d+(\.\d+)?(s|ms) \((\d+) modules\)/g
),
]
expect(modules.length).toBeGreaterThanOrEqual(1)
for (const [, , , , moduleCount] of modules) {
// Ensure that the number of modules is less than 1000 - otherwise we're
// importing the entire library.
expect(parseInt(moduleCount)).toBeLessThan(1000)
}
})
it('app - should optimize recursive wildcard export mapping', async () => {
let logs = ''
next.on('stdout', (log) => {
logs += log
})
it('should handle recursive wildcard exports', async () => {
const html = await next.render('/recursive')
expect(html).toContain('<h1>42</h1>')
})
await next.render('/recursive-barrel-app')
it('should support visx', async () => {
const html = await next.render('/visx')
expect(html).toContain('<linearGradient')
})
const modules = [...logs.matchAll(/\((\d+) modules\)/g)]
it('should not break "use client" directive in optimized packages', async () => {
const html = await next.render('/client')
expect(html).toContain('this is a client component')
})
expect(modules.length).toBeGreaterThanOrEqual(1)
for (const [, moduleCount] of modules) {
// Ensure that the number of modules is less than 1000 - otherwise we're
// importing the entire library.
expect(parseInt(moduleCount)).toBeLessThan(1000)
}
})
it('should support "use client" directive in barrel file', async () => {
const html = await next.render('/client-boundary')
expect(html).toContain('<button>0</button>')
it('pages - should optimize recursive wildcard export mapping', async () => {
let logs = ''
next.on('stdout', (log) => {
logs += log
})
}
)
await next.render('/recursive-barrel')
const modules = [...logs.matchAll(/\((\d+) modules\)/g)]
expect(modules.length).toBeGreaterThanOrEqual(1)
for (const [, moduleCount] of modules) {
// Ensure that the number of modules is less than 1000 - otherwise we're
// importing the entire library.
expect(parseInt(moduleCount)).toBeLessThan(1000)
}
})
it('should handle recursive wildcard exports', async () => {
const html = await next.render('/recursive')
expect(html).toContain('<h1>42</h1>')
})
it('should support visx', async () => {
const html = await next.render('/visx')
expect(html).toContain('<linearGradient')
})
it('should not break "use client" directive in optimized packages', async () => {
const html = await next.render('/client')
expect(html).toContain('this is a client component')
})
it('should support "use client" directive in barrel file', async () => {
const html = await next.render('/client-boundary')
expect(html).toContain('<button>0</button>')
})
})
}
)
import { join } from 'path'
import webdriver from 'next-webdriver'
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'useDefineForClassFields SWC option',
{
describe('useDefineForClassFields SWC option', () => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixture'),
dependencies: {
mobx: '6.3.7',
......@@ -14,67 +13,66 @@ createNextDescribe(
'@types/node': 'latest',
'mobx-react': '7.2.1',
},
},
({ next }) => {
it('tsx should compile with useDefineForClassFields enabled', async () => {
let browser
try {
browser = await webdriver(next.url, '/')
await browser.elementByCss('#action').click()
await check(
() => browser.elementByCss('#name').text(),
/this is my name: next/
)
} finally {
if (browser) {
await browser.close()
}
})
it('tsx should compile with useDefineForClassFields enabled', async () => {
let browser
try {
browser = await webdriver(next.url, '/')
await browser.elementByCss('#action').click()
await check(
() => browser.elementByCss('#name').text(),
/this is my name: next/
)
} finally {
if (browser) {
await browser.close()
}
})
}
})
it("Initializes resident to undefined after the call to 'super()' when with useDefineForClassFields enabled", async () => {
let browser
try {
browser = await webdriver(next.url, '/animal')
expect(await browser.elementByCss('#dog').text()).toBe('')
expect(await browser.elementByCss('#dogDecl').text()).toBe('dog')
} finally {
if (browser) {
await browser.close()
}
it("Initializes resident to undefined after the call to 'super()' when with useDefineForClassFields enabled", async () => {
let browser
try {
browser = await webdriver(next.url, '/animal')
expect(await browser.elementByCss('#dog').text()).toBe('')
expect(await browser.elementByCss('#dogDecl').text()).toBe('dog')
} finally {
if (browser) {
await browser.close()
}
})
}
})
async function matchLogs$(browser) {
let data_foundLog = false
let name_foundLog = false
async function matchLogs$(browser) {
let data_foundLog = false
let name_foundLog = false
const browserLogs = await browser.log('browser')
const browserLogs = await browser.log('browser')
browserLogs.forEach((log) => {
if (log.message.includes('data changed')) {
data_foundLog = true
}
if (log.message.includes('name changed')) {
name_foundLog = true
}
})
return [data_foundLog, name_foundLog]
}
it('set accessors from base classes won’t get triggered with useDefineForClassFields enabled', async () => {
let browser
try {
browser = await webdriver(next.url, '/derived')
await matchLogs$(browser).then(([data_foundLog, name_foundLog]) => {
expect(data_foundLog).toBe(true)
expect(name_foundLog).toBe(false)
})
} finally {
if (browser) {
await browser.close()
}
browserLogs.forEach((log) => {
if (log.message.includes('data changed')) {
data_foundLog = true
}
if (log.message.includes('name changed')) {
name_foundLog = true
}
})
return [data_foundLog, name_foundLog]
}
)
it('set accessors from base classes won’t get triggered with useDefineForClassFields enabled', async () => {
let browser
try {
browser = await webdriver(next.url, '/derived')
await matchLogs$(browser).then(([data_foundLog, name_foundLog]) => {
expect(data_foundLog).toBe(true)
expect(name_foundLog).toBe(false)
})
} finally {
if (browser) {
await browser.close()
}
}
})
})
import { join } from 'path'
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
createNextDescribe(
'emotion SWC option',
{
describe('emotion SWC option', () => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixture'),
dependencies: {
'@emotion/react': '11.10.4',
'@emotion/styled': '11.10.4',
'@emotion/cache': '11.10.3',
},
},
({ next }) => {
it('should have styling from the css prop', async () => {
const browser = await next.browser('/')
})
const color = await browser
.elementByCss('#test-element')
.getComputedCss('background-color')
expect(color).toBe('rgb(255, 192, 203)')
})
}
)
it('should have styling from the css prop', async () => {
const browser = await next.browser('/')
const color = await browser
.elementByCss('#test-element')
.getComputedCss('background-color')
expect(color).toBe('rgb(255, 192, 203)')
})
})
import webdriver from 'next-webdriver'
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { fetchViaHTTP, renderViaHTTP } from 'next-test-utils'
createNextDescribe(
'styled-components SWC transform',
{
describe('styled-components SWC transform', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
'styled-components': '5.3.3',
},
},
({ next }) => {
async function matchLogs$(browser) {
let foundLog = false
})
async function matchLogs$(browser) {
let foundLog = false
const browserLogs = await browser.log('browser')
const browserLogs = await browser.log('browser')
browserLogs.forEach((log) => {
if (log.message.includes('Warning: Prop `%s` did not match.')) {
foundLog = true
}
})
return foundLog
}
browserLogs.forEach((log) => {
if (log.message.includes('Warning: Prop `%s` did not match.')) {
foundLog = true
}
})
return foundLog
}
it('should not have hydration mismatch with styled-components transform enabled', async () => {
let browser
try {
browser = await webdriver(next.url, '/')
it('should not have hydration mismatch with styled-components transform enabled', async () => {
let browser
try {
browser = await webdriver(next.url, '/')
// Compile /_error
await fetchViaHTTP(next.url, '/404')
// Compile /_error
await fetchViaHTTP(next.url, '/404')
// Try 4 times to be sure there is no mismatch
expect(await matchLogs$(browser)).toBe(false)
await browser.refresh()
expect(await matchLogs$(browser)).toBe(false)
await browser.refresh()
expect(await matchLogs$(browser)).toBe(false)
await browser.refresh()
expect(await matchLogs$(browser)).toBe(false)
} finally {
if (browser) {
await browser.close()
}
// Try 4 times to be sure there is no mismatch
expect(await matchLogs$(browser)).toBe(false)
await browser.refresh()
expect(await matchLogs$(browser)).toBe(false)
await browser.refresh()
expect(await matchLogs$(browser)).toBe(false)
await browser.refresh()
expect(await matchLogs$(browser)).toBe(false)
} finally {
if (browser) {
await browser.close()
}
})
}
})
it('should render the page with correct styles', async () => {
const browser = await webdriver(next.url, '/')
it('should render the page with correct styles', async () => {
const browser = await webdriver(next.url, '/')
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('#btn')).color`
)
).toBe('rgb(255, 255, 255)')
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('#wrap-div')).color`
)
).toBe('rgb(0, 0, 0)')
})
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('#btn')).color`
)
).toBe('rgb(255, 255, 255)')
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('#wrap-div')).color`
)
).toBe('rgb(0, 0, 0)')
})
it('should enable the display name transform by default', async () => {
// make sure the index chunk gets generated
const html = await next.render('/')
expect(html).toContain('pages__Button')
})
it('should enable the display name transform by default', async () => {
// make sure the index chunk gets generated
const html = await next.render('/')
expect(html).toContain('pages__Button')
})
it('should contain styles in initial HTML', async () => {
const html = await renderViaHTTP(next.url, '/')
expect(html).toContain('background:transparent')
expect(html).toContain('color:white')
})
it('should contain styles in initial HTML', async () => {
const html = await renderViaHTTP(next.url, '/')
expect(html).toContain('background:transparent')
expect(html).toContain('color:white')
})
it('should only render once on the server per request', async () => {
const outputs = []
next.on('stdout', (args) => {
outputs.push(args)
})
await renderViaHTTP(next.url, '/')
expect(
outputs.filter((output) => output.trim() === '__render__').length
).toBe(1)
it('should only render once on the server per request', async () => {
const outputs = []
next.on('stdout', (args) => {
outputs.push(args)
})
}
)
await renderViaHTTP(next.url, '/')
expect(
outputs.filter((output) => output.trim() === '__render__').length
).toBe(1)
})
})
import { join } from 'path'
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
createNextDescribe(
'theme-ui SWC option',
{
describe('theme-ui SWC option', () => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixture'),
dependencies: {
'theme-ui': '0.12.0',
},
},
({ next }) => {
it('should have theme provided styling', async () => {
const browser = await next.browser('/')
const color = await browser.elementByCss('#hello').getComputedCss('color')
expect(color).toBe('rgb(51, 51, 238)')
})
}
)
})
it('should have theme provided styling', async () => {
const browser = await next.browser('/')
const color = await browser.elementByCss('#hello').getComputedCss('color')
expect(color).toBe('rgb(51, 51, 238)')
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
createNextDescribe(
'Handles Duplicate Pages',
{
describe('Handles Duplicate Pages', () => {
const { next } = nextTestSetup({
files: __dirname,
},
({ next }) => {
it('Shows warning in development', async () => {
await next.render('/hello')
expect(next.cliOutput).toMatch(/Duplicate page detected/)
})
}
)
})
it('Shows warning in development', async () => {
await next.render('/hello')
expect(next.cliOutput).toMatch(/Duplicate page detected/)
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import https from 'https'
import { renderViaHTTP, shouldRunTurboDevTest } from 'next-test-utils'
createNextDescribe(
'experimental-https-server (generated certificate)',
{
describe('experimental-https-server (generated certificate)', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
startCommand: `pnpm next ${
shouldRunTurboDevTest() ? 'dev --turbo' : 'dev'
} --experimental-https`,
skipStart: !process.env.CI,
},
({ next }) => {
if (!process.env.CI) {
console.warn('only runs on CI as it requires administrator privileges')
it('only runs on CI as it requires administrator privileges', () => {})
return
}
})
if (skipped) return
const agent = new https.Agent({
rejectUnauthorized: false,
})
if (!process.env.CI) {
console.warn('only runs on CI as it requires administrator privileges')
it('only runs on CI as it requires administrator privileges', () => {})
return
}
it('should successfully load the app in app dir', async () => {
expect(next.url).toInclude('https://')
const html = await renderViaHTTP(next.url, '/1', undefined, { agent })
expect(html).toContain('Hello from App')
})
const agent = new https.Agent({
rejectUnauthorized: false,
})
it('should successfully load the app in pages dir', async () => {
expect(next.url).toInclude('https://')
const html = await renderViaHTTP(next.url, '/2', undefined, { agent })
expect(html).toContain('Hello from Pages')
})
}
)
it('should successfully load the app in app dir', async () => {
expect(next.url).toInclude('https://')
const html = await renderViaHTTP(next.url, '/1', undefined, { agent })
expect(html).toContain('Hello from App')
})
it('should successfully load the app in pages dir', async () => {
expect(next.url).toInclude('https://')
const html = await renderViaHTTP(next.url, '/2', undefined, { agent })
expect(html).toContain('Hello from Pages')
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import https from 'https'
import { renderViaHTTP, shouldRunTurboDevTest } from 'next-test-utils'
createNextDescribe(
'experimental-https-server (provided certificate)',
{
describe('experimental-https-server (provided certificate)', () => {
const { next } = nextTestSetup({
files: __dirname,
startCommand: `pnpm next ${
shouldRunTurboDevTest() ? 'dev --turbo' : 'dev'
} --experimental-https --experimental-https-key ./certificates/localhost-key.pem --experimental-https-cert ./certificates/localhost.pem`,
},
({ next }) => {
const agent = new https.Agent({
rejectUnauthorized: false,
})
})
const agent = new https.Agent({
rejectUnauthorized: false,
})
it('should successfully load the app in app dir', async () => {
expect(next.url).toInclude('https://')
const html = await renderViaHTTP(next.url, '/1', undefined, { agent })
expect(html).toContain('Hello from App')
})
it('should successfully load the app in app dir', async () => {
expect(next.url).toInclude('https://')
const html = await renderViaHTTP(next.url, '/1', undefined, { agent })
expect(html).toContain('Hello from App')
})
it('should successfully load the app in pages dir', async () => {
expect(next.url).toInclude('https://')
const html = await renderViaHTTP(next.url, '/2', undefined, { agent })
expect(html).toContain('Hello from Pages')
})
}
)
it('should successfully load the app in pages dir', async () => {
expect(next.url).toInclude('https://')
const html = await renderViaHTTP(next.url, '/2', undefined, { agent })
expect(html).toContain('Hello from Pages')
})
})
/* eslint-env jest */
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'Deprecated @next/font warning',
{
describe('Deprecated @next/font warning', () => {
const { next, skipped } = nextTestSetup({
files: {
'pages/index.js': '',
},
......@@ -14,34 +13,34 @@ createNextDescribe(
'@next/font': 'canary',
},
skipStart: true,
},
({ next }) => {
it('should warn if @next/font is in deps', async () => {
await next.start()
await check(() => next.cliOutput, /ready/i)
await check(
() => next.cliOutput,
new RegExp('please use the built-in `next/font` instead')
)
})
if (skipped) return
await next.stop()
await next.clean()
})
it('should warn if @next/font is in deps', async () => {
await next.start()
await check(() => next.cliOutput, /ready/i)
await check(
() => next.cliOutput,
new RegExp('please use the built-in `next/font` instead')
)
it('should not warn if @next/font is not in deps', async () => {
// Remove @next/font from deps
const packageJson = JSON.parse(await next.readFile('package.json'))
delete packageJson.dependencies['@next/font']
await next.patchFile('package.json', JSON.stringify(packageJson))
await next.stop()
await next.clean()
})
await next.start()
await check(() => next.cliOutput, /ready/i)
expect(next.cliOutput).not.toInclude(
'please use the built-in `next/font` instead'
)
it('should not warn if @next/font is not in deps', async () => {
// Remove @next/font from deps
const packageJson = JSON.parse(await next.readFile('package.json'))
delete packageJson.dependencies['@next/font']
await next.patchFile('package.json', JSON.stringify(packageJson))
await next.stop()
await next.clean()
})
}
)
await next.start()
await check(() => next.cliOutput, /ready/i)
expect(next.cliOutput).not.toInclude(
'please use the built-in `next/font` instead'
)
await next.stop()
await next.clean()
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'custom-app-hmr',
{
describe('custom-app-hmr', () => {
const { next } = nextTestSetup({
files: __dirname,
},
({ next }) => {
it('should not do full reload when simply editing _app.js', async () => {
const customAppFilePath = 'pages/_app.js'
const browser = await next.browser('/')
await browser.eval('window.hmrConstantValue = "should-not-change"')
const customAppContent = await next.readFile(customAppFilePath)
const newCustomAppContent = customAppContent.replace(
'hmr text origin',
'hmr text changed'
)
await next.patchFile(customAppFilePath, newCustomAppContent)
await check(async () => {
const pText = await browser.elementByCss('h1').text()
expect(pText).toBe('hmr text changed')
// Should keep the value on window, which indicates there's no full reload
const hmrConstantValue = await browser.eval('window.hmrConstantValue')
expect(hmrConstantValue).toBe('should-not-change')
return 'success'
}, 'success')
await next.patchFile(customAppFilePath, customAppContent)
await check(async () => {
const pText = await browser.elementByCss('h1').text()
expect(pText).toBe('hmr text origin')
// Should keep the value on window, which indicates there's no full reload
const hmrConstantValue = await browser.eval('window.hmrConstantValue')
expect(hmrConstantValue).toBe('should-not-change')
return 'success'
}, 'success')
})
}
)
})
it('should not do full reload when simply editing _app.js', async () => {
const customAppFilePath = 'pages/_app.js'
const browser = await next.browser('/')
await browser.eval('window.hmrConstantValue = "should-not-change"')
const customAppContent = await next.readFile(customAppFilePath)
const newCustomAppContent = customAppContent.replace(
'hmr text origin',
'hmr text changed'
)
await next.patchFile(customAppFilePath, newCustomAppContent)
await check(async () => {
const pText = await browser.elementByCss('h1').text()
expect(pText).toBe('hmr text changed')
// Should keep the value on window, which indicates there's no full reload
const hmrConstantValue = await browser.eval('window.hmrConstantValue')
expect(hmrConstantValue).toBe('should-not-change')
return 'success'
}, 'success')
await next.patchFile(customAppFilePath, customAppContent)
await check(async () => {
const pText = await browser.elementByCss('h1').text()
expect(pText).toBe('hmr text origin')
// Should keep the value on window, which indicates there's no full reload
const hmrConstantValue = await browser.eval('window.hmrConstantValue')
expect(hmrConstantValue).toBe('should-not-change')
return 'success'
}, 'success')
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import fs from 'fs-extra'
import { hasRedbox } from 'next-test-utils'
import path from 'path'
createNextDescribe(
'repeated-dev-edits',
{
describe('repeated-dev-edits', () => {
const { next } = nextTestSetup({
files: __dirname,
},
({ next }) => {
// Recommended for tests that check HTML. Cheerio is a HTML parser that has a jQuery like API.
it('should not break the hydration ', async () => {
const browser = await next.browser('/')
expect(await browser.elementByCss('p').text()).toBe('version-1')
const pagePath = 'pages/index.tsx'
const pageContent = String(
await fs.readFile(path.join(__dirname, pagePath))
)
await next.patchFile(
pagePath,
pageContent.replaceAll('version-1', 'version-2')
)
await browser.waitForElementByCss('#version-2')
expect(await browser.elementByCss('p').text()).toBe('version-2')
// Verify no hydration mismatch:
expect(await hasRedbox(browser)).toBeFalse()
await next.patchFile(
pagePath,
pageContent.replaceAll('version-1', 'version-3')
)
await browser.waitForElementByCss('#version-3')
expect(await browser.elementByCss('p').text()).toBe('version-3')
// Verify no hydration mismatch:
expect(await hasRedbox(browser)).toBeFalse()
await browser.refresh()
// Verify no hydration mismatch:
expect(await hasRedbox(browser)).toBeFalse()
})
}
)
})
// Recommended for tests that check HTML. Cheerio is a HTML parser that has a jQuery like API.
it('should not break the hydration ', async () => {
const browser = await next.browser('/')
expect(await browser.elementByCss('p').text()).toBe('version-1')
const pagePath = 'pages/index.tsx'
const pageContent = String(
await fs.readFile(path.join(__dirname, pagePath))
)
await next.patchFile(
pagePath,
pageContent.replaceAll('version-1', 'version-2')
)
await browser.waitForElementByCss('#version-2')
expect(await browser.elementByCss('p').text()).toBe('version-2')
// Verify no hydration mismatch:
expect(await hasRedbox(browser)).toBeFalse()
await next.patchFile(
pagePath,
pageContent.replaceAll('version-1', 'version-3')
)
await browser.waitForElementByCss('#version-3')
expect(await browser.elementByCss('p').text()).toBe('version-3')
// Verify no hydration mismatch:
expect(await hasRedbox(browser)).toBeFalse()
await browser.refresh()
// Verify no hydration mismatch:
expect(await hasRedbox(browser)).toBeFalse()
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import { join } from 'path'
createNextDescribe(
'watch-config-file',
{
describe('watch-config-file', () => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixture'),
},
({ next }) => {
it('should output config file change', async () => {
await check(async () => next.cliOutput, /ready/i)
})
it('should output config file change', async () => {
await check(async () => next.cliOutput, /ready/i)
await check(async () => {
await next.patchFile(
'next.config.js',
`
await check(async () => {
await next.patchFile(
'next.config.js',
`
console.log(${Date.now()})
const nextConfig = {
reactStrictMode: true,
......@@ -28,11 +27,10 @@ createNextDescribe(
},
}
module.exports = nextConfig`
)
return next.cliOutput
}, /Found a change in next\.config\.js\. Restarting the server to apply the changes\.\.\./)
)
return next.cliOutput
}, /Found a change in next\.config\.js\. Restarting the server to apply the changes\.\.\./)
await check(() => next.fetch('/about').then((res) => res.status), 200)
})
}
)
await check(() => next.fetch('/about').then((res) => res.status), 200)
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
createNextDescribe(
'app-dir edge runtime config',
{
describe('app-dir edge runtime config', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
},
({ next, isNextDev }) => {
it('should warn the legacy object config export', async () => {
let error
await next.start().catch((err) => {
error = err
})
if (isNextDev) {
expect(error).not.toBeDefined()
await next.fetch('/legacy-runtime-config')
} else {
expect(error).toBeDefined()
}
})
expect(next.cliOutput).toContain('Page config in ')
expect(next.cliOutput).toContain(
// the full path is more complex, we only care about this part
'app/legacy-runtime-config/page.js is deprecated. Replace `export const config=…` with the following:'
)
expect(next.cliOutput).toContain('- `export const runtime = "edge"`')
expect(next.cliOutput).toContain(
'- `export const preferredRegion = ["us-east-1"]`'
)
})
if (skipped) {
return
}
)
it('should warn the legacy object config export', async () => {
let error
await next.start().catch((err) => {
error = err
})
if (isNextDev) {
expect(error).not.toBeDefined()
await next.fetch('/legacy-runtime-config')
} else {
expect(error).toBeDefined()
}
expect(next.cliOutput).toContain('Page config in ')
expect(next.cliOutput).toContain(
// the full path is more complex, we only care about this part
'app/legacy-runtime-config/page.js is deprecated. Replace `export const config=…` with the following:'
)
expect(next.cliOutput).toContain('- `export const runtime = "edge"`')
expect(next.cliOutput).toContain(
'- `export const preferredRegion = ["us-east-1"]`'
)
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
createNextDescribe(
'_allow-underscored-root-directory',
{
describe('_allow-underscored-root-directory', () => {
const { next } = nextTestSetup({
files: __dirname,
},
({ next }) => {
it('should not serve app path with underscore', async () => {
const res = await next.fetch('/_handlers')
expect(res.status).toBe(404)
})
})
it('should not serve app path with underscore', async () => {
const res = await next.fetch('/_handlers')
expect(res.status).toBe(404)
})
it('should pages path with a underscore at the root', async () => {
const res = await next.fetch('/')
await expect(res.text()).resolves.toBe('Hello, world!')
})
it('should pages path with a underscore at the root', async () => {
const res = await next.fetch('/')
await expect(res.text()).resolves.toBe('Hello, world!')
})
it('should serve app path with %5F', async () => {
const res = await next.fetch('/_routable-folder')
await expect(res.text()).resolves.toBe('Hello, world!')
})
}
)
it('should serve app path with %5F', async () => {
const res = await next.fetch('/_routable-folder')
await expect(res.text()).resolves.toBe('Hello, world!')
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import { join } from 'path'
createNextDescribe(
'app-dir action allowed origins',
{
describe('app-dir action allowed origins', () => {
const { next, skipped } = nextTestSetup({
files: join(__dirname, 'safe-origins'),
skipDeployment: true,
dependencies: {
......@@ -14,16 +13,19 @@ createNextDescribe(
},
// An arbitrary & random port.
forcedPort: '41831',
},
({ next }) => {
it('should pass if localhost is set as a safe origin', async function () {
const browser = await next.browser('/')
})
await browser.elementByCss('button').click()
await check(async () => {
return await browser.elementByCss('#res').text()
}, 'hi')
})
if (skipped) {
return
}
)
it('should pass if localhost is set as a safe origin', async function () {
const browser = await next.browser('/')
await browser.elementByCss('button').click()
await check(async () => {
return await browser.elementByCss('#res').text()
}, 'hi')
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import { join } from 'path'
createNextDescribe(
'app-dir action disallowed origins',
{
describe('app-dir action disallowed origins', () => {
const { next, skipped } = nextTestSetup({
files: join(__dirname, 'unsafe-origins'),
skipDeployment: true,
dependencies: {
......@@ -12,22 +11,25 @@ createNextDescribe(
'react-dom': 'latest',
'server-only': 'latest',
},
},
({ next }) => {
// Origin should be localhost
it('should error if x-forwarded-host does not match the origin', async function () {
const browser = await next.browser('/')
})
await browser.elementByCss('button').click()
await check(async () => {
const t = await browser.elementByCss('#res').text()
return t.includes('Invalid Server Actions request.') ||
// In prod the message is hidden
t.includes('An error occurred in the Server Components render.')
? 'yes'
: 'no'
}, 'yes')
})
if (skipped) {
return
}
)
// Origin should be localhost
it('should error if x-forwarded-host does not match the origin', async function () {
const browser = await next.browser('/')
await browser.elementByCss('button').click()
await check(async () => {
const t = await browser.elementByCss('#res').text()
return t.includes('Invalid Server Actions request.') ||
// In prod the message is hidden
t.includes('An error occurred in the Server Components render.')
? 'yes'
: 'no'
}, 'yes')
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check, waitFor } from 'next-test-utils'
createNextDescribe(
'app-dir action handling',
{
describe('app-dir action handling', () => {
const { next } = nextTestSetup({
files: __dirname,
},
({ next }) => {
it('should handle actions correctly after navigation / redirection events', async () => {
const browser = await next.browser('/')
})
await browser.elementByCss('#middleware-redirect').click()
it('should handle actions correctly after navigation / redirection events', async () => {
const browser = await next.browser('/')
expect(await browser.elementByCss('#form').text()).not.toContain(
'Loading...'
)
await browser.elementByCss('#middleware-redirect').click()
await browser.elementByCss('#submit').click()
expect(await browser.elementByCss('#form').text()).not.toContain(
'Loading...'
)
await check(() => {
return browser.elementByCss('#form').text()
}, /Loading.../)
await browser.elementByCss('#submit').click()
// wait for 2 seconds, since the action takes a second to resolve
await waitFor(2000)
await check(() => {
return browser.elementByCss('#form').text()
}, /Loading.../)
expect(await browser.elementByCss('#form').text()).not.toContain(
'Loading...'
)
// wait for 2 seconds, since the action takes a second to resolve
await waitFor(2000)
expect(await browser.elementByCss('#result').text()).toContain(
'RESULT FROM SERVER ACTION'
)
})
expect(await browser.elementByCss('#form').text()).not.toContain(
'Loading...'
)
it('should handle actions correctly after following a relative link', async () => {
const browser = await next.browser('/nested-folder/products')
expect(await browser.elementByCss('#result').text()).toContain(
'RESULT FROM SERVER ACTION'
)
})
await browser.elementByCss('a').click()
it('should handle actions correctly after following a relative link', async () => {
const browser = await next.browser('/nested-folder/products')
await browser.elementByCss('button').click()
await browser.elementByCss('a').click()
await check(() => {
return (next.cliOutput.match(/addToCart/g) || []).length
}, 1)
})
}
)
await browser.elementByCss('button').click()
await check(() => {
return (next.cliOutput.match(/addToCart/g) || []).length
}, 1)
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
createNextDescribe(
'app-dir action handling - next export',
{
describe('app-dir action handling - next export', () => {
const { next, isNextStart, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
......@@ -11,32 +10,32 @@ createNextDescribe(
'react-dom': 'latest',
'server-only': 'latest',
},
},
({ next, isNextStart }) => {
if (!isNextStart) {
it('skip test for development mode', () => {})
return
}
})
if (skipped) return
beforeAll(async () => {
await next.stop()
await next.patchFile(
'next.config.js',
`
if (!isNextStart) {
it('skip test for development mode', () => {})
return
}
beforeAll(async () => {
await next.stop()
await next.patchFile(
'next.config.js',
`
module.exports = {
output: 'export'
}
`
)
try {
await next.start()
} catch {}
})
)
try {
await next.start()
} catch {}
})
it('should error when use export output for server actions', async () => {
expect(next.cliOutput).toContain(
`Server Actions are not supported with static export.`
)
})
}
)
it('should error when use export output for server actions', async () => {
expect(next.cliOutput).toContain(
`Server Actions are not supported with static export.`
)
})
})
/* eslint-disable jest/no-standalone-expect */
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'app-dir action useFormState',
{
describe('app-dir action useFormState', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
react: 'latest',
'react-dom': 'latest',
},
},
({ next }) => {
it('should support submitting form state with JS', async () => {
const browser = await next.browser('/client/form-state')
})
it('should support submitting form state with JS', async () => {
const browser = await next.browser('/client/form-state')
await browser.eval(`document.getElementById('name-input').value = 'test'`)
await browser.elementByCss('#submit-form').click()
await browser.eval(`document.getElementById('name-input').value = 'test'`)
await browser.elementByCss('#submit-form').click()
await check(() => {
return browser.elementByCss('#form-state').text()
}, 'initial-state:test')
await check(() => {
return browser.elementByCss('#form-state').text()
}, 'initial-state:test')
})
it('should support submitting form state without JS', async () => {
const browser = await next.browser('/client/form-state', {
disableJavaScript: true,
})
it('should support submitting form state without JS', async () => {
const browser = await next.browser('/client/form-state', {
disableJavaScript: true,
})
await browser.eval(`document.getElementById('name-input').value = 'test'`)
await browser.elementByCss('#submit-form').click()
await browser.eval(`document.getElementById('name-input').value = 'test'`)
await browser.elementByCss('#submit-form').click()
// It should inline the form state into HTML so it can still be hydrated.
await check(() => {
return browser.elementByCss('#form-state').text()
}, 'initial-state:test')
})
// It should inline the form state into HTML so it can still be hydrated.
await check(() => {
return browser.elementByCss('#form-state').text()
}, 'initial-state:test')
})
it('should support hydrating the app from progressively enhanced form request', async () => {
const browser = await next.browser('/client/form-state')
it('should support hydrating the app from progressively enhanced form request', async () => {
const browser = await next.browser('/client/form-state')
// Simulate a progressively enhanced form request
await browser.eval(`document.getElementById('name-input').value = 'test'`)
await browser.eval(`document.getElementById('form-state-form').submit()`)
// Simulate a progressively enhanced form request
await browser.eval(`document.getElementById('name-input').value = 'test'`)
await browser.eval(`document.getElementById('form-state-form').submit()`)
await check(() => {
return browser.elementByCss('#form-state').text()
}, 'initial-state:test')
await check(() => {
return browser.elementByCss('#form-state').text()
}, 'initial-state:test')
// Should hydrate successfully
await check(() => {
return browser.elementByCss('#hydrated').text()
}, 'hydrated')
})
// Should hydrate successfully
await check(() => {
return browser.elementByCss('#hydrated').text()
}, 'hydrated')
it('should send the action to the provided permalink with form state when JS disabled', async () => {
const browser = await next.browser('/client/form-state/page-2', {
disableJavaScript: true,
})
it('should send the action to the provided permalink with form state when JS disabled', async () => {
const browser = await next.browser('/client/form-state/page-2', {
disableJavaScript: true,
})
// Simulate a progressively enhanced form request
await browser.eval(
`document.getElementById('name-input').value = 'test-permalink'`
)
await browser.eval(`document.getElementById('form-state-form').submit()`)
// Simulate a progressively enhanced form request
await browser.eval(
`document.getElementById('name-input').value = 'test-permalink'`
)
await browser.eval(`document.getElementById('form-state-form').submit()`)
await check(() => {
return browser.elementByCss('#form-state').text()
}, 'initial-state:test-permalink')
})
}
)
await check(() => {
return browser.elementByCss('#form-state').text()
}, 'initial-state:test-permalink')
})
})
/* eslint-disable jest/no-standalone-expect */
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import type { Response } from 'playwright'
createNextDescribe(
'app-dir action progressive enhancement',
{
describe('app-dir action progressive enhancement', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
react: 'latest',
......@@ -13,46 +12,43 @@ createNextDescribe(
'react-dom': 'latest',
'server-only': 'latest',
},
},
({ next }) => {
it('should support formData and redirect without JS', async () => {
let responseCode
const browser = await next.browser('/server', {
disableJavaScript: true,
beforePageLoad(page) {
page.on('response', (response: Response) => {
const url = new URL(response.url())
const status = response.status()
if (url.pathname.includes('/server')) {
responseCode = status
}
})
},
})
await browser.eval(`document.getElementById('name').value = 'test'`)
await browser.elementByCss('#submit').click()
await check(() => {
return browser.eval('window.location.pathname + window.location.search')
}, '/header?name=test&hidden-info=hi')
expect(responseCode).toBe(303)
})
it('should support formData and redirect without JS', async () => {
let responseCode
const browser = await next.browser('/server', {
disableJavaScript: true,
beforePageLoad(page) {
page.on('response', (response: Response) => {
const url = new URL(response.url())
const status = response.status()
if (url.pathname.includes('/server')) {
responseCode = status
}
})
},
})
it('should support actions from client without JS', async () => {
const browser = await next.browser('/server', {
disableJavaScript: true,
})
await browser.eval(`document.getElementById('name').value = 'test'`)
await browser.elementByCss('#submit').click()
await check(() => {
return browser.eval('window.location.pathname + window.location.search')
}, '/header?name=test&hidden-info=hi')
await browser.eval(
`document.getElementById('client-name').value = 'test'`
)
await browser.elementByCss('#there').click()
expect(responseCode).toBe(303)
})
await check(() => {
return browser.eval('window.location.pathname + window.location.search')
}, '/header?name=test&hidden-info=hi')
it('should support actions from client without JS', async () => {
const browser = await next.browser('/server', {
disableJavaScript: true,
})
}
)
await browser.eval(`document.getElementById('client-name').value = 'test'`)
await browser.elementByCss('#there').click()
await check(() => {
return browser.eval('window.location.pathname + window.location.search')
}, '/header?name=test&hidden-info=hi')
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { accountForOverhead } from './account-for-overhead'
const CONFIG_ERROR =
'Server Actions Size Limit must be a valid number or filesize format larger than 1MB'
createNextDescribe(
'app-dir action size limit invalid config',
{
describe('app-dir action size limit invalid config', () => {
const { next, isNextStart, isNextDeploy, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
skipStart: true,
......@@ -16,143 +15,143 @@ createNextDescribe(
'react-dom': 'latest',
'server-only': 'latest',
},
},
({ next, isNextStart, isNextDeploy }) => {
if (!isNextStart) {
it('skip test for development mode', () => {})
return
}
})
if (skipped) return
const logs: string[] = []
if (!isNextStart) {
it('skip test for development mode', () => {})
return
}
beforeAll(() => {
const onLog = (log: string) => {
logs.push(log.trim())
}
const logs: string[] = []
next.on('stdout', onLog)
next.on('stderr', onLog)
})
beforeAll(() => {
const onLog = (log: string) => {
logs.push(log.trim())
}
afterEach(async () => {
logs.length = 0
next.on('stdout', onLog)
next.on('stderr', onLog)
})
await next.stop()
})
afterEach(async () => {
logs.length = 0
it('should error if serverActions.bodySizeLimit config is a negative number', async function () {
await next.patchFile(
'next.config.js',
`
await next.stop()
})
it('should error if serverActions.bodySizeLimit config is a negative number', async function () {
await next.patchFile(
'next.config.js',
`
module.exports = {
experimental: {
serverActions: { bodySizeLimit: -3000 }
},
}
`
)
try {
await next.start()
} catch {}
expect(next.cliOutput).toContain(CONFIG_ERROR)
})
it('should error if serverActions.bodySizeLimit config is invalid', async function () {
await next.patchFile(
'next.config.js',
`
)
try {
await next.start()
} catch {}
expect(next.cliOutput).toContain(CONFIG_ERROR)
})
it('should error if serverActions.bodySizeLimit config is invalid', async function () {
await next.patchFile(
'next.config.js',
`
module.exports = {
experimental: {
serverActions: { bodySizeLimit: 'testmb' }
},
}
`
)
try {
await next.start()
} catch {}
expect(next.cliOutput).toContain(CONFIG_ERROR)
})
it('should error if serverActions.bodySizeLimit config is a negative size', async function () {
await next.patchFile(
'next.config.js',
`
)
try {
await next.start()
} catch {}
expect(next.cliOutput).toContain(CONFIG_ERROR)
})
it('should error if serverActions.bodySizeLimit config is a negative size', async function () {
await next.patchFile(
'next.config.js',
`
module.exports = {
experimental: {
serverActions: { bodySizeLimit: '-3000mb' }
},
}
`
)
try {
await next.start()
} catch {}
expect(next.cliOutput).toContain(CONFIG_ERROR)
})
if (!isNextDeploy) {
it('should respect the size set in serverActions.bodySizeLimit', async function () {
await next.patchFile(
'next.config.js',
`
)
try {
await next.start()
} catch {}
expect(next.cliOutput).toContain(CONFIG_ERROR)
})
if (!isNextDeploy) {
it('should respect the size set in serverActions.bodySizeLimit', async function () {
await next.patchFile(
'next.config.js',
`
module.exports = {
experimental: {
serverActions: { bodySizeLimit: '1.5mb' }
},
}
`
)
await next.start()
)
await next.start()
const browser = await next.browser('/file')
await browser.elementByCss('#size-1mb').click()
const browser = await next.browser('/file')
await browser.elementByCss('#size-1mb').click()
await retry(() => {
expect(logs).toContainEqual(`size = ${accountForOverhead(1)}`)
})
await retry(() => {
expect(logs).toContainEqual(`size = ${accountForOverhead(1)}`)
})
await browser.elementByCss('#size-2mb').click()
await browser.elementByCss('#size-2mb').click()
await retry(() => {
expect(logs).toContainEqual(
expect.stringContaining('[Error]: Body exceeded 1.5mb limit')
)
expect(logs).toContainEqual(
expect.stringContaining(
'To configure the body size limit for Server Actions, see'
)
await retry(() => {
expect(logs).toContainEqual(
expect.stringContaining('[Error]: Body exceeded 1.5mb limit')
)
expect(logs).toContainEqual(
expect.stringContaining(
'To configure the body size limit for Server Actions, see'
)
})
)
})
})
it('should respect the size set in serverActions.bodySizeLimit when submitting form', async function () {
await next.patchFile(
'next.config.js',
`
it('should respect the size set in serverActions.bodySizeLimit when submitting form', async function () {
await next.patchFile(
'next.config.js',
`
module.exports = {
experimental: {
serverActions: { bodySizeLimit: '2mb' }
},
}
`
)
)
await next.start()
await next.start()
const browser = await next.browser('/form')
await browser.elementByCss('#size-1mb').click()
const browser = await next.browser('/form')
await browser.elementByCss('#size-1mb').click()
await retry(() => {
expect(logs).toContainEqual(`size = ${accountForOverhead(1)}`)
})
await retry(() => {
expect(logs).toContainEqual(`size = ${accountForOverhead(1)}`)
})
await browser.elementByCss('#size-2mb').click()
await browser.elementByCss('#size-2mb').click()
await retry(() => {
expect(logs).toContainEqual(`size = ${accountForOverhead(2)}`)
})
await retry(() => {
expect(logs).toContainEqual(`size = ${accountForOverhead(2)}`)
})
}
})
}
)
})
This diff is collapsed.
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import type { BrowserInterface } from 'next-webdriver'
createNextDescribe(
'app a11y features',
{
describe('app a11y features', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
packageJson: {},
skipDeployment: true,
},
({ next }) => {
describe('route announcer', () => {
async function getAnnouncerContent(browser: BrowserInterface) {
return browser.eval(
`document.getElementsByTagName('next-route-announcer')[0]?.shadowRoot.childNodes[0]?.innerHTML`
)
}
})
it('should not announce the initital title', async () => {
const browser = await next.browser('/page-with-h1')
await check(() => getAnnouncerContent(browser), '')
})
if (skipped) {
return
}
it('should announce document.title changes', async () => {
const browser = await next.browser('/page-with-h1')
await browser.elementById('page-with-title').click()
await check(() => getAnnouncerContent(browser), 'page-with-title')
})
describe('route announcer', () => {
async function getAnnouncerContent(browser: BrowserInterface) {
return browser.eval(
`document.getElementsByTagName('next-route-announcer')[0]?.shadowRoot.childNodes[0]?.innerHTML`
)
}
it('should announce h1 changes', async () => {
const browser = await next.browser('/page-with-h1')
await browser.elementById('noop-layout-page-1').click()
await check(() => getAnnouncerContent(browser), 'noop-layout/page-1')
})
it('should not announce the initital title', async () => {
const browser = await next.browser('/page-with-h1')
await check(() => getAnnouncerContent(browser), '')
})
it('should announce route changes when h1 changes inside an inner layout', async () => {
const browser = await next.browser('/noop-layout/page-1')
await browser.elementById('noop-layout-page-2').click()
await check(() => getAnnouncerContent(browser), 'noop-layout/page-2')
})
it('should announce document.title changes', async () => {
const browser = await next.browser('/page-with-h1')
await browser.elementById('page-with-title').click()
await check(() => getAnnouncerContent(browser), 'page-with-title')
})
}
)
it('should announce h1 changes', async () => {
const browser = await next.browser('/page-with-h1')
await browser.elementById('noop-layout-page-1').click()
await check(() => getAnnouncerContent(browser), 'noop-layout/page-1')
})
it('should announce route changes when h1 changes inside an inner layout', async () => {
const browser = await next.browser('/noop-layout/page-1')
await browser.elementById('noop-layout-page-2').click()
await check(() => getAnnouncerContent(browser), 'noop-layout/page-2')
})
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
createNextDescribe(
'app-dir alias',
{
describe('app-dir alias', () => {
const { next, isNextStart, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
},
({ next, isNextStart }) => {
it('should handle typescript paths alias correctly', async () => {
const html = await next.render('/button')
expect(html).toContain('click</button>')
})
})
it('should resolve css imports from outside with src folder presented', async () => {
const browser = await next.browser('/button')
const fontSize = await browser
.elementByCss('button')
.getComputedCss('font-size')
expect(fontSize).toBe('50px')
})
if (skipped) {
return
}
it('should handle typescript paths alias correctly', async () => {
const html = await next.render('/button')
expect(html).toContain('click</button>')
})
if (isNextStart) {
it('should not contain installed react/react-dom version in client chunks', async () => {
const appBuildManifest = await next.readJSON(
'.next/app-build-manifest.json'
it('should resolve css imports from outside with src folder presented', async () => {
const browser = await next.browser('/button')
const fontSize = await browser
.elementByCss('button')
.getComputedCss('font-size')
expect(fontSize).toBe('50px')
})
if (isNextStart) {
it('should not contain installed react/react-dom version in client chunks', async () => {
const appBuildManifest = await next.readJSON(
'.next/app-build-manifest.json'
)
Object.keys(appBuildManifest.pages).forEach((page) => {
const containFrameworkChunk = appBuildManifest.pages[page].some(
(chunk) => {
return chunk.includes('framework')
}
)
Object.keys(appBuildManifest.pages).forEach((page) => {
const containFrameworkChunk = appBuildManifest.pages[page].some(
(chunk) => {
return chunk.includes('framework')
}
)
expect(containFrameworkChunk).toBe(false)
})
expect(containFrameworkChunk).toBe(false)
})
})
it('should generate app-build-manifest correctly', async () => {
// Remove other page CSS files:
const manifest = await next.readJSON('.next/app-build-manifest.json')
it('should generate app-build-manifest correctly', async () => {
// Remove other page CSS files:
const manifest = await next.readJSON('.next/app-build-manifest.json')
expect(manifest.pages).not.toBeEmptyObject()
})
}
expect(manifest.pages).not.toBeEmptyObject()
})
}
)
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check, retry } from 'next-test-utils'
import { join } from 'path'
createNextDescribe(
'custom-app-server-action-redirect',
{
describe('custom-app-server-action-redirect', () => {
const { next, skipped } = nextTestSetup({
files: join(__dirname, 'custom-server'),
skipDeployment: true,
startCommand: 'node server.js',
dependencies: {
'get-port': '5.1.1',
},
},
({ next }) => {
it('redirects with basepath properly when server action handler uses `redirect`', async () => {
const browser = await next.browser('/base')
const getCount = async () => browser.elementByCss('#current-count').text()
// Increase count to track if the page reloaded
await browser.elementByCss('#increase-count').click().click()
await retry(async () => {
expect(await getCount()).toBe('Count: 2')
})
await browser.elementById('submit-server-action-redirect').click()
expect(await browser.waitForElementByCss('#another').text()).toBe(
'Another Page'
)
expect(await browser.url()).toBe(
`http://localhost:${next.appPort}/base/another`
)
// Count should still be 2 as the browser should not have reloaded the page.
})
if (skipped) {
return
}
it('redirects with basepath properly when server action handler uses `redirect`', async () => {
const browser = await next.browser('/base')
const getCount = async () => browser.elementByCss('#current-count').text()
// Increase count to track if the page reloaded
await browser.elementByCss('#increase-count').click().click()
await retry(async () => {
expect(await getCount()).toBe('Count: 2')
})
it('redirects with proper cookies set from both redirect response and post respose', async () => {
const browser = await next.browser('/base')
await browser.elementById('submit-server-action-redirect').click()
expect(await browser.waitForElementByCss('#another').text()).toBe(
'Another Page'
)
expect(await browser.url()).toBe(
`http://localhost:${next.appPort}/base/another`
)
await check(
() => browser.eval('document.cookie'),
/custom-server-test-cookie/
)
await check(
() => browser.eval('document.cookie'),
/custom-server-action-test-cookie/
)
})
}
)
await browser.elementById('submit-server-action-redirect').click()
expect(await browser.waitForElementByCss('#another').text()).toBe(
'Another Page'
)
expect(await browser.url()).toBe(
`http://localhost:${next.appPort}/base/another`
)
// Count should still be 2 as the browser should not have reloaded the page.
expect(await getCount()).toBe('Count: 2')
})
it('redirects with proper cookies set from both redirect response and post respose', async () => {
const browser = await next.browser('/base')
await browser.elementById('submit-server-action-redirect').click()
expect(await browser.waitForElementByCss('#another').text()).toBe(
'Another Page'
)
expect(await browser.url()).toBe(
`http://localhost:${next.appPort}/base/another`
)
await check(
() => browser.eval('document.cookie'),
/custom-server-test-cookie/
)
await check(
() => browser.eval('document.cookie'),
/custom-server-action-test-cookie/
)
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
createNextDescribe(
'app dir - basepath',
{
describe('app dir - basepath', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
dependencies: {
sass: 'latest',
},
},
({ next }) => {
it('should successfully hard navigate from pages -> app', async () => {
const browser = await next.browser('/base/pages-path')
await browser.elementByCss('#to-another').click()
await browser.waitForElementByCss('#page-2')
})
})
it('should support `basePath`', async () => {
const html = await next.render('/base')
expect(html).toContain('<h1>Test Page</h1>')
})
if (skipped) {
return
}
it('should support Link with basePath prefixed', async () => {
const browser = await next.browser('/base')
expect(
await browser
.elementByCss('a[href="/base/another"]')
.click()
.waitForElementByCss('#page-2')
.text()
).toBe(`Page 2`)
})
it('should successfully hard navigate from pages -> app', async () => {
const browser = await next.browser('/base/pages-path')
await browser.elementByCss('#to-another').click()
await browser.waitForElementByCss('#page-2')
})
it('should prefix metadata og image with basePath', async () => {
const $ = await next.render$('/base/another')
const ogImageHref = $('meta[property="og:image"]').attr('content')
it('should support `basePath`', async () => {
const html = await next.render('/base')
expect(html).toContain('<h1>Test Page</h1>')
})
expect(ogImageHref).toContain('/base/another/opengraph-image.png')
})
it('should support Link with basePath prefixed', async () => {
const browser = await next.browser('/base')
expect(
await browser
.elementByCss('a[href="/base/another"]')
.click()
.waitForElementByCss('#page-2')
.text()
).toBe(`Page 2`)
})
it('should prefix redirect() with basePath', async () => {
const browser = await next.browser('/base/redirect')
await retry(async () => {
expect(await browser.url()).toBe(`${next.url}/base/another`)
})
it('should prefix metadata og image with basePath', async () => {
const $ = await next.render$('/base/another')
const ogImageHref = $('meta[property="og:image"]').attr('content')
expect(ogImageHref).toContain('/base/another/opengraph-image.png')
})
it('should prefix redirect() with basePath', async () => {
const browser = await next.browser('/base/redirect')
await retry(async () => {
expect(await browser.url()).toBe(`${next.url}/base/another`)
})
})
it('should render usePathname without the basePath', async () => {
const pathnames = ['/use-pathname', '/use-pathname-another']
const validatorPromises = pathnames.map(async (pathname) => {
const $ = await next.render$('/base' + pathname)
expect($('#pathname').data('pathname')).toBe(pathname)
})
await Promise.all(validatorPromises)
it('should render usePathname without the basePath', async () => {
const pathnames = ['/use-pathname', '/use-pathname-another']
const validatorPromises = pathnames.map(async (pathname) => {
const $ = await next.render$('/base' + pathname)
expect($('#pathname').data('pathname')).toBe(pathname)
})
await Promise.all(validatorPromises)
})
it('should handle redirect in dynamic in suspense boundary routes with basePath', async () => {
const browser = await next.browser('/base/dynamic/source')
await retry(async () => {
// Check content is loaded first to avoid flakiness
expect(await browser.elementByCss('p').text()).toBe(`id:dest`)
expect(await browser.url()).toBe(`${next.url}/base/dynamic/dest`)
})
it('should handle redirect in dynamic in suspense boundary routes with basePath', async () => {
const browser = await next.browser('/base/dynamic/source')
await retry(async () => {
// Check content is loaded first to avoid flakiness
expect(await browser.elementByCss('p').text()).toBe(`id:dest`)
expect(await browser.url()).toBe(`${next.url}/base/dynamic/dest`)
})
})
it.each(['/base/refresh', '/base/refresh?foo=bar'])(
`should only make a single RSC call to the current page (%s)`,
async (path) => {
let rscRequests = []
const browser = await next.browser(path, {
beforePageLoad(page) {
page.on('request', (request) => {
return request.allHeaders().then((headers) => {
if (
headers['RSC'.toLowerCase()] === '1' &&
// Prefetches also include `RSC`
headers['Next-Router-Prefetch'.toLowerCase()] !== '1'
) {
rscRequests.push(request.url())
}
})
it.each(['/base/refresh', '/base/refresh?foo=bar'])(
`should only make a single RSC call to the current page (%s)`,
async (path) => {
let rscRequests = []
const browser = await next.browser(path, {
beforePageLoad(page) {
page.on('request', (request) => {
return request.allHeaders().then((headers) => {
if (
headers['RSC'.toLowerCase()] === '1' &&
// Prefetches also include `RSC`
headers['Next-Router-Prefetch'.toLowerCase()] !== '1'
) {
rscRequests.push(request.url())
}
})
},
})
await browser.elementByCss('button').click()
await retry(async () => {
expect(rscRequests.length).toBe(1)
expect(rscRequests[0]).toContain(`${next.url}${path}`)
})
}
)
}
)
})
},
})
await browser.elementByCss('button').click()
await retry(async () => {
expect(rscRequests.length).toBe(1)
expect(rscRequests[0]).toContain(`${next.url}${path}`)
})
}
)
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check, hasRedbox, waitFor } from 'next-test-utils'
createNextDescribe(
'app dir',
{
describe('app dir', () => {
const { next, isNextDev, isNextStart } = nextTestSetup({
files: __dirname,
},
({ next, isNextDev: isDev, isNextStart }) => {
if (isNextStart) {
describe('Loading', () => {
it('should render loading.js in initial html for slow page', async () => {
const $ = await next.render$('/page-with-loading')
expect($('#loading').text()).toBe('Loading...')
})
})
if (isNextStart) {
describe('Loading', () => {
it('should render loading.js in initial html for slow page', async () => {
const $ = await next.render$('/page-with-loading')
expect($('#loading').text()).toBe('Loading...')
})
}
})
}
if (isDev) {
describe('HMR', () => {
it('should not cause error when removing loading.js', async () => {
const browser = await next.browser('/page-with-loading')
await check(
() => browser.elementByCss('h1').text(),
'hello from slow page'
)
if (isNextDev) {
describe('HMR', () => {
it('should not cause error when removing loading.js', async () => {
const browser = await next.browser('/page-with-loading')
await check(
() => browser.elementByCss('h1').text(),
'hello from slow page'
)
await next.renameFile(
'app/page-with-loading/loading.js',
'app/page-with-loading/_loading.js'
)
await next.renameFile(
'app/page-with-loading/loading.js',
'app/page-with-loading/_loading.js'
)
await waitFor(1000)
await waitFor(1000)
// It should not have an error
expect(await hasRedbox(browser)).toBe(false)
// It should not have an error
expect(await hasRedbox(browser)).toBe(false)
// HMR should still work
const code = await next.readFile('app/page-with-loading/page.js')
await next.patchFile(
'app/page-with-loading/page.js',
code.replace('hello from slow page', 'hello from new page')
)
await check(
() => browser.elementByCss('h1').text(),
'hello from new page'
)
})
// HMR should still work
const code = await next.readFile('app/page-with-loading/page.js')
await next.patchFile(
'app/page-with-loading/page.js',
code.replace('hello from slow page', 'hello from new page')
)
await check(
() => browser.elementByCss('h1').text(),
'hello from new page'
)
})
}
})
}
)
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
createNextDescribe(
'app dir - crossOrigin config',
{
describe('app dir - crossOrigin config', () => {
const { next, isNextStart, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
},
({ next, isNextStart }) => {
if (isNextStart) {
it('skip in start mode', () => {})
return
}
it('should render correctly with assetPrefix: "/"', async () => {
const $ = await next.render$('/')
// Only potential external (assetPrefix) <script /> and <link /> should have crossorigin attribute
$(
'script[src*="https://example.vercel.sh"], link[href*="https://example.vercel.sh"]'
).each((_, el) => {
const crossOrigin = $(el).attr('crossorigin')
expect(crossOrigin).toBe('use-credentials')
})
})
// Inline <script /> (including RSC payload) and <link /> should not have crossorigin attribute
$('script:not([src]), link:not([href])').each((_, el) => {
const crossOrigin = $(el).attr('crossorigin')
expect(crossOrigin).toBeUndefined()
})
if (skipped) {
return
}
// Same origin <script /> and <link /> should not have crossorigin attribute either
$('script[src^="/"], link[href^="/"]').each((_, el) => {
const crossOrigin = $(el).attr('crossorigin')
expect(crossOrigin).toBeUndefined()
})
})
if (isNextStart) {
it('skip in start mode', () => {})
return
}
)
it('should render correctly with assetPrefix: "/"', async () => {
const $ = await next.render$('/')
// Only potential external (assetPrefix) <script /> and <link /> should have crossorigin attribute
$(
'script[src*="https://example.vercel.sh"], link[href*="https://example.vercel.sh"]'
).each((_, el) => {
const crossOrigin = $(el).attr('crossorigin')
expect(crossOrigin).toBe('use-credentials')
})
// Inline <script /> (including RSC payload) and <link /> should not have crossorigin attribute
$('script:not([src]), link:not([href])').each((_, el) => {
const crossOrigin = $(el).attr('crossorigin')
expect(crossOrigin).toBeUndefined()
})
// Same origin <script /> and <link /> should not have crossorigin attribute either
$('script[src^="/"], link[href^="/"]').each((_, el) => {
const crossOrigin = $(el).attr('crossorigin')
expect(crossOrigin).toBeUndefined()
})
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
createNextDescribe(
'app dir - css with pageextensions',
{
describe('app dir - css with pageextensions', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
dependencies: {
......@@ -11,19 +10,22 @@ createNextDescribe(
'react-dom': 'latest',
sass: 'latest',
},
},
({ next }) => {
describe('css support with pageextensions', () => {
describe('page in app directory with pageextention, css should work', () => {
it('should support global css inside layout', async () => {
const browser = await next.browser('/css-pageextensions')
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('h1')).color`
)
).toBe('rgb(255, 0, 0)')
})
})
if (skipped) {
return
}
describe('css support with pageextensions', () => {
describe('page in app directory with pageextention, css should work', () => {
it('should support global css inside layout', async () => {
const browser = await next.browser('/css-pageextensions')
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('h1')).color`
)
).toBe('rgb(255, 0, 0)')
})
})
}
)
})
})
This diff is collapsed.
import { type NextInstance, createNextDescribe, FileRef } from 'e2e-utils'
import { type NextInstance, nextTestSetup, FileRef } from 'e2e-utils'
import { check } from 'next-test-utils'
import fs from 'fs'
......@@ -27,37 +27,40 @@ function runTests(
})
}
createNextDescribe(
'app-dir - custom-cache-handler - cjs',
{
describe('app-dir - custom-cache-handler - cjs', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
env: {
CUSTOM_CACHE_HANDLER: 'cache-handler.js',
},
},
({ next, isNextDev }) => {
runTests('cjs module exports', { next, isNextDev })
})
if (skipped) {
return
}
)
createNextDescribe(
'app-dir - custom-cache-handler - cjs-default-export',
{
runTests('cjs module exports', { next, isNextDev })
})
describe('app-dir - custom-cache-handler - cjs-default-export', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
env: {
CUSTOM_CACHE_HANDLER: 'cache-handler-cjs-default-export.js',
},
},
({ next, isNextDev }) => {
runTests('cjs default export', { next, isNextDev })
})
if (skipped) {
return
}
)
createNextDescribe(
'app-dir - custom-cache-handler - esm',
{
runTests('cjs default export', { next, isNextDev })
})
describe('app-dir - custom-cache-handler - esm', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: {
app: new FileRef(__dirname + '/app'),
'cache-handler-esm.js': new FileRef(__dirname + '/cache-handler-esm.js'),
......@@ -73,8 +76,11 @@ createNextDescribe(
env: {
CUSTOM_CACHE_HANDLER: 'cache-handler-esm.js',
},
},
({ next, isNextDev }) => {
runTests('esm default export', { next, isNextDev })
})
if (skipped) {
return
}
)
runTests('esm default export', { next, isNextDev })
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
createNextDescribe(
'app-dir edge runtime root layout',
{
describe('app-dir edge runtime root layout', () => {
const { next, isNextStart, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
},
({ next, isNextStart }) => {
it('should not emit metadata files into bad paths', async () => {
await next.fetch('/favicon.ico')
// issue: If metadata files are not filter out properly with image-loader,
// an incorrect static/media folder will be generated
})
// Check that the static folder is not generated
const incorrectGeneratedStaticFolder = await next.hasFile('static')
expect(incorrectGeneratedStaticFolder).toBe(false)
})
if (skipped) {
return
}
it('should not emit metadata files into bad paths', async () => {
await next.fetch('/favicon.ico')
// issue: If metadata files are not filter out properly with image-loader,
// an incorrect static/media folder will be generated
if (isNextStart) {
it('should mark static contain metadata routes as edge functions', async () => {
const middlewareManifest = await next.readFile(
'.next/server/middleware-manifest.json'
)
expect(middlewareManifest).not.toContain('favicon')
})
}
// Check that the static folder is not generated
const incorrectGeneratedStaticFolder = await next.hasFile('static')
expect(incorrectGeneratedStaticFolder).toBe(false)
})
if (isNextStart) {
it('should mark static contain metadata routes as edge functions', async () => {
const middlewareManifest = await next.readFile(
'.next/server/middleware-manifest.json'
)
expect(middlewareManifest).not.toContain('favicon')
})
}
)
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'app-dir edge SSR',
{
describe('app-dir edge SSR', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
},
({ next }) => {
it('should handle edge only routes', async () => {
const appHtml = await next.render('/edge/basic')
expect(appHtml).toContain('<p>Edge!</p>')
})
const pageHtml = await next.render('/pages-edge')
expect(pageHtml).toContain('<p>pages-edge-ssr</p>')
})
if (skipped) {
return
}
it('should retrieve cookies in a server component in the edge runtime', async () => {
const res = await next.fetch('/edge-apis/cookies')
expect(await res.text()).toInclude('Hello')
})
it('should handle edge only routes', async () => {
const appHtml = await next.render('/edge/basic')
expect(appHtml).toContain('<p>Edge!</p>')
it('should handle /index routes correctly', async () => {
const appHtml = await next.render('/index')
expect(appHtml).toContain('the /index route')
})
const pageHtml = await next.render('/pages-edge')
expect(pageHtml).toContain('<p>pages-edge-ssr</p>')
})
it('should retrieve cookies in a server component in the edge runtime', async () => {
const res = await next.fetch('/edge-apis/cookies')
expect(await res.text()).toInclude('Hello')
})
if ((globalThis as any).isNextDev) {
it('should warn about the re-export of a pages runtime/preferredRegion config', async () => {
const logs = []
next.on('stderr', (log) => {
logs.push(log)
})
const appHtml = await next.render('/export/inherit')
expect(appHtml).toContain('<p>Node!</p>')
expect(
logs.some((log) =>
log.includes(
`Next.js can't recognize the exported \`runtime\` field in`
)
it('should handle /index routes correctly', async () => {
const appHtml = await next.render('/index')
expect(appHtml).toContain('the /index route')
})
if ((globalThis as any).isNextDev) {
it('should warn about the re-export of a pages runtime/preferredRegion config', async () => {
const logs = []
next.on('stderr', (log) => {
logs.push(log)
})
const appHtml = await next.render('/export/inherit')
expect(appHtml).toContain('<p>Node!</p>')
expect(
logs.some((log) =>
log.includes(
`Next.js can't recognize the exported \`runtime\` field in`
)
).toBe(true)
expect(
logs.some((log) =>
log.includes(
`Next.js can't recognize the exported \`preferredRegion\` field in`
)
)
).toBe(true)
expect(
logs.some((log) =>
log.includes(
`Next.js can't recognize the exported \`preferredRegion\` field in`
)
).toBe(true)
})
)
).toBe(true)
})
it('should resolve module without error in edge runtime', async () => {
const logs = []
next.on('stderr', (log) => {
logs.push(log)
})
await next.render('/app-edge')
expect(
logs.some((log) => log.includes(`Attempted import error:`))
).toBe(false)
it('should resolve module without error in edge runtime', async () => {
const logs = []
next.on('stderr', (log) => {
logs.push(log)
})
await next.render('/app-edge')
expect(logs.some((log) => log.includes(`Attempted import error:`))).toBe(
false
)
})
it('should resolve client component without error', async () => {
const logs = []
next.on('stderr', (log) => {
logs.push(log)
})
const html = await next.render('/with-client')
expect(html).toContain('My Button')
expect(logs).toEqual([])
it('should resolve client component without error', async () => {
const logs = []
next.on('stderr', (log) => {
logs.push(log)
})
const html = await next.render('/with-client')
expect(html).toContain('My Button')
expect(logs).toEqual([])
})
it('should handle edge rsc hmr', async () => {
const pageFile = 'app/edge/basic/page.tsx'
const content = await next.readFile(pageFile)
it('should handle edge rsc hmr', async () => {
const pageFile = 'app/edge/basic/page.tsx'
const content = await next.readFile(pageFile)
// Update rendered content
const updatedContent = content.replace('Edge!', 'edge-hmr')
await next.patchFile(pageFile, updatedContent)
await check(async () => {
const html = await next.render('/edge/basic')
return html
}, /edge-hmr/)
// Update rendered content
const updatedContent = content.replace('Edge!', 'edge-hmr')
await next.patchFile(pageFile, updatedContent)
await check(async () => {
const html = await next.render('/edge/basic')
return html
}, /edge-hmr/)
// Revert
await next.patchFile(pageFile, content)
await check(async () => {
const html = await next.render('/edge/basic')
return html
}, /Edge!/)
})
} else {
// Production tests
it('should generate matchers correctly in middleware manifest', async () => {
const manifest = JSON.parse(
await next.readFile('.next/server/middleware-manifest.json')
)
expect(manifest.functions['/(group)/group/page'].matchers).toEqual([
{
regexp: '^/group$',
originalSource: '/group',
},
])
})
}
// Revert
await next.patchFile(pageFile, content)
await check(async () => {
const html = await next.render('/edge/basic')
return html
}, /Edge!/)
})
} else {
// Production tests
it('should generate matchers correctly in middleware manifest', async () => {
const manifest = JSON.parse(
await next.readFile('.next/server/middleware-manifest.json')
)
expect(manifest.functions['/(group)/group/page'].matchers).toEqual([
{
regexp: '^/group$',
originalSource: '/group',
},
])
})
}
)
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
createNextDescribe(
'app-dir - esm js extension',
{
describe('app-dir - esm js extension', () => {
const { next } = nextTestSetup({
files: __dirname,
},
({ next }) => {
it('should be able to render nextjs api in app router', async () => {
const $ = await next.render$('/app')
async function validateDomNodes(selector: string) {
expect(await $(`${selector} .img`).prop('tagName')).toBe('IMG')
expect(await $(`${selector} .link`).prop('tagName')).toBe('A')
expect(await $(`${selector} .typeof-getImageProps`).text()).toContain(
'function'
)
}
await validateDomNodes('#with-ext')
await validateDomNodes('#without-ext')
expect($('head link[href="/test-ext.js"]').length).toBe(1)
expect($('head link[href="/test.js"]').length).toBe(1)
})
it('should be able to use nextjs api in pages router', async () => {
const $ = await next.render$('/pages')
expect(await $('meta[name="head-value-1"]').attr('content')).toBe(
'with-ext'
)
expect(await $('meta[name="head-value-2"]').attr('content')).toBe(
'without-ext'
})
it('should be able to render nextjs api in app router', async () => {
const $ = await next.render$('/app')
async function validateDomNodes(selector: string) {
expect(await $(`${selector} .img`).prop('tagName')).toBe('IMG')
expect(await $(`${selector} .link`).prop('tagName')).toBe('A')
expect(await $(`${selector} .typeof-getImageProps`).text()).toContain(
'function'
)
expect(await $('.root').text()).toContain('pages')
})
it('should support next/og image', async () => {
const res = await next.fetch('/opengraph-image')
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('image/png')
})
}
)
}
await validateDomNodes('#with-ext')
await validateDomNodes('#without-ext')
expect($('head link[href="/test-ext.js"]').length).toBe(1)
expect($('head link[href="/test.js"]').length).toBe(1)
})
it('should be able to use nextjs api in pages router', async () => {
const $ = await next.render$('/pages')
expect(await $('meta[name="head-value-1"]').attr('content')).toBe(
'with-ext'
)
expect(await $('meta[name="head-value-2"]').attr('content')).toBe(
'without-ext'
)
expect(await $('.root').text()).toContain('pages')
})
it('should support next/og image', async () => {
const res = await next.fetch('/opengraph-image')
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('image/png')
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'app-invalid-revalidate',
{
describe('app-invalid-revalidate', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
},
({ next, isNextDev }) => {
it('should error properly for invalid revalidate at layout', async () => {
await next.stop().catch(() => {})
const origText = await next.readFile('app/layout.tsx')
})
try {
await next.patchFile(
'app/layout.tsx',
origText.replace('// export', 'export')
)
await next.start().catch(() => {})
if (skipped) {
return
}
await check(async () => {
if (isNextDev) {
await next.fetch('/')
}
return next.cliOutput
}, /Invalid revalidate value "1" on "\/", must be a non-negative number or "false"/)
} finally {
await next.patchFile('app/layout.tsx', origText)
}
})
it('should error properly for invalid revalidate at layout', async () => {
await next.stop().catch(() => {})
const origText = await next.readFile('app/layout.tsx')
it('should error properly for invalid revalidate at page', async () => {
await next.stop().catch(() => {})
const origText = await next.readFile('app/page.tsx')
try {
await next.patchFile(
'app/layout.tsx',
origText.replace('// export', 'export')
)
await next.start().catch(() => {})
try {
await next.patchFile(
'app/page.tsx',
origText.replace('// export', 'export')
)
await next.start().catch(() => {})
await check(async () => {
if (isNextDev) {
await next.fetch('/')
}
return next.cliOutput
}, /Invalid revalidate value "1" on "\/", must be a non-negative number or "false"/)
} finally {
await next.patchFile('app/layout.tsx', origText)
}
})
await check(async () => {
if (isNextDev) {
await next.fetch('/')
}
return next.cliOutput
}, /Invalid revalidate value "1" on "\/", must be a non-negative number or "false"/)
} finally {
await next.patchFile('app/page.tsx', origText)
}
})
it('should error properly for invalid revalidate at page', async () => {
await next.stop().catch(() => {})
const origText = await next.readFile('app/page.tsx')
it('should error properly for invalid revalidate on fetch', async () => {
await next.stop().catch(() => {})
const origText = await next.readFile('app/page.tsx')
try {
await next.patchFile(
'app/page.tsx',
origText.replace('// export', 'export')
)
await next.start().catch(() => {})
try {
await next.patchFile(
'app/page.tsx',
origText.replace('// await', 'await')
)
await next.start().catch(() => {})
await check(async () => {
if (isNextDev) {
await next.fetch('/')
}
return next.cliOutput
}, /Invalid revalidate value "1" on "\/", must be a non-negative number or "false"/)
} finally {
await next.patchFile('app/page.tsx', origText)
}
})
await check(async () => {
if (isNextDev) {
await next.fetch('/')
}
return next.cliOutput
}, /Invalid revalidate value "1" on "\/", must be a non-negative number or "false"/)
} finally {
await next.patchFile('app/page.tsx', origText)
}
})
it('should error properly for invalid revalidate on fetch', async () => {
await next.stop().catch(() => {})
const origText = await next.readFile('app/page.tsx')
it('should error properly for invalid revalidate on unstable_cache', async () => {
await next.stop().catch(() => {})
const origText = await next.readFile('app/page.tsx')
try {
await next.patchFile(
'app/page.tsx',
origText.replace('// await', 'await')
)
await next.start().catch(() => {})
try {
await next.patchFile(
'app/page.tsx',
origText.replace('// await unstable', 'await unstable')
)
await next.start().catch(() => {})
await check(async () => {
if (isNextDev) {
await next.fetch('/')
}
return next.cliOutput
}, /Invalid revalidate value "1" on "\/", must be a non-negative number or "false"/)
} finally {
await next.patchFile('app/page.tsx', origText)
}
})
await check(async () => {
if (isNextDev) {
await next.fetch('/')
}
return next.cliOutput
}, /Invalid revalidate value "1" on "unstable_cache/)
} finally {
await next.patchFile('app/page.tsx', origText)
}
})
}
)
it('should error properly for invalid revalidate on unstable_cache', async () => {
await next.stop().catch(() => {})
const origText = await next.readFile('app/page.tsx')
try {
await next.patchFile(
'app/page.tsx',
origText.replace('// await unstable', 'await unstable')
)
await next.start().catch(() => {})
await check(async () => {
if (isNextDev) {
await next.fetch('/')
}
return next.cliOutput
}, /Invalid revalidate value "1" on "unstable_cache/)
} finally {
await next.patchFile('app/page.tsx', origText)
}
})
})
import { createNextDescribe } from 'e2e-utils'
import { nextTestSetup } from 'e2e-utils'
const bathPath = process.env.BASE_PATH ?? ''
createNextDescribe(
'app-routes-subrequests',
{
describe('app-routes-subrequests', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
},
({ next }) => {
it('shortcuts after 5 subrequests', async () => {
expect(JSON.parse(await next.render(bathPath + '/'))).toEqual({
count: 5,
})
})
})
if (skipped) {
return
}
)
it('shortcuts after 5 subrequests', async () => {
expect(JSON.parse(await next.render(bathPath + '/'))).toEqual({
count: 5,
})
})
})
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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