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