Unverified Commit 1e710ab7 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Rename process.env.TURBOPACK -> process.env.TURBOPACK_DEV in test skips (#63665)

## What?

Follow-up to #63653.

<!-- 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 #

-->


Closes NEXT-2911
parent f9d73cc2
...@@ -14,7 +14,7 @@ createNextDescribe( ...@@ -14,7 +14,7 @@ createNextDescribe(
}, },
({ next, isNextStart }) => { ({ next, isNextStart }) => {
if (!isNextStart) { if (!isNextStart) {
it('skip test for dev mode', () => {}) it('skip test for development mode', () => {})
return return
} }
......
...@@ -17,7 +17,7 @@ createNextDescribe( ...@@ -17,7 +17,7 @@ createNextDescribe(
}, },
({ next, isNextStart, isNextDeploy }) => { ({ next, isNextStart, isNextDeploy }) => {
if (!isNextStart) { if (!isNextStart) {
it('skip test for dev mode', () => {}) it('skip test for development mode', () => {})
return return
} }
......
...@@ -80,7 +80,7 @@ createNextDescribe( ...@@ -80,7 +80,7 @@ createNextDescribe(
}, },
({ next, isNextDev }) => { ({ next, isNextDev }) => {
if (isNextDev) { if (isNextDev) {
// since the router behavior is different in dev mode (no viewport prefetching + liberal revalidation) // since the router behavior is different in development mode (no viewport prefetching + liberal revalidation)
// we only check the production behavior // we only check the production behavior
it('should skip dev', () => {}) it('should skip dev', () => {})
} else { } else {
......
...@@ -35,7 +35,7 @@ createNextDescribe( ...@@ -35,7 +35,7 @@ createNextDescribe(
}, },
({ next, isNextDev }) => { ({ next, isNextDev }) => {
if (isNextDev) { if (isNextDev) {
it.skip('should skip test in dev mode', () => {}) it.skip('should skip test in development mode', () => {})
} else { } else {
it('should avoid double-fetching when optimistic navigation fails', async () => { it('should avoid double-fetching when optimistic navigation fails', async () => {
const browser = await next.browser('/foo') const browser = await next.browser('/foo')
......
...@@ -3056,7 +3056,7 @@ createNextDescribe( ...@@ -3056,7 +3056,7 @@ createNextDescribe(
}) })
} }
}) })
// Don't run these tests in dev mode since they won't be statically generated // Don't run these tests in development mode since they won't be statically generated
if (!isDev) { if (!isDev) {
describe('server response', () => { describe('server response', () => {
it('should bailout to client rendering - with suspense boundary', async () => { it('should bailout to client rendering - with suspense boundary', async () => {
...@@ -3215,7 +3215,7 @@ createNextDescribe( ...@@ -3215,7 +3215,7 @@ createNextDescribe(
}) })
} }
if (!process.env.CUSTOM_CACHE_HANDLER && isDev) { if (!process.env.CUSTOM_CACHE_HANDLER && isDev) {
it('should not cache request if response data size is greater than 2MB and FetchCache is possible in Dev mode', async () => { it('should not cache request if response data size is greater than 2MB and FetchCache is possible in development mode', async () => {
const cliOutputStart = next.cliOutput.length const cliOutputStart = next.cliOutput.length
const resp1 = await next.fetch('/force-cache/large-data') const resp1 = await next.fetch('/force-cache/large-data')
const resp1Text = await resp1.text() const resp1Text = await resp1.text()
...@@ -3243,7 +3243,7 @@ createNextDescribe( ...@@ -3243,7 +3243,7 @@ createNextDescribe(
}) })
} }
if (process.env.CUSTOM_CACHE_HANDLER && isDev) { if (process.env.CUSTOM_CACHE_HANDLER && isDev) {
it('should cache request if response data size is greater than 2MB in Dev mode', async () => { it('should cache request if response data size is greater than 2MB in development mode', async () => {
const cliOutputStart = next.cliOutput.length const cliOutputStart = next.cliOutput.length
const resp1 = await next.fetch('/force-cache/large-data') const resp1 = await next.fetch('/force-cache/large-data')
const resp1Text = await resp1.text() const resp1Text = await resp1.text()
......
...@@ -52,7 +52,7 @@ createNextDescribe( ...@@ -52,7 +52,7 @@ createNextDescribe(
withFullUrlFetches?: boolean withFullUrlFetches?: boolean
}) { }) {
if (withFetchesLogging) { if (withFetchesLogging) {
it('should only log requests in dev mode', async () => { it('should only log requests in development mode', async () => {
const outputIndex = next.cliOutput.length const outputIndex = next.cliOutput.length
await next.fetch('/default-cache') await next.fetch('/default-cache')
......
...@@ -12,7 +12,7 @@ createNextDescribe( ...@@ -12,7 +12,7 @@ createNextDescribe(
}, },
({ next, isNextDev }) => { ({ next, isNextDev }) => {
// If it's start mode, we get the whole logs since they're from build process. // If it's start mode, we get the whole logs since they're from build process.
// If it's dev mode, we get the logs after request // If it's development mode, we get the logs after request
function getCliOutput(logStartPosition: number) { function getCliOutput(logStartPosition: number) {
return isNextDev ? next.cliOutput.slice(logStartPosition) : next.cliOutput return isNextDev ? next.cliOutput.slice(logStartPosition) : next.cliOutput
} }
......
...@@ -8,7 +8,7 @@ createNextDescribe( ...@@ -8,7 +8,7 @@ createNextDescribe(
}, },
({ next, isNextDev }) => { ({ next, isNextDev }) => {
if (isNextDev) { if (isNextDev) {
it.skip('skip test for dev mode', () => {}) it.skip('skip test for development mode', () => {})
return return
} }
......
import { nextBuild } from 'next-test-utils' import { nextBuild } from 'next-test-utils'
describe('ppr build errors', () => { describe('ppr build errors', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
let stderr: string 'production mode',
let stdout: string () => {
let stderr: string
let stdout: string
beforeAll(async () => { beforeAll(async () => {
const output = await nextBuild(__dirname, [], { const output = await nextBuild(__dirname, [], {
stderr: true, stderr: true,
stdout: true, stdout: true,
})
stderr = output.stderr
stdout = output.stdout
}) })
stderr = output.stderr
stdout = output.stdout
})
describe('within a suspense boundary', () => { describe('within a suspense boundary', () => {
it('should fail the build for uncaught prerender errors', async () => { it('should fail the build for uncaught prerender errors', async () => {
expect(stderr).toContain( expect(stderr).toContain(
'Error occurred prerendering page "/regular-error-suspense-boundary".' 'Error occurred prerendering page "/regular-error-suspense-boundary".'
) )
expect(stderr).toContain( expect(stderr).toContain(
'Error occurred prerendering page "/re-throwing-error".' 'Error occurred prerendering page "/re-throwing-error".'
) )
})
}) })
})
describe('outside of a suspense boundary', () => { describe('outside of a suspense boundary', () => {
it('should fail the build for uncaught errors', async () => { it('should fail the build for uncaught errors', async () => {
expect(stderr).toContain( expect(stderr).toContain(
'Error occurred prerendering page "/regular-error".' 'Error occurred prerendering page "/regular-error".'
) )
expect(stderr).toContain( expect(stderr).toContain(
'Error occurred prerendering page "/no-suspense-boundary-re-throwing-error".' 'Error occurred prerendering page "/no-suspense-boundary-re-throwing-error".'
) )
})
}) })
})
describe('when a postpone call is caught and logged it should', () => { describe('when a postpone call is caught and logged it should', () => {
it('should include a message telling why', async () => { it('should include a message telling why', async () => {
expect(stdout).toContain( expect(stdout).toContain(
'User land logged error: Route /logging-error needs to bail out of prerendering at this point because it used cookies.' 'User land logged error: Route /logging-error needs to bail out of prerendering at this point because it used cookies.'
) )
})
}) })
}) }
}) )
}) })
...@@ -16,7 +16,7 @@ const apiPath = 'pages/api/edge.js' ...@@ -16,7 +16,7 @@ const apiPath = 'pages/api/edge.js'
const api = new File(join(appDir, apiPath)) const api = new File(join(appDir, apiPath))
if ((global as any).isNextDev) { if ((global as any).isNextDev) {
describe('In dev mode', () => { describe('In development mode', () => {
beforeAll(async () => { beforeAll(async () => {
next = await createNext({ next = await createNext({
files: new FileRef(appDir), files: new FileRef(appDir),
......
...@@ -1076,7 +1076,7 @@ describe('Prerender', () => { ...@@ -1076,7 +1076,7 @@ describe('Prerender', () => {
expect(JSON.parse($2('#__NEXT_DATA__').text()).isFallback).toBe(false) expect(JSON.parse($2('#__NEXT_DATA__').text()).isFallback).toBe(false)
}) })
it('should log error in console and browser in dev mode', async () => { it('should log error in console and browser in development mode', async () => {
const indexPage = 'pages/index.js' const indexPage = 'pages/index.js'
const origContent = await next.readFile(indexPage) const origContent = await next.readFile(indexPage)
......
...@@ -21,45 +21,48 @@ let appPort ...@@ -21,45 +21,48 @@ let appPort
let app let app
describe('404 Page Support with _app', () => { describe('404 Page Support with _app', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
afterAll(() => killApp(app)) 'production mode',
() => {
afterAll(() => killApp(app))
it('should build successfully', async () => { it('should build successfully', async () => {
const { code, stderr, stdout } = await nextBuild(appDir, [], { const { code, stderr, stdout } = await nextBuild(appDir, [], {
stderr: true, stderr: true,
stdout: true, stdout: true,
}) })
expect(code).toBe(0) expect(code).toBe(0)
expect(stderr).not.toMatch(gip404Err) expect(stderr).not.toMatch(gip404Err)
expect(stdout).not.toMatch(gip404Err) expect(stdout).not.toMatch(gip404Err)
appPort = await findPort() appPort = await findPort()
app = await nextStart(appDir, appPort) app = await nextStart(appDir, appPort)
}) })
it('should not output static 404 if _app has getInitialProps', async () => { it('should not output static 404 if _app has getInitialProps', async () => {
const browser = await webdriver(appPort, '/404') const browser = await webdriver(appPort, '/404')
const isAutoExported = await browser.eval('__NEXT_DATA__.autoExport') const isAutoExported = await browser.eval('__NEXT_DATA__.autoExport')
expect(isAutoExported).toBeFalsy() expect(isAutoExported).toBeFalsy()
}) })
it('specify to use the 404 page still in the routes-manifest', async () => { it('specify to use the 404 page still in the routes-manifest', async () => {
const manifest = await fs.readJSON( const manifest = await fs.readJSON(
join(appDir, '.next/routes-manifest.json') join(appDir, '.next/routes-manifest.json')
) )
expect(manifest.pages404).toBe(true) expect(manifest.pages404).toBe(true)
}) })
it('should still use 404 page', async () => { it('should still use 404 page', async () => {
const res = await fetchViaHTTP(appPort, '/abc') const res = await fetchViaHTTP(appPort, '/abc')
expect(res.status).toBe(404) expect(res.status).toBe(404)
const $ = cheerio.load(await res.text()) const $ = cheerio.load(await res.text())
expect($('#404-title').text()).toBe('Hi There') expect($('#404-title').text()).toBe('Hi There')
}) })
}) }
)
describe('dev mode', () => { describe('development mode', () => {
let stderr = '' let stderr = ''
let stdout = '' let stdout = ''
......
...@@ -51,26 +51,29 @@ const runTests = (mode) => { ...@@ -51,26 +51,29 @@ const runTests = (mode) => {
} }
describe('Default 404 Page with custom _error', () => { describe('Default 404 Page with custom _error', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
afterAll(() => killApp(app)) 'production mode',
() => {
afterAll(() => killApp(app))
it('should build successfully', async () => { it('should build successfully', async () => {
const { code } = await nextBuild(appDir, [], { const { code } = await nextBuild(appDir, [], {
stderr: true, stderr: true,
stdout: true, stdout: true,
}) })
expect(code).toBe(0) expect(code).toBe(0)
appPort = await findPort() appPort = await findPort()
app = await nextStart(appDir, appPort) app = await nextStart(appDir, appPort)
}) })
runTests('server') runTests('server')
}) }
)
describe('dev mode', () => { describe('development mode', () => {
beforeAll(async () => { beforeAll(async () => {
appPort = await findPort() appPort = await findPort()
app = await launchApp(appDir, appPort) app = await launchApp(appDir, appPort)
......
...@@ -76,42 +76,45 @@ const runTests = (isDev) => { ...@@ -76,42 +76,45 @@ const runTests = (isDev) => {
} }
describe('404 Page Support SSG', () => { describe('404 Page Support SSG', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
afterAll(() => killApp(app)) 'production mode',
() => {
it('should build successfully', async () => { afterAll(() => killApp(app))
const {
code, it('should build successfully', async () => {
stderr: buildStderr, const {
stdout: buildStdout, code,
} = await nextBuild(appDir, [], { stderr: buildStderr,
stderr: true, stdout: buildStdout,
stdout: true, } = await nextBuild(appDir, [], {
stderr: true,
stdout: true,
})
expect(code).toBe(0)
expect(buildStderr).not.toMatch(gip404Err)
expect(buildStdout).not.toMatch(gip404Err)
appPort = await findPort()
stderr = ''
stdout = ''
app = await nextStart(appDir, appPort, {
onStdout(msg) {
stdout += msg
},
onStderr(msg) {
stderr += msg
},
})
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
}) })
expect(code).toBe(0) runTests()
expect(buildStderr).not.toMatch(gip404Err) }
expect(buildStdout).not.toMatch(gip404Err) )
appPort = await findPort()
stderr = ''
stdout = ''
app = await nextStart(appDir, appPort, {
onStdout(msg) {
stdout += msg
},
onStderr(msg) {
stderr += msg
},
})
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
})
runTests()
})
describe('dev mode', () => { describe('development mode', () => {
beforeAll(async () => { beforeAll(async () => {
appPort = await findPort() appPort = await findPort()
stderr = '' stderr = ''
......
...@@ -70,7 +70,7 @@ const runTests = (mode = 'server') => { ...@@ -70,7 +70,7 @@ const runTests = (mode = 'server') => {
} }
describe('404 Page Support', () => { describe('404 Page Support', () => {
describe('dev mode', () => { describe('development mode', () => {
beforeAll(async () => { beforeAll(async () => {
appPort = await findPort() appPort = await findPort()
app = await launchApp(appDir, appPort) app = await launchApp(appDir, appPort)
...@@ -79,7 +79,7 @@ describe('404 Page Support', () => { ...@@ -79,7 +79,7 @@ describe('404 Page Support', () => {
runTests('dev') runTests('dev')
}) })
describe('dev mode 2', () => { describe('development mode 2', () => {
it('falls back to _error correctly without pages/404', async () => { it('falls back to _error correctly without pages/404', async () => {
await fs.move(pages404, `${pages404}.bak`) await fs.move(pages404, `${pages404}.bak`)
appPort = await findPort() appPort = await findPort()
...@@ -180,135 +180,141 @@ describe('404 Page Support', () => { ...@@ -180,135 +180,141 @@ describe('404 Page Support', () => {
expect(stderr).toMatch(gip404Err) expect(stderr).toMatch(gip404Err)
}) })
}) })
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
await nextBuild(appDir) () => {
appPort = await findPort() beforeAll(async () => {
app = await nextStart(appDir, appPort) await nextBuild(appDir)
}) appPort = await findPort()
afterAll(() => killApp(app)) app = await nextStart(appDir, appPort)
})
runTests('server') afterAll(() => killApp(app))
})
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { runTests('server')
it('should not cache for custom 404 page with gssp and revalidate disabled', async () => { }
await fs.move(pages404, `${pages404}.bak`) )
await fs.writeFile( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
pages404, 'production mode',
` () => {
it('should not cache for custom 404 page with gssp and revalidate disabled', async () => {
await fs.move(pages404, `${pages404}.bak`)
await fs.writeFile(
pages404,
`
const page = () => 'custom 404 page' const page = () => 'custom 404 page'
export async function getStaticProps() { return { props: {} } } export async function getStaticProps() { return { props: {} } }
export default page export default page
` `
) )
await nextBuild(appDir) await nextBuild(appDir)
appPort = await findPort() appPort = await findPort()
app = await nextStart(appDir, appPort) app = await nextStart(appDir, appPort)
const cache404 = await getCacheHeader(appPort, '/404') const cache404 = await getCacheHeader(appPort, '/404')
const cacheNext = await getCacheHeader(appPort, '/_next/abc') const cacheNext = await getCacheHeader(appPort, '/_next/abc')
await fs.remove(pages404) await fs.remove(pages404)
await fs.move(`${pages404}.bak`, pages404) await fs.move(`${pages404}.bak`, pages404)
await killApp(app) await killApp(app)
expect(cache404).toBe( expect(cache404).toBe(
'private, no-cache, no-store, max-age=0, must-revalidate' 'private, no-cache, no-store, max-age=0, must-revalidate'
) )
expect(cacheNext).toBe( expect(cacheNext).toBe(
'private, no-cache, no-store, max-age=0, must-revalidate' 'private, no-cache, no-store, max-age=0, must-revalidate'
) )
}) })
it('should not cache for custom 404 page with gssp and revalidate enabled', async () => { it('should not cache for custom 404 page with gssp and revalidate enabled', async () => {
await fs.move(pages404, `${pages404}.bak`) await fs.move(pages404, `${pages404}.bak`)
await fs.writeFile( await fs.writeFile(
pages404, pages404,
` `
const page = () => 'custom 404 page' const page = () => 'custom 404 page'
export async function getStaticProps() { return { props: {}, revalidate: 1 } } export async function getStaticProps() { return { props: {}, revalidate: 1 } }
export default page export default page
` `
) )
await nextBuild(appDir) await nextBuild(appDir)
appPort = await findPort() appPort = await findPort()
app = await nextStart(appDir, appPort) app = await nextStart(appDir, appPort)
const cache404 = await getCacheHeader(appPort, '/404') const cache404 = await getCacheHeader(appPort, '/404')
const cacheNext = await getCacheHeader(appPort, '/_next/abc') const cacheNext = await getCacheHeader(appPort, '/_next/abc')
await fs.remove(pages404) await fs.remove(pages404)
await fs.move(`${pages404}.bak`, pages404) await fs.move(`${pages404}.bak`, pages404)
await killApp(app) await killApp(app)
expect(cache404).toBe( expect(cache404).toBe(
'private, no-cache, no-store, max-age=0, must-revalidate' 'private, no-cache, no-store, max-age=0, must-revalidate'
) )
expect(cacheNext).toBe( expect(cacheNext).toBe(
'private, no-cache, no-store, max-age=0, must-revalidate' 'private, no-cache, no-store, max-age=0, must-revalidate'
) )
}) })
it('should not cache for custom 404 page without gssp', async () => { it('should not cache for custom 404 page without gssp', async () => {
await nextBuild(appDir) await nextBuild(appDir)
appPort = await findPort() appPort = await findPort()
app = await nextStart(appDir, appPort) app = await nextStart(appDir, appPort)
const cache404 = await getCacheHeader(appPort, '/404') const cache404 = await getCacheHeader(appPort, '/404')
const cacheNext = await getCacheHeader(appPort, '/_next/abc') const cacheNext = await getCacheHeader(appPort, '/_next/abc')
await killApp(app) await killApp(app)
expect(cache404).toBe(null) expect(cache404).toBe(null)
expect(cacheNext).toBe('no-cache, no-store, max-age=0, must-revalidate') expect(cacheNext).toBe('no-cache, no-store, max-age=0, must-revalidate')
}) })
it('shows error with getInitialProps in pages/404 build', async () => { it('shows error with getInitialProps in pages/404 build', async () => {
await fs.move(pages404, `${pages404}.bak`) await fs.move(pages404, `${pages404}.bak`)
await fs.writeFile( await fs.writeFile(
pages404, pages404,
` `
const page = () => 'custom 404 page' const page = () => 'custom 404 page'
page.getInitialProps = () => ({ a: 'b' }) page.getInitialProps = () => ({ a: 'b' })
export default page export default page
` `
) )
const { stderr, code } = await nextBuild(appDir, [], { stderr: true }) const { stderr, code } = await nextBuild(appDir, [], { stderr: true })
await fs.remove(pages404) await fs.remove(pages404)
await fs.move(`${pages404}.bak`, pages404) await fs.move(`${pages404}.bak`, pages404)
expect(stderr).toMatch(gip404Err) expect(stderr).toMatch(gip404Err)
expect(code).toBe(1) expect(code).toBe(1)
}) })
it('does not show error with getStaticProps in pages/404 build', async () => { it('does not show error with getStaticProps in pages/404 build', async () => {
await fs.move(pages404, `${pages404}.bak`) await fs.move(pages404, `${pages404}.bak`)
await fs.writeFile( await fs.writeFile(
pages404, pages404,
` `
const page = () => 'custom 404 page' const page = () => 'custom 404 page'
export const getStaticProps = () => ({ props: { a: 'b' } }) export const getStaticProps = () => ({ props: { a: 'b' } })
export default page export default page
` `
) )
const { stderr, code } = await nextBuild(appDir, [], { stderr: true }) const { stderr, code } = await nextBuild(appDir, [], { stderr: true })
await fs.remove(pages404) await fs.remove(pages404)
await fs.move(`${pages404}.bak`, pages404) await fs.move(`${pages404}.bak`, pages404)
expect(stderr).not.toMatch(gip404Err) expect(stderr).not.toMatch(gip404Err)
expect(code).toBe(0) expect(code).toBe(0)
}) })
it('shows error with getServerSideProps in pages/404 build', async () => { it('shows error with getServerSideProps in pages/404 build', async () => {
await fs.move(pages404, `${pages404}.bak`) await fs.move(pages404, `${pages404}.bak`)
await fs.writeFile( await fs.writeFile(
pages404, pages404,
` `
const page = () => 'custom 404 page' const page = () => 'custom 404 page'
export const getServerSideProps = () => ({ props: { a: 'b' } }) export const getServerSideProps = () => ({ props: { a: 'b' } })
export default page export default page
` `
) )
const { stderr, code } = await nextBuild(appDir, [], { stderr: true }) const { stderr, code } = await nextBuild(appDir, [], { stderr: true })
await fs.remove(pages404) await fs.remove(pages404)
await fs.move(`${pages404}.bak`, pages404) await fs.move(`${pages404}.bak`, pages404)
expect(stderr).toMatch(gip404Err) expect(stderr).toMatch(gip404Err)
expect(code).toBe(1) expect(code).toBe(1)
}) })
}) }
)
}) })
...@@ -23,163 +23,166 @@ let appPort ...@@ -23,163 +23,166 @@ let appPort
let app let app
describe('gsp-gssp', () => { describe('gsp-gssp', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
it('does not show error with getStaticProps in pages/500 build', async () => { 'production mode',
await fs.move(pages500, `${pages500}.bak`) () => {
await fs.writeFile( it('does not show error with getStaticProps in pages/500 build', async () => {
pages500, await fs.move(pages500, `${pages500}.bak`)
` await fs.writeFile(
pages500,
`
const page = () => 'custom 500 page' const page = () => 'custom 500 page'
export const getStaticProps = () => ({ props: { a: 'b' } }) export const getStaticProps = () => ({ props: { a: 'b' } })
export default page export default page
` `
) )
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
const { stderr, code } = await nextBuild(appDir, [], { stderr: true }) const { stderr, code } = await nextBuild(appDir, [], { stderr: true })
await fs.remove(pages500) await fs.remove(pages500)
await fs.move(`${pages500}.bak`, pages500) await fs.move(`${pages500}.bak`, pages500)
expect(stderr).not.toMatch(gip500Err) expect(stderr).not.toMatch(gip500Err)
expect(code).toBe(0) expect(code).toBe(0)
}) })
it('shows error with getServerSideProps in pages/500 build', async () => { it('shows error with getServerSideProps in pages/500 build', async () => {
await fs.move(pages500, `${pages500}.bak`) await fs.move(pages500, `${pages500}.bak`)
await fs.writeFile( await fs.writeFile(
pages500, pages500,
` `
const page = () => 'custom 500 page' const page = () => 'custom 500 page'
export const getServerSideProps = () => ({ props: { a: 'b' } }) export const getServerSideProps = () => ({ props: { a: 'b' } })
export default page export default page
` `
) )
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
const { stderr, code } = await nextBuild(appDir, [], { stderr: true }) const { stderr, code } = await nextBuild(appDir, [], { stderr: true })
await fs.remove(pages500) await fs.remove(pages500)
await fs.move(`${pages500}.bak`, pages500) await fs.move(`${pages500}.bak`, pages500)
expect(stderr).toMatch(gip500Err) expect(stderr).toMatch(gip500Err)
expect(code).toBe(1) expect(code).toBe(1)
}) })
it('does build 500 statically with getInitialProps in _app and getStaticProps in pages/500', async () => { it('does build 500 statically with getInitialProps in _app and getStaticProps in pages/500', async () => {
await fs.writeFile( await fs.writeFile(
pagesApp, pagesApp,
` `
import App from 'next/app' import App from 'next/app'
const page = ({ Component, pageProps }) => <Component {...pageProps} /> const page = ({ Component, pageProps }) => <Component {...pageProps} />
page.getInitialProps = (ctx) => App.getInitialProps(ctx) page.getInitialProps = (ctx) => App.getInitialProps(ctx)
export default page export default page
` `
) )
await fs.rename(pages500, `${pages500}.bak`) await fs.rename(pages500, `${pages500}.bak`)
await fs.writeFile( await fs.writeFile(
pages500, pages500,
` `
const page = () => { const page = () => {
console.log('rendered 500') console.log('rendered 500')
return 'custom 500 page' return 'custom 500 page'
} }
export default page export default page
export const getStaticProps = () => { export const getStaticProps = () => {
return { return {
props: {} props: {}
} }
} }
` `
) )
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
const { const {
stderr, stderr,
stdout: buildStdout, stdout: buildStdout,
code, code,
} = await nextBuild(appDir, [], { } = await nextBuild(appDir, [], {
stderr: true, stderr: true,
stdout: true, stdout: true,
})
await fs.remove(pagesApp)
await fs.remove(pages500)
await fs.rename(`${pages500}.bak`, pages500)
expect(stderr).not.toMatch(gip500Err)
expect(buildStdout).toContain('rendered 500')
expect(code).toBe(0)
expect(
await fs.pathExists(join(appDir, '.next/server/pages/500.html'))
).toBe(true)
let appStdout = ''
const appPort = await findPort()
const app = await nextStart(appDir, appPort, {
onStdout(msg) {
appStdout += msg || ''
},
onStderr(msg) {
appStdout += msg || ''
},
})
await renderViaHTTP(appPort, '/err')
await killApp(app)
expect(appStdout).not.toContain('rendered 500')
}) })
await fs.remove(pagesApp) it('does not build 500 statically with no pages/500 and getServerSideProps in _error', async () => {
await fs.remove(pages500) await fs.rename(pages500, `${pages500}.bak`)
await fs.rename(`${pages500}.bak`, pages500) await fs.writeFile(
pagesError,
expect(stderr).not.toMatch(gip500Err) `
expect(buildStdout).toContain('rendered 500')
expect(code).toBe(0)
expect(
await fs.pathExists(join(appDir, '.next/server/pages/500.html'))
).toBe(true)
let appStdout = ''
const appPort = await findPort()
const app = await nextStart(appDir, appPort, {
onStdout(msg) {
appStdout += msg || ''
},
onStderr(msg) {
appStdout += msg || ''
},
})
await renderViaHTTP(appPort, '/err')
await killApp(app)
expect(appStdout).not.toContain('rendered 500')
})
it('does not build 500 statically with no pages/500 and getServerSideProps in _error', async () => {
await fs.rename(pages500, `${pages500}.bak`)
await fs.writeFile(
pagesError,
`
function Error({ statusCode }) { function Error({ statusCode }) {
return <p>Error status: {statusCode}</p> return <p>Error status: {statusCode}</p>
} }
export const getServerSideProps = ({ req, res, err }) => { export const getServerSideProps = ({ req, res, err }) => {
console.error('called _error getServerSideProps') console.error('called _error getServerSideProps')
if (req.url === '/500') { if (req.url === '/500') {
throw new Error('should not export /500') throw new Error('should not export /500')
} }
return { return {
props: { props: {
statusCode: res && res.statusCode ? res.statusCode : err ? err.statusCode : 404 statusCode: res && res.statusCode ? res.statusCode : err ? err.statusCode : 404
} }
} }
} }
export default Error export default Error
` `
) )
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
const { stderr: buildStderr, code } = await nextBuild(appDir, [], { const { stderr: buildStderr, code } = await nextBuild(appDir, [], {
stderr: true, stderr: true,
}) })
await fs.rename(`${pages500}.bak`, pages500) await fs.rename(`${pages500}.bak`, pages500)
await fs.remove(pagesError) await fs.remove(pagesError)
console.log(buildStderr) console.log(buildStderr)
expect(buildStderr).not.toMatch(gip500Err) expect(buildStderr).not.toMatch(gip500Err)
expect(code).toBe(0) expect(code).toBe(0)
expect( expect(
await fs.pathExists(join(appDir, '.next/server/pages/500.html')) await fs.pathExists(join(appDir, '.next/server/pages/500.html'))
).toBe(false) ).toBe(false)
let appStderr = '' let appStderr = ''
const appPort = await findPort() const appPort = await findPort()
const app = await nextStart(appDir, appPort, { const app = await nextStart(appDir, appPort, {
onStderr(msg) { onStderr(msg) {
appStderr += msg || '' appStderr += msg || ''
}, },
})
await renderViaHTTP(appPort, '/err')
await killApp(app)
expect(appStderr).toContain('called _error getServerSideProps')
}) })
}
await renderViaHTTP(appPort, '/err') )
await killApp(app)
expect(appStderr).toContain('called _error getServerSideProps')
})
})
describe('development mode', () => { describe('development mode', () => {
it('does not show error with getStaticProps in pages/500 dev', async () => { it('does not show error with getStaticProps in pages/500 dev', async () => {
......
...@@ -60,7 +60,7 @@ const runTests = (mode = 'server') => { ...@@ -60,7 +60,7 @@ const runTests = (mode = 'server') => {
} }
describe('500 Page Support', () => { describe('500 Page Support', () => {
describe('dev mode', () => { describe('development mode', () => {
beforeAll(async () => { beforeAll(async () => {
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
appPort = await findPort() appPort = await findPort()
...@@ -100,18 +100,21 @@ describe('500 Page Support', () => { ...@@ -100,18 +100,21 @@ describe('500 Page Support', () => {
expect(stderr).toMatch(gip500Err) expect(stderr).toMatch(gip500Err)
}) })
}) })
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
await fs.remove(join(appDir, '.next')) () => {
await nextBuild(appDir) beforeAll(async () => {
appPort = await findPort() await fs.remove(join(appDir, '.next'))
app = await nextStart(appDir, appPort) await nextBuild(appDir)
}) appPort = await findPort()
afterAll(() => killApp(app)) app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests('server') runTests('server')
}) }
;(process.env.TURBOPACK ? describe.skip : describe)( )
;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode 2', 'production mode 2',
() => { () => {
it('does not build 500 statically with getInitialProps in _app', async () => { it('does not build 500 statically with getInitialProps in _app', async () => {
...@@ -119,7 +122,7 @@ describe('500 Page Support', () => { ...@@ -119,7 +122,7 @@ describe('500 Page Support', () => {
pagesApp, pagesApp,
` `
import App from 'next/app' import App from 'next/app'
const page = ({ Component, pageProps }) => <Component {...pageProps} /> const page = ({ Component, pageProps }) => <Component {...pageProps} />
page.getInitialProps = (ctx) => App.getInitialProps(ctx) page.getInitialProps = (ctx) => App.getInitialProps(ctx)
export default page export default page
...@@ -233,19 +236,19 @@ describe('500 Page Support', () => { ...@@ -233,19 +236,19 @@ describe('500 Page Support', () => {
function Error({ statusCode }) { function Error({ statusCode }) {
return <p>Error status: {statusCode}</p> return <p>Error status: {statusCode}</p>
} }
Error.getInitialProps = ({ req, res, err }) => { Error.getInitialProps = ({ req, res, err }) => {
console.error('called _error.getInitialProps') console.error('called _error.getInitialProps')
if (req.url === '/500') { if (req.url === '/500') {
throw new Error('should not export /500') throw new Error('should not export /500')
} }
return { return {
statusCode: res && res.statusCode ? res.statusCode : err ? err.statusCode : 404 statusCode: res && res.statusCode ? res.statusCode : err ? err.statusCode : 404
} }
} }
export default Error export default Error
` `
) )
...@@ -284,19 +287,19 @@ describe('500 Page Support', () => { ...@@ -284,19 +287,19 @@ describe('500 Page Support', () => {
function Error({ statusCode }) { function Error({ statusCode }) {
return <p>Error status: {statusCode}</p> return <p>Error status: {statusCode}</p>
} }
Error.getInitialProps = ({ req, res, err }) => { Error.getInitialProps = ({ req, res, err }) => {
console.error('called _error.getInitialProps') console.error('called _error.getInitialProps')
if (req.url === '/500') { if (req.url === '/500') {
throw new Error('should not export /500') throw new Error('should not export /500')
} }
return { return {
statusCode: res && res.statusCode ? res.statusCode : err ? err.statusCode : 404 statusCode: res && res.statusCode ? res.statusCode : err ? err.statusCode : 404
} }
} }
export default Error export default Error
` `
) )
...@@ -306,18 +309,18 @@ describe('500 Page Support', () => { ...@@ -306,18 +309,18 @@ describe('500 Page Support', () => {
function App({ pageProps, Component }) { function App({ pageProps, Component }) {
return <Component {...pageProps} /> return <Component {...pageProps} />
} }
App.getInitialProps = async ({ Component, ctx }) => { App.getInitialProps = async ({ Component, ctx }) => {
// throw _app GIP err here // throw _app GIP err here
let pageProps = {} let pageProps = {}
if (Component.getInitialProps) { if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx) pageProps = await Component.getInitialProps(ctx)
} }
return { pageProps } return { pageProps }
} }
export default App export default App
` `
) )
......
...@@ -19,105 +19,108 @@ let cdnAccessLog = [] ...@@ -19,105 +19,108 @@ let cdnAccessLog = []
const nextConfig = new File(path.resolve(__dirname, '../next.config.js')) const nextConfig = new File(path.resolve(__dirname, '../next.config.js'))
describe('absolute assetPrefix with path prefix', () => { describe('absolute assetPrefix with path prefix', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
cdnPort = await findPort() () => {
// lightweight http proxy beforeAll(async () => {
cdn = http.createServer((clientReq, clientRes) => { cdnPort = await findPort()
const proxyPath = clientReq.url.slice('/path-prefix'.length) // lightweight http proxy
cdnAccessLog.push(proxyPath) cdn = http.createServer((clientReq, clientRes) => {
const proxyReq = http.request( const proxyPath = clientReq.url.slice('/path-prefix'.length)
{ cdnAccessLog.push(proxyPath)
hostname: 'localhost', const proxyReq = http.request(
port: appPort, {
path: proxyPath, hostname: 'localhost',
method: clientReq.method, port: appPort,
headers: clientReq.headers, path: proxyPath,
}, method: clientReq.method,
(proxyRes) => { headers: clientReq.headers,
// cdn must be configured to allow requests from this origin },
proxyRes.headers[ (proxyRes) => {
'Access-Control-Allow-Origin' // cdn must be configured to allow requests from this origin
] = `http://localhost:${appPort}` proxyRes.headers[
clientRes.writeHead(proxyRes.statusCode, proxyRes.headers) 'Access-Control-Allow-Origin'
proxyRes.pipe(clientRes, { end: true }) ] = `http://localhost:${appPort}`
} clientRes.writeHead(proxyRes.statusCode, proxyRes.headers)
proxyRes.pipe(clientRes, { end: true })
}
)
clientReq.pipe(proxyReq, { end: true })
})
await new Promise((resolve) => cdn.listen(cdnPort, resolve))
nextConfig.replace('__CDN_PORT__', cdnPort)
await nextBuild(appDir)
buildId = await fs.readFile(
path.resolve(__dirname, '../.next/BUILD_ID'),
'utf8'
) )
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
clientReq.pipe(proxyReq, { end: true }) afterEach(() => {
cdnAccessLog = []
}) })
await new Promise((resolve) => cdn.listen(cdnPort, resolve))
nextConfig.replace('__CDN_PORT__', cdnPort)
await nextBuild(appDir)
buildId = await fs.readFile(
path.resolve(__dirname, '../.next/BUILD_ID'),
'utf8'
)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterEach(() => { afterAll(() => killApp(app))
cdnAccessLog = [] afterAll(() => cdn.close())
}) afterAll(() => nextConfig.restore())
afterAll(() => killApp(app)) it('should not fetch static data from a CDN', async () => {
afterAll(() => cdn.close()) const browser = await webdriver(appPort, '/')
afterAll(() => nextConfig.restore()) await browser.waitForElementByCss('#about-link').click()
const prop = await browser.waitForElementByCss('#prop').text()
expect(prop).toBe('hello')
expect(cdnAccessLog).not.toContain(`/_next/data/${buildId}/about.json`)
})
it('should not fetch static data from a CDN', async () => { it('should fetch from cache correctly', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await browser.waitForElementByCss('#about-link').click() await browser.eval('window.clientSideNavigated = true')
const prop = await browser.waitForElementByCss('#prop').text() await browser.waitForElementByCss('#about-link').click()
expect(prop).toBe('hello') await browser.waitForElementByCss('#prop')
expect(cdnAccessLog).not.toContain(`/_next/data/${buildId}/about.json`) await browser.back()
}) await browser.waitForElementByCss('#about-link').click()
const prop = await browser.waitForElementByCss('#prop').text()
expect(prop).toBe('hello')
expect(await browser.eval('window.clientSideNavigated')).toBe(true)
expect(
cdnAccessLog.filter(
(path) => path === `/_next/data/${buildId}/about.json`
)
).toHaveLength(0)
})
it('should fetch from cache correctly', async () => { it('should work with getStaticPaths prerendered', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await browser.eval('window.clientSideNavigated = true') await browser.waitForElementByCss('#gsp-prerender-link').click()
await browser.waitForElementByCss('#about-link').click() const prop = await browser.waitForElementByCss('#prop').text()
await browser.waitForElementByCss('#prop') expect(prop).toBe('prerendered')
await browser.back() expect(cdnAccessLog).not.toContain(
await browser.waitForElementByCss('#about-link').click() `/_next/data/${buildId}/gsp-fallback/prerendered.json`
const prop = await browser.waitForElementByCss('#prop').text()
expect(prop).toBe('hello')
expect(await browser.eval('window.clientSideNavigated')).toBe(true)
expect(
cdnAccessLog.filter(
(path) => path === `/_next/data/${buildId}/about.json`
) )
).toHaveLength(0) })
})
it('should work with getStaticPaths prerendered', async () => {
const browser = await webdriver(appPort, '/')
await browser.waitForElementByCss('#gsp-prerender-link').click()
const prop = await browser.waitForElementByCss('#prop').text()
expect(prop).toBe('prerendered')
expect(cdnAccessLog).not.toContain(
`/_next/data/${buildId}/gsp-fallback/prerendered.json`
)
})
it('should work with getStaticPaths fallback', async () => { it('should work with getStaticPaths fallback', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await browser.waitForElementByCss('#gsp-fallback-link').click() await browser.waitForElementByCss('#gsp-fallback-link').click()
const prop = await browser.waitForElementByCss('#prop').text() const prop = await browser.waitForElementByCss('#prop').text()
expect(prop).toBe('fallback') expect(prop).toBe('fallback')
expect(cdnAccessLog).not.toContain( expect(cdnAccessLog).not.toContain(
`/_next/data/${buildId}/gsp-fallback/fallback.json` `/_next/data/${buildId}/gsp-fallback/fallback.json`
) )
}) })
it('should work with getServerSideProps', async () => { it('should work with getServerSideProps', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await browser.waitForElementByCss('#gssp-link').click() await browser.waitForElementByCss('#gssp-link').click()
const prop = await browser.waitForElementByCss('#prop').text() const prop = await browser.waitForElementByCss('#prop').text()
expect(prop).toBe('foo') expect(prop).toBe('foo')
expect(cdnAccessLog).not.toContain( expect(cdnAccessLog).not.toContain(
`/_next/data/${buildId}/gssp.json?prop=foo` `/_next/data/${buildId}/gssp.json?prop=foo`
) )
}) })
}) }
)
}) })
...@@ -13,106 +13,113 @@ const nextConfig = new File(join(appDir, 'next.config.js')) ...@@ -13,106 +13,113 @@ const nextConfig = new File(join(appDir, 'next.config.js'))
let buildOutput let buildOutput
describe('AMP Validation on Export', () => { describe('AMP Validation on Export', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
const { stdout = '', stderr = '' } = await nextBuild(appDir, [], { () => {
stdout: true, beforeAll(async () => {
stderr: true, const { stdout = '', stderr = '' } = await nextBuild(appDir, [], {
stdout: true,
stderr: true,
})
buildOutput = stdout + stderr
}) })
buildOutput = stdout + stderr
})
it('should have shown errors during build', async () => { it('should have shown errors during build', async () => {
expect(buildOutput).toMatch( expect(buildOutput).toMatch(
/error.*The mandatory attribute 'height' is missing in tag 'amp-video'\./ /error.*The mandatory attribute 'height' is missing in tag 'amp-video'\./
) )
expect(existsSync(outDir)).toBeFalse() expect(existsSync(outDir)).toBeFalse()
}) })
// this is now an error instead of a warning // this is now an error instead of a warning
it.skip('shows AMP warning without throwing error', async () => { it.skip('shows AMP warning without throwing error', async () => {
nextConfig.replace( nextConfig.replace(
'// exportPathMap', '// exportPathMap',
`exportPathMap: function(defaultMap) { `exportPathMap: function(defaultMap) {
return { return {
'/cat': { page: '/cat' }, '/cat': { page: '/cat' },
} }
},` },`
)
try {
const { stdout, stderr } = await runNextCommand(['export', appDir], {
stdout: true,
stderr: true,
})
expect(stdout).toMatch(
/error.*The mandatory attribute 'height' is missing in tag 'amp-video'\./
)
await expect(access(join(outDir, 'cat.html'))).resolves.toBe(undefined)
await expect(stderr).not.toMatch(
/Found conflicting amp tag "meta" with conflicting prop name="viewport"/
) )
} finally {
nextConfig.restore()
}
})
// img instead of amp-img no longer shows a warning try {
it.skip('throws error on AMP error', async () => { const { stdout, stderr } = await runNextCommand(['export', appDir], {
nextConfig.replace( stdout: true,
'// exportPathMap', stderr: true,
`exportPathMap: function(defaultMap) { })
expect(stdout).toMatch(
/error.*The mandatory attribute 'height' is missing in tag 'amp-video'\./
)
await expect(access(join(outDir, 'cat.html'))).resolves.toBe(
undefined
)
await expect(stderr).not.toMatch(
/Found conflicting amp tag "meta" with conflicting prop name="viewport"/
)
} finally {
nextConfig.restore()
}
})
// img instead of amp-img no longer shows a warning
it.skip('throws error on AMP error', async () => {
nextConfig.replace(
'// exportPathMap',
`exportPathMap: function(defaultMap) {
return { return {
'/dog': { page: '/dog' }, '/dog': { page: '/dog' },
} }
},` },`
)
try {
const { stdout, stderr } = await runNextCommand(['export', appDir], {
stdout: true,
stderr: true,
})
expect(stdout).toMatch(
/error.*The parent tag of tag 'img' is 'div', but it can only be 'i-amphtml-sizer-intrinsic'\./
)
await expect(access(join(outDir, 'dog.html'))).resolves.toBe(undefined)
await expect(stderr).not.toMatch(
/Found conflicting amp tag "meta" with conflicting prop name="viewport"/
) )
} finally {
nextConfig.restore()
}
})
// img instead of amp-img no longer shows a warning try {
it.skip('shows warning and error when throwing error', async () => { const { stdout, stderr } = await runNextCommand(['export', appDir], {
nextConfig.replace( stdout: true,
'// exportPathMap', stderr: true,
`exportPathMap: function(defaultMap) { })
expect(stdout).toMatch(
/error.*The parent tag of tag 'img' is 'div', but it can only be 'i-amphtml-sizer-intrinsic'\./
)
await expect(access(join(outDir, 'dog.html'))).resolves.toBe(
undefined
)
await expect(stderr).not.toMatch(
/Found conflicting amp tag "meta" with conflicting prop name="viewport"/
)
} finally {
nextConfig.restore()
}
})
// img instead of amp-img no longer shows a warning
it.skip('shows warning and error when throwing error', async () => {
nextConfig.replace(
'// exportPathMap',
`exportPathMap: function(defaultMap) {
return { return {
'/dog-cat': { page: '/dog-cat' }, '/dog-cat': { page: '/dog-cat' },
} }
},` },`
)
try {
const { stdout, stderr } = await runNextCommand(['export', appDir], {
stdout: true,
stderr: true,
})
expect(stdout).toMatch(
/error.*The parent tag of tag 'img' is 'div', but it can only be 'i-amphtml-sizer-intrinsic'\./
)
await expect(access(join(outDir, 'dog-cat.html'))).resolves.toBe(
undefined
) )
await expect(stderr).not.toMatch(
/Found conflicting amp tag "meta" with conflicting prop name="viewport"/ try {
) const { stdout, stderr } = await runNextCommand(['export', appDir], {
} finally { stdout: true,
nextConfig.restore() stderr: true,
} })
}) expect(stdout).toMatch(
}) /error.*The parent tag of tag 'img' is 'div', but it can only be 'i-amphtml-sizer-intrinsic'\./
)
await expect(access(join(outDir, 'dog-cat.html'))).resolves.toBe(
undefined
)
await expect(stderr).not.toMatch(
/Found conflicting amp tag "meta" with conflicting prop name="viewport"/
)
} finally {
nextConfig.restore()
}
})
}
)
}) })
...@@ -14,43 +14,46 @@ let appPort ...@@ -14,43 +14,46 @@ let appPort
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
describe('AMP Custom Optimizer', () => { describe('AMP Custom Optimizer', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
it('should build and start for static page', async () => { 'production mode',
const { code } = await nextBuild(appDir) () => {
expect(code).toBe(0) it('should build and start for static page', async () => {
const { code } = await nextBuild(appDir)
appPort = await findPort() expect(code).toBe(0)
app = await nextStart(appDir, appPort)
appPort = await findPort()
const html = await renderViaHTTP(appPort, '/') app = await nextStart(appDir, appPort)
await killApp(app)
const html = await renderViaHTTP(appPort, '/')
expect(html).toContain( await killApp(app)
'amp-twitter width="500" height="500" layout="responsive" data-tweetid="1159145442896166912"'
) expect(html).toContain(
expect(html).toContain('i-amphtml-version="001515617716922"') 'amp-twitter width="500" height="500" layout="responsive" data-tweetid="1159145442896166912"'
expect(html).toContain( )
'script async src="https://cdn.ampproject.org/rtv/001515617716922/v0.mjs"' expect(html).toContain('i-amphtml-version="001515617716922"')
) expect(html).toContain(
}) 'script async src="https://cdn.ampproject.org/rtv/001515617716922/v0.mjs"'
)
it('should build and start for dynamic page', async () => { })
const { code } = await nextBuild(appDir)
expect(code).toBe(0) it('should build and start for dynamic page', async () => {
const { code } = await nextBuild(appDir)
appPort = await findPort() expect(code).toBe(0)
app = await nextStart(appDir, appPort)
appPort = await findPort()
const html = await renderViaHTTP(appPort, '/dynamic') app = await nextStart(appDir, appPort)
await killApp(app)
const html = await renderViaHTTP(appPort, '/dynamic')
expect(html).toContain( await killApp(app)
'amp-img width="500" height="500" layout="responsive" src="https://amp.dev/static/samples/img/story_dog2_portrait.jpg"'
) expect(html).toContain(
expect(html).toContain('i-amphtml-version="001515617716922"') 'amp-img width="500" height="500" layout="responsive" src="https://amp.dev/static/samples/img/story_dog2_portrait.jpg"'
expect(html).toContain( )
'script async src="https://cdn.ampproject.org/rtv/001515617716922/v0.mjs"' expect(html).toContain('i-amphtml-version="001515617716922"')
) expect(html).toContain(
}) 'script async src="https://cdn.ampproject.org/rtv/001515617716922/v0.mjs"'
}) )
})
}
)
}) })
...@@ -18,7 +18,7 @@ const appDir = join(__dirname, '../') ...@@ -18,7 +18,7 @@ const appDir = join(__dirname, '../')
;(process.env.TURBOPACK ? describe.skip : describe)( ;(process.env.TURBOPACK ? describe.skip : describe)(
'AMP Custom Validator', 'AMP Custom Validator',
() => { () => {
;(process.env.TURBOPACK ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode', 'production mode',
() => { () => {
it('should build and start successfully', async () => { it('should build and start successfully', async () => {
...@@ -37,7 +37,7 @@ const appDir = join(__dirname, '../') ...@@ -37,7 +37,7 @@ const appDir = join(__dirname, '../')
) )
describe('development mode', () => { describe('development mode', () => {
it('should run in dev mode successfully', async () => { it('should run in development mode successfully', async () => {
let stderr = '' let stderr = ''
appPort = await findPort() appPort = await findPort()
......
...@@ -16,21 +16,24 @@ let appPort ...@@ -16,21 +16,24 @@ let appPort
let app let app
describe('AMP Fragment Styles', () => { describe('AMP Fragment Styles', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
await nextBuild(appDir, []) () => {
appPort = await findPort() beforeAll(async () => {
app = await nextStart(appDir, appPort) await nextBuild(appDir, [])
}) appPort = await findPort()
afterAll(() => killApp(app)) app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
it('adds styles from fragment in AMP mode correctly', async () => { it('adds styles from fragment in AMP mode correctly', async () => {
const html = await renderViaHTTP(appPort, '/', { amp: 1 }) const html = await renderViaHTTP(appPort, '/', { amp: 1 })
await validateAMP(html) await validateAMP(html)
const $ = cheerio.load(html) const $ = cheerio.load(html)
const styles = $('style[amp-custom]').text() const styles = $('style[amp-custom]').text()
expect(styles).toMatch(/background:(.*|)hotpink/) expect(styles).toMatch(/background:(.*|)hotpink/)
expect(styles).toMatch(/font-size:(.*|)16\.4px/) expect(styles).toMatch(/font-size:(.*|)16\.4px/)
}) })
}) }
)
}) })
...@@ -99,18 +99,21 @@ const runTests = (isDev = false) => { ...@@ -99,18 +99,21 @@ const runTests = (isDev = false) => {
} }
describe('AMP SSG Support', () => { describe('AMP SSG Support', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
await nextBuild(appDir) () => {
appPort = await findPort() beforeAll(async () => {
app = await nextStart(appDir, appPort) await nextBuild(appDir)
// TODO: use browser instead to do checks that now need filesystem access appPort = await findPort()
builtServerPagesDir = join(appDir, '.next', 'server', 'pages') app = await nextStart(appDir, appPort)
}) // TODO: use browser instead to do checks that now need filesystem access
afterAll(() => killApp(app)) builtServerPagesDir = join(appDir, '.next', 'server', 'pages')
runTests() })
}) afterAll(() => killApp(app))
describe('dev mode', () => { runTests()
}
)
describe('development mode', () => {
beforeAll(async () => { beforeAll(async () => {
appPort = await findPort() appPort = await findPort()
app = await launchApp(appDir, appPort) app = await launchApp(appDir, appPort)
...@@ -119,7 +122,7 @@ describe('AMP SSG Support', () => { ...@@ -119,7 +122,7 @@ describe('AMP SSG Support', () => {
runTests(true) runTests(true)
}) })
describe('export mode', () => { describe('export mode', () => {
;(process.env.TURBOPACK ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode', 'production mode',
() => { () => {
let buildId let buildId
......
This diff is collapsed.
...@@ -59,14 +59,17 @@ describe('API routes', () => { ...@@ -59,14 +59,17 @@ describe('API routes', () => {
runTests() runTests()
}) })
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
await nextBuild(appDir) () => {
appPort = await findPort() beforeAll(async () => {
app = await nextStart(appDir, appPort) await nextBuild(appDir)
}) appPort = await findPort()
afterAll(() => killApp(app)) app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests() runTests()
}) }
)
}) })
...@@ -547,7 +547,7 @@ function runTests(dev = false) { ...@@ -547,7 +547,7 @@ function runTests(dev = false) {
expect(getPageFileFromPagesManifest(appDir, '/api/users')).toBeTruthy() expect(getPageFileFromPagesManifest(appDir, '/api/users')).toBeTruthy()
}) })
it('should show warning when the API resolves without ending the request in dev mode', async () => { it('should show warning when the API resolves without ending the request in development mode', async () => {
const controller = new AbortController() const controller = new AbortController()
setTimeout(() => { setTimeout(() => {
controller.abort() controller.abort()
...@@ -644,15 +644,18 @@ describe('API routes', () => { ...@@ -644,15 +644,18 @@ describe('API routes', () => {
runTests(true) runTests(true)
}) })
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
await nextBuild(appDir) () => {
mode = 'server' beforeAll(async () => {
appPort = await findPort() await nextBuild(appDir)
app = await nextStart(appDir, appPort) mode = 'server'
}) appPort = await findPort()
afterAll(() => killApp(app)) app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests() runTests()
}) }
)
}) })
...@@ -11,79 +11,84 @@ import { ...@@ -11,79 +11,84 @@ import {
} from './utils' } from './utils'
describe('app dir - with output export (next dev / next build)', () => { describe('app dir - with output export (next dev / next build)', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
it('should throw when exportPathMap configured', async () => { 'production mode',
nextConfig.replace( () => {
'trailingSlash: true,', it('should throw when exportPathMap configured', async () => {
`trailingSlash: true, nextConfig.replace(
'trailingSlash: true,',
`trailingSlash: true,
exportPathMap: async function (map) { exportPathMap: async function (map) {
return map return map
},` },`
) )
await fs.remove(distDir) await fs.remove(distDir)
await fs.remove(exportDir) await fs.remove(exportDir)
let result = { code: 0, stderr: '' } let result = { code: 0, stderr: '' }
try {
result = await nextBuild(appDir, [], { stderr: true })
} finally {
nextConfig.restore()
}
expect(result.code).toBe(1)
expect(result.stderr).toContain(
'The "exportPathMap" configuration cannot be used with the "app" directory. Please use generateStaticParams() instead.'
)
})
it('should error when running next export', async () => {
await fs.remove(distDir)
await fs.remove(exportDir)
nextConfig.delete()
try {
await nextBuild(appDir)
expect(await getFiles()).toEqual([])
let stdout = ''
let stderr = ''
let error = undefined
try { try {
await runNextCommand(['export', appDir], { result = await nextBuild(appDir, [], { stderr: true })
onStdout(msg) { } finally {
stdout += msg nextConfig.restore()
},
onStderr(msg) {
stderr += msg
},
})
} catch (e) {
error = e
} }
expect(error).toBeDefined() expect(result.code).toBe(1)
expect(stderr).toContain( expect(result.stderr).toContain(
`\`next export\` has been removed in favor of 'output: export' in next.config.js` 'The "exportPathMap" configuration cannot be used with the "app" directory. Please use generateStaticParams() instead.'
) )
expect(stdout).not.toContain('Export successful. Files written to') })
expect(await getFiles()).toEqual([]) it('should error when running next export', async () => {
} finally {
nextConfig.restore()
await fs.remove(distDir) await fs.remove(distDir)
await fs.remove(exportDir) await fs.remove(exportDir)
} nextConfig.delete()
}) try {
it('should correctly emit exported assets to config.distDir', async () => { await nextBuild(appDir)
const outputDir = join(appDir, 'output') expect(await getFiles()).toEqual([])
await fs.remove(distDir) let stdout = ''
await fs.remove(outputDir) let stderr = ''
nextConfig.replace( let error = undefined
'trailingSlash: true,', try {
`trailingSlash: true, await runNextCommand(['export', appDir], {
distDir: 'output',` onStdout(msg) {
) stdout += msg
try { },
await nextBuild(appDir) onStderr(msg) {
expect(await getFiles(outputDir)).toEqual(expectedWhenTrailingSlashTrue) stderr += msg
} finally { },
nextConfig.restore() })
} catch (e) {
error = e
}
expect(error).toBeDefined()
expect(stderr).toContain(
`\`next export\` has been removed in favor of 'output: export' in next.config.js`
)
expect(stdout).not.toContain('Export successful. Files written to')
expect(await getFiles()).toEqual([])
} finally {
nextConfig.restore()
await fs.remove(distDir)
await fs.remove(exportDir)
}
})
it('should correctly emit exported assets to config.distDir', async () => {
const outputDir = join(appDir, 'output')
await fs.remove(distDir) await fs.remove(distDir)
await fs.remove(outputDir) await fs.remove(outputDir)
} nextConfig.replace(
}) 'trailingSlash: true,',
}) `trailingSlash: true,
distDir: 'output',`
)
try {
await nextBuild(appDir)
expect(await getFiles(outputDir)).toEqual(
expectedWhenTrailingSlashTrue
)
} finally {
nextConfig.restore()
await fs.remove(distDir)
await fs.remove(outputDir)
}
})
}
)
}) })
import { runTests } from './utils' import { runTests } from './utils'
describe('app dir - with output export - dynamic missing gsp prod', () => { describe('app dir - with output export - dynamic missing gsp prod', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
it('should error when dynamic route is missing generateStaticParams', async () => { 'production mode',
await runTests({ () => {
isDev: false, it('should error when dynamic route is missing generateStaticParams', async () => {
dynamicPage: 'undefined', await runTests({
generateStaticParamsOpt: 'set noop', isDev: false,
expectedErrMsg: dynamicPage: 'undefined',
'Page "/another/[slug]" is missing "generateStaticParams()" so it cannot be used with "output: export" config.', generateStaticParamsOpt: 'set noop',
expectedErrMsg:
'Page "/another/[slug]" is missing "generateStaticParams()" so it cannot be used with "output: export" config.',
})
}) })
})
it('should error when client component has generateStaticParams', async () => { it('should error when client component has generateStaticParams', async () => {
await runTests({ await runTests({
isDev: false, isDev: false,
dynamicPage: 'undefined', dynamicPage: 'undefined',
generateStaticParamsOpt: 'set client', generateStaticParamsOpt: 'set client',
expectedErrMsg: expectedErrMsg:
'Page "/another/[slug]/page" cannot use both "use client" and export function "generateStaticParams()".', 'Page "/another/[slug]/page" cannot use both "use client" and export function "generateStaticParams()".',
})
}) })
}) }
}) )
}) })
import { runTests } from './utils' import { runTests } from './utils'
describe('app dir - with output export - dynamic api route prod', () => { describe('app dir - with output export - dynamic api route prod', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
it.each([ 'production mode',
{ dynamicApiRoute: 'undefined' }, () => {
{ dynamicApiRoute: "'error'" }, it.each([
{ dynamicApiRoute: "'force-static'" }, { dynamicApiRoute: 'undefined' },
{ { dynamicApiRoute: "'error'" },
dynamicApiRoute: "'force-dynamic'", { dynamicApiRoute: "'force-static'" },
expectedErrMsg: {
'export const dynamic = "force-dynamic" on page "/api/json" cannot be used with "output: export".', dynamicApiRoute: "'force-dynamic'",
}, expectedErrMsg:
])( 'export const dynamic = "force-dynamic" on page "/api/json" cannot be used with "output: export".',
'should work in prod with dynamicApiRoute $dynamicApiRoute', },
async ({ dynamicApiRoute, expectedErrMsg }) => { ])(
await runTests({ isDev: false, dynamicApiRoute, expectedErrMsg }) 'should work in prod with dynamicApiRoute $dynamicApiRoute',
} async ({ dynamicApiRoute, expectedErrMsg }) => {
) await runTests({ isDev: false, dynamicApiRoute, expectedErrMsg })
}) }
)
}
)
}) })
import { runTests } from './utils' import { runTests } from './utils'
describe('app dir - with output export - dynamic api route prod', () => { describe('app dir - with output export - dynamic api route prod', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
it.each([ 'production mode',
{ dynamicPage: 'undefined' }, () => {
{ dynamicPage: "'error'" }, it.each([
{ dynamicPage: "'force-static'" }, { dynamicPage: 'undefined' },
{ { dynamicPage: "'error'" },
dynamicPage: "'force-dynamic'", { dynamicPage: "'force-static'" },
expectedErrMsg: {
'Page with `dynamic = "force-dynamic"` couldn\'t be exported. `output: "export"` requires all pages be renderable statically', dynamicPage: "'force-dynamic'",
}, expectedErrMsg:
])( 'Page with `dynamic = "force-dynamic"` couldn\'t be exported. `output: "export"` requires all pages be renderable statically',
'should work in prod with dynamicPage $dynamicPage', },
async ({ dynamicPage, expectedErrMsg }) => { ])(
await runTests({ isDev: false, dynamicPage, expectedErrMsg }) 'should work in prod with dynamicPage $dynamicPage',
} async ({ dynamicPage, expectedErrMsg }) => {
) await runTests({ isDev: false, dynamicPage, expectedErrMsg })
}) }
)
}
)
}) })
...@@ -18,45 +18,48 @@ const nextConfig = new File(join(appDir, 'next.config.js')) ...@@ -18,45 +18,48 @@ const nextConfig = new File(join(appDir, 'next.config.js'))
let app let app
describe('app dir - with output export (next start)', () => { describe('app dir - with output export (next start)', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
afterEach(async () => { 'production mode',
await killApp(app) () => {
nextConfig.restore() afterEach(async () => {
await fs.remove(distDir) await killApp(app)
await fs.remove(exportDir) nextConfig.restore()
}) await fs.remove(distDir)
await fs.remove(exportDir)
})
it('should error during next start with output export', async () => { it('should error during next start with output export', async () => {
const { code } = await nextBuild(appDir) const { code } = await nextBuild(appDir)
expect(code).toBe(0) expect(code).toBe(0)
const port = await findPort() const port = await findPort()
let stderr = '' let stderr = ''
app = await nextStart(appDir, port, { app = await nextStart(appDir, port, {
onStderr(msg: string) { onStderr(msg: string) {
stderr += msg || '' stderr += msg || ''
}, },
})
await check(() => stderr, /error/i)
expect(stderr).toContain(
'"next start" does not work with "output: export" configuration. Use "npx serve@latest out" instead.'
)
}) })
await check(() => stderr, /error/i)
expect(stderr).toContain(
'"next start" does not work with "output: export" configuration. Use "npx serve@latest out" instead.'
)
})
it('should warn during next start with output standalone', async () => { it('should warn during next start with output standalone', async () => {
nextConfig.replace(`output: 'export'`, `output: 'standalone'`) nextConfig.replace(`output: 'export'`, `output: 'standalone'`)
const { code } = await nextBuild(appDir) const { code } = await nextBuild(appDir)
expect(code).toBe(0) expect(code).toBe(0)
const port = await findPort() const port = await findPort()
let stderr = '' let stderr = ''
app = await nextStart(appDir, port, { app = await nextStart(appDir, port, {
onStderr(msg: string) { onStderr(msg: string) {
stderr += msg || '' stderr += msg || ''
}, },
})
await check(() => stderr, /⚠/i)
expect(stderr).toContain(
`"next start" does not work with "output: standalone" configuration. Use "node .next/standalone/server.js" instead.`
)
}) })
await check(() => stderr, /⚠/i) }
expect(stderr).toContain( )
`"next start" does not work with "output: standalone" configuration. Use "node .next/standalone/server.js" instead.`
)
})
})
}) })
import { runTests } from './utils' import { runTests } from './utils'
describe('app dir - with output export - trailing slash prod', () => { describe('app dir - with output export - trailing slash prod', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
it.each([{ trailingSlash: false }, { trailingSlash: true }])( 'production mode',
"should work in prod with trailingSlash '$trailingSlash'", () => {
async ({ trailingSlash }) => { it.each([{ trailingSlash: false }, { trailingSlash: true }])(
await runTests({ isDev: false, trailingSlash }) "should work in prod with trailingSlash '$trailingSlash'",
} async ({ trailingSlash }) => {
) await runTests({ isDev: false, trailingSlash })
}) }
)
}
)
}) })
...@@ -51,23 +51,26 @@ const respectsChunkAttachmentOrder = async () => { ...@@ -51,23 +51,26 @@ const respectsChunkAttachmentOrder = async () => {
} }
describe('Root components import order', () => { describe('Root components import order', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
await nextBuild(appDir) () => {
appPort = await findPort() beforeAll(async () => {
app = await nextStart(appDir, appPort) await nextBuild(appDir)
}) appPort = await findPort()
afterAll(() => killApp(app)) app = await nextStart(appDir, appPort)
})
it( afterAll(() => killApp(app))
'_app chunks should be attached to de dom before page chunks',
respectsChunkAttachmentOrder it(
) '_app chunks should be attached to de dom before page chunks',
it( respectsChunkAttachmentOrder
'root components should be imported in this order _document > _app > page in order to respect side effects', )
respectsSideEffects it(
) 'root components should be imported in this order _document > _app > page in order to respect side effects',
}) respectsSideEffects
)
}
)
}) })
describe('development mode', () => { describe('development mode', () => {
......
...@@ -16,27 +16,30 @@ let server ...@@ -16,27 +16,30 @@ let server
let app let app
describe('Custom Document Fragment Styles', () => { describe('Custom Document Fragment Styles', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
await nextBuild(appDir) () => {
app = nextServer({ beforeAll(async () => {
dir: join(__dirname, '../'), await nextBuild(appDir)
dev: false, app = nextServer({
quiet: true, dir: join(__dirname, '../'),
}) dev: false,
quiet: true,
})
server = await startApp(app) server = await startApp(app)
appPort = server.address().port appPort = server.address().port
}) })
afterAll(() => stopApp(server)) afterAll(() => stopApp(server))
it('correctly adds styles from fragment styles key', async () => { it('correctly adds styles from fragment styles key', async () => {
const html = await renderViaHTTP(appPort, '/') const html = await renderViaHTTP(appPort, '/')
const $ = cheerio.load(html) const $ = cheerio.load(html)
const styles = $('style').text() const styles = $('style').text()
expect(styles).toMatch(/background:(.*|)hotpink/) expect(styles).toMatch(/background:(.*|)hotpink/)
expect(styles).toMatch(/font-size:(.*|)16\.4px/) expect(styles).toMatch(/font-size:(.*|)16\.4px/)
}) })
}) }
)
}) })
import { nextBuild } from 'next-test-utils' import { nextBuild } from 'next-test-utils'
import { join } from 'path' import { join } from 'path'
describe('app-dynamic-error', () => { describe('app-dynamic-error', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
it('throws an error when prerendering a page with config dynamic error', async () => { 'production mode',
const appDir = join(__dirname, '../../app-dynamic-error') () => {
const { stderr, code } = await nextBuild(appDir, [], { it('throws an error when prerendering a page with config dynamic error', async () => {
stderr: true, const appDir = join(__dirname, '../../app-dynamic-error')
stdout: true, const { stderr, code } = await nextBuild(appDir, [], {
stderr: true,
stdout: true,
})
expect(stderr).toContain(
'Error occurred prerendering page "/dynamic-error"'
)
expect(code).toBe(1)
}) })
expect(stderr).toContain( }
'Error occurred prerendering page "/dynamic-error"' )
)
expect(code).toBe(1)
})
})
}) })
...@@ -48,7 +48,7 @@ const runTests = () => { ...@@ -48,7 +48,7 @@ const runTests = () => {
} }
describe('AppTree', () => { describe('AppTree', () => {
describe('dev mode', () => { describe('development mode', () => {
beforeAll(async () => { beforeAll(async () => {
appPort = await findPort() appPort = await findPort()
app = await launchApp(appDir, appPort) app = await launchApp(appDir, appPort)
...@@ -56,13 +56,16 @@ describe('AppTree', () => { ...@@ -56,13 +56,16 @@ describe('AppTree', () => {
afterAll(() => killApp(app)) afterAll(() => killApp(app))
runTests() runTests()
}) })
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
await nextBuild(appDir) () => {
appPort = await findPort() beforeAll(async () => {
app = await nextStart(appDir, appPort) await nextBuild(appDir)
}) appPort = await findPort()
afterAll(() => killApp(app)) app = await nextStart(appDir, appPort)
runTests() })
}) afterAll(() => killApp(app))
runTests()
}
)
}) })
...@@ -7,103 +7,106 @@ import { nextBuild } from 'next-test-utils' ...@@ -7,103 +7,106 @@ import { nextBuild } from 'next-test-utils'
const appDir = __dirname const appDir = __dirname
describe('app type checking', () => { describe('app type checking', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
let stderr, errors 'production mode',
beforeAll(async () => { () => {
stderr = (await nextBuild(appDir, [], { stderr: true })).stderr let stderr, errors
beforeAll(async () => {
errors = stderr.match( stderr = (await nextBuild(appDir, [], { stderr: true })).stderr
/===== TS errors =====(.+)===== TS errors =====/s
)?.[1] errors = stderr.match(
}) /===== TS errors =====(.+)===== TS errors =====/s
)?.[1]
it('should generate route types correctly and report link error', async () => { })
// Make sure the d.ts file is generated
const dts = ( it('should generate route types correctly and report link error', async () => {
await fs.readFile(path.join(appDir, '.next', 'types', 'link.d.ts')) // Make sure the d.ts file is generated
).toString() const dts = (
expect(dts.includes('`/dashboard/user/')).toBeTruthy() await fs.readFile(path.join(appDir, '.next', 'types', 'link.d.ts'))
expect(dts.includes('`/dashboard/another')).toBeTruthy() ).toString()
expect(dts.includes('`/dashboard/user/')).toBeTruthy()
// Check type checking errors expect(dts.includes('`/dashboard/another')).toBeTruthy()
expect(errors).toContain(
'Type error: "/(newroot)/dashboard/another" is not an existing route. If it is intentional, please type it explicitly with `as Route`.' // Check type checking errors
) expect(errors).toContain(
'Type error: "/(newroot)/dashboard/another" is not an existing route. If it is intentional, please type it explicitly with `as Route`.'
// Make sure all errors were reported and other links passed type checking )
const errorLines = [
...errors.matchAll( // Make sure all errors were reported and other links passed type checking
/\.\/src\/app\/type-checks\/link\/page\.tsx:(\d+):/g const errorLines = [
), ...errors.matchAll(
].map(([, line]) => +line) /\.\/src\/app\/type-checks\/link\/page\.tsx:(\d+):/g
),
const ST = 17 ].map(([, line]) => +line)
const ED = 34
expect(errorLines).toEqual( const ST = 17
Array.from({ length: ED - ST + 1 }, (_, i) => i + ST) const ED = 34
) expect(errorLines).toEqual(
}) Array.from({ length: ED - ST + 1 }, (_, i) => i + ST)
)
it('should generate route types correctly and report router API errors', async () => { })
// Make sure all errors were reported and other links passed type checking
const errorLines = [ it('should generate route types correctly and report router API errors', async () => {
...errors.matchAll( // Make sure all errors were reported and other links passed type checking
/\.\/src\/app\/type-checks\/router\/page\.tsx:(\d+):/g const errorLines = [
), ...errors.matchAll(
].map(([, line]) => +line) /\.\/src\/app\/type-checks\/router\/page\.tsx:(\d+):/g
),
const ST = 11 ].map(([, line]) => +line)
const ED = 13
expect(errorLines).toEqual( const ST = 11
Array.from({ length: ED - ST + 1 }, (_, i) => i + ST) const ED = 13
) expect(errorLines).toEqual(
}) Array.from({ length: ED - ST + 1 }, (_, i) => i + ST)
)
it('should type check invalid entry exports', () => { })
// Can't export arbitrary things.
expect(errors).toContain(`"foo" is not a valid Page export field.`) it('should type check invalid entry exports', () => {
// Can't export arbitrary things.
// Can't export invalid fields. expect(errors).toContain(`"foo" is not a valid Page export field.`)
expect(errors).toMatch(
/Invalid configuration "revalidate":\s+Expected "false | number (>= 0)", got "-1"/ // Can't export invalid fields.
) expect(errors).toMatch(
/Invalid configuration "revalidate":\s+Expected "false | number (>= 0)", got "-1"/
// Avoid invalid argument types for exported functions. )
expect(errors).toMatch(
/Page "src\/app\/type-checks\/config\/page\.tsx" has an invalid "default" export:\s+Type "{ foo: string; }" is not valid/ // Avoid invalid argument types for exported functions.
) expect(errors).toMatch(
expect(errors).toMatch( /Page "src\/app\/type-checks\/config\/page\.tsx" has an invalid "default" export:\s+Type "{ foo: string; }" is not valid/
/Page "src\/app\/type-checks\/config\/page\.tsx" has an invalid "generateMetadata" export:\s+Type "{ s: number; }" is not valid/ )
) expect(errors).toMatch(
expect(errors).toMatch( /Page "src\/app\/type-checks\/config\/page\.tsx" has an invalid "generateMetadata" export:\s+Type "{ s: number; }" is not valid/
/Page "src\/app\/type-checks\/config\/page\.tsx" has an invalid "generateStaticParams" export:\s+Type "string" is not valid/ )
) expect(errors).toMatch(
/Page "src\/app\/type-checks\/config\/page\.tsx" has an invalid "generateStaticParams" export:\s+Type "string" is not valid/
// Avoid invalid return types for exported functions. )
expect(errors).toContain(
`"Promise<number>" is not a valid generateStaticParams return type` // Avoid invalid return types for exported functions.
) expect(errors).toContain(
`"Promise<number>" is not a valid generateStaticParams return type`
// Can't export arbitrary things. )
expect(errors).toContain(`"bar" is not a valid Route export field.`)
// Can't export arbitrary things.
// Can't export invalid fields. expect(errors).toContain(`"bar" is not a valid Route export field.`)
expect(errors).toMatch(
/Invalid configuration "revalidate":\s+Expected "false | number (>= 0)", got "-1"/ // Can't export invalid fields.
) expect(errors).toMatch(
/Invalid configuration "revalidate":\s+Expected "false | number (>= 0)", got "-1"/
// Avoid invalid argument types for exported functions. )
expect(errors).toMatch(
/Route "src\/app\/type-checks\/route-handlers\/route\.ts" has an invalid "GET" export:\s+Type "boolean" is not a valid type for the function's first argument/ // Avoid invalid argument types for exported functions.
) expect(errors).toMatch(
expect(errors).toMatch( /Route "src\/app\/type-checks\/route-handlers\/route\.ts" has an invalid "GET" export:\s+Type "boolean" is not a valid type for the function's first argument/
/Route "src\/app\/type-checks\/route-handlers\/route\.ts" has an invalid "generateStaticParams" export:\s+Type "string" is not valid/ )
) expect(errors).toMatch(
/Route "src\/app\/type-checks\/route-handlers\/route\.ts" has an invalid "generateStaticParams" export:\s+Type "string" is not valid/
// Avoid invalid return types for exported functions. )
expect(errors).toContain(
`"Promise<boolean>" is not a valid generateStaticParams return type` // Avoid invalid return types for exported functions.
) expect(errors).toContain(
}) `"Promise<boolean>" is not a valid generateStaticParams return type`
}) )
})
}
)
}) })
...@@ -104,7 +104,7 @@ function runTests(dev = false) { ...@@ -104,7 +104,7 @@ function runTests(dev = false) {
} }
describe('Async modules', () => { describe('Async modules', () => {
describe('dev mode', () => { describe('development mode', () => {
beforeAll(async () => { beforeAll(async () => {
appPort = await findPort() appPort = await findPort()
app = await launchApp(appDir, appPort) app = await launchApp(appDir, appPort)
...@@ -115,16 +115,19 @@ describe('Async modules', () => { ...@@ -115,16 +115,19 @@ describe('Async modules', () => {
runTests(true) runTests(true)
}) })
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
await nextBuild(appDir) () => {
appPort = await findPort() beforeAll(async () => {
app = await nextStart(appDir, appPort) await nextBuild(appDir)
}) appPort = await findPort()
afterAll(async () => { app = await nextStart(appDir, appPort)
await killApp(app) })
}) afterAll(async () => {
await killApp(app)
})
runTests() runTests()
}) }
)
}) })
...@@ -30,7 +30,10 @@ const runTests = () => { ...@@ -30,7 +30,10 @@ const runTests = () => {
} }
describe('Auto Export _error bail', () => { describe('Auto Export _error bail', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
runTests() 'production mode',
}) () => {
runTests()
}
)
}) })
...@@ -21,15 +21,22 @@ const runTests = () => { ...@@ -21,15 +21,22 @@ const runTests = () => {
} }
describe('Auto Export', () => { describe('Auto Export', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
const { stderr: curStderr, code: curCode } = await nextBuild(appDir, [], { () => {
stderr: true, beforeAll(async () => {
const { stderr: curStderr, code: curCode } = await nextBuild(
appDir,
[],
{
stderr: true,
}
)
stderr = curStderr
exitCode = curCode
}) })
stderr = curStderr
exitCode = curCode
})
runTests() runTests()
}) }
)
}) })
...@@ -57,19 +57,22 @@ const runTests = () => { ...@@ -57,19 +57,22 @@ const runTests = () => {
} }
describe('Auto Export', () => { describe('Auto Export', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
await nextBuild(appDir) () => {
appPort = await findPort() beforeAll(async () => {
app = await nextStart(appDir, appPort) await nextBuild(appDir)
}) appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => { afterAll(async () => {
await killApp(app) await killApp(app)
}) })
runTests() runTests()
}) }
)
describe('dev', () => { describe('dev', () => {
beforeAll(async () => { beforeAll(async () => {
......
...@@ -28,7 +28,7 @@ const runTests = () => { ...@@ -28,7 +28,7 @@ const runTests = () => {
} }
// Skip as it runs `next build`, seems that is a bug. // Skip as it runs `next build`, seems that is a bug.
;(process.env.TURBOPACK ? describe.skip : describe)('dev mode', () => { ;(process.env.TURBOPACK ? describe.skip : describe)('development mode', () => {
beforeAll(async () => { beforeAll(async () => {
// TODO: This look like a bug, `nextBuild` shouldn't be required here. // TODO: This look like a bug, `nextBuild` shouldn't be required here.
await nextBuild(appDir) await nextBuild(appDir)
...@@ -39,13 +39,16 @@ const runTests = () => { ...@@ -39,13 +39,16 @@ const runTests = () => {
afterAll(() => killApp(app)) afterAll(() => killApp(app))
runTests() runTests()
}) })
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
await nextBuild(appDir) () => {
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8') beforeAll(async () => {
appPort = await findPort() await nextBuild(appDir)
app = await nextStart(appDir, appPort) buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
}) appPort = await findPort()
afterAll(() => killApp(app)) app = await nextStart(appDir, appPort)
runTests() })
}) afterAll(() => killApp(app))
runTests()
}
)
...@@ -33,7 +33,7 @@ const runTests = () => { ...@@ -33,7 +33,7 @@ const runTests = () => {
} }
describe('bigint API route support', () => { describe('bigint API route support', () => {
describe('dev mode', () => { describe('development mode', () => {
beforeAll(async () => { beforeAll(async () => {
appPort = await findPort() appPort = await findPort()
app = await launchApp(appDir, appPort) app = await launchApp(appDir, appPort)
...@@ -42,15 +42,18 @@ describe('bigint API route support', () => { ...@@ -42,15 +42,18 @@ describe('bigint API route support', () => {
runTests() runTests()
}) })
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
await fs.remove(nextConfig) () => {
await nextBuild(appDir) beforeAll(async () => {
appPort = await findPort() await fs.remove(nextConfig)
app = await nextStart(appDir, appPort) await nextBuild(appDir)
}) appPort = await findPort()
afterAll(() => killApp(app)) app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests() runTests()
}) }
)
}) })
...@@ -7,88 +7,93 @@ import { nextBuild } from 'next-test-utils' ...@@ -7,88 +7,93 @@ import { nextBuild } from 'next-test-utils'
const appDir = join(__dirname, '../app') const appDir = join(__dirname, '../app')
describe('build trace with extra entries', () => { describe('build trace with extra entries', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
it('should build and trace correctly', async () => { 'production mode',
const result = await nextBuild(appDir, undefined, { () => {
cwd: appDir, it('should build and trace correctly', async () => {
stderr: true, const result = await nextBuild(appDir, undefined, {
stdout: true, cwd: appDir,
}) stderr: true,
console.log(result) stdout: true,
expect(result.code).toBe(0) })
console.log(result)
const appTrace = await fs.readJSON( expect(result.code).toBe(0)
join(appDir, '.next/server/pages/_app.js.nft.json')
)
const indexTrace = await fs.readJSON(
join(appDir, '.next/server/pages/index.js.nft.json')
)
const anotherTrace = await fs.readJSON(
join(appDir, '.next/server/pages/another.js.nft.json')
)
const imageTrace = await fs.readJSON(
join(appDir, '.next/server/pages/image-import.js.nft.json')
)
const appDirRoute1Trace = await fs.readJSON(
join(appDir, '.next/server/app/route1/route.js.nft.json')
)
expect( const appTrace = await fs.readJSON(
appDirRoute1Trace.files.some( join(appDir, '.next/server/pages/_app.js.nft.json')
(file) => file === '../../../../include-me/hello.txt' )
const indexTrace = await fs.readJSON(
join(appDir, '.next/server/pages/index.js.nft.json')
)
const anotherTrace = await fs.readJSON(
join(appDir, '.next/server/pages/another.js.nft.json')
)
const imageTrace = await fs.readJSON(
join(appDir, '.next/server/pages/image-import.js.nft.json')
) )
).toBe(true) const appDirRoute1Trace = await fs.readJSON(
expect( join(appDir, '.next/server/app/route1/route.js.nft.json')
appDirRoute1Trace.files.some(
(file) => file === '../../../../include-me/second.txt'
) )
).toBe(true)
expect(
appDirRoute1Trace.files.some((file) => file.includes('exclude-me'))
).toBe(false)
const tracedFiles = [ expect(
...appTrace.files, appDirRoute1Trace.files.some(
...indexTrace.files, (file) => file === '../../../../include-me/hello.txt'
...anotherTrace.files, )
...imageTrace.files, ).toBe(true)
] expect(
appDirRoute1Trace.files.some(
(file) => file === '../../../../include-me/second.txt'
)
).toBe(true)
expect(
appDirRoute1Trace.files.some((file) => file.includes('exclude-me'))
).toBe(false)
expect(tracedFiles.some((file) => file.endsWith('hello.json'))).toBe(true) const tracedFiles = [
expect( ...appTrace.files,
tracedFiles.some((file) => file.includes('some-cms/index.js')) ...indexTrace.files,
).toBe(true) ...anotherTrace.files,
expect( ...imageTrace.files,
tracedFiles.some((file) => file === '../../../include-me/hello.txt') ]
).toBe(true)
expect(
tracedFiles.some((file) => file === '../../../include-me/second.txt')
).toBe(true)
expect(indexTrace.files.some((file) => file.includes('exclude-me'))).toBe(
false
)
expect( expect(tracedFiles.some((file) => file.endsWith('hello.json'))).toBe(
tracedFiles.some((file) => true
file.includes('nested-structure/constants/package.json')
) )
).toBe(true) expect(
expect( tracedFiles.some((file) => file.includes('some-cms/index.js'))
tracedFiles.some((file) => ).toBe(true)
file.includes('nested-structure/package.json') expect(
) tracedFiles.some((file) => file === '../../../include-me/hello.txt')
).toBe(true) ).toBe(true)
expect( expect(
tracedFiles.some((file) => tracedFiles.some((file) => file === '../../../include-me/second.txt')
file.includes('nested-structure/dist/constants.js') ).toBe(true)
) expect(
).toBe(true) indexTrace.files.some((file) => file.includes('exclude-me'))
expect( ).toBe(false)
tracedFiles.some((file) => file.includes('public/another.jpg'))
).toBe(true) expect(
expect(tracedFiles.some((file) => file.includes('public/test.jpg'))).toBe( tracedFiles.some((file) =>
false file.includes('nested-structure/constants/package.json')
) )
}) ).toBe(true)
}) expect(
tracedFiles.some((file) =>
file.includes('nested-structure/package.json')
)
).toBe(true)
expect(
tracedFiles.some((file) =>
file.includes('nested-structure/dist/constants.js')
)
).toBe(true)
expect(
tracedFiles.some((file) => file.includes('public/another.jpg'))
).toBe(true)
expect(
tracedFiles.some((file) => file.includes('public/test.jpg'))
).toBe(false)
})
}
)
}) })
...@@ -7,115 +7,118 @@ import { nextBuild } from 'next-test-utils' ...@@ -7,115 +7,118 @@ import { nextBuild } from 'next-test-utils'
const appDir = join(__dirname, '../app') const appDir = join(__dirname, '../app')
describe('build trace with extra entries', () => { describe('build trace with extra entries', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
it('should build and trace correctly', async () => { 'production mode',
const result = await nextBuild(appDir, undefined, { () => {
cwd: appDir, it('should build and trace correctly', async () => {
stderr: true, const result = await nextBuild(appDir, undefined, {
stdout: true, cwd: appDir,
}) stderr: true,
console.log(result) stdout: true,
expect(result.code).toBe(0) })
console.log(result)
const appTrace = await fs.readJSON( expect(result.code).toBe(0)
join(appDir, '.next/server/pages/_app.js.nft.json')
)
const indexTrace = await fs.readJSON(
join(appDir, '.next/server/pages/index.js.nft.json')
)
const anotherTrace = await fs.readJSON(
join(appDir, '.next/server/pages/another.js.nft.json')
)
const imageTrace = await fs.readJSON(
join(appDir, '.next/server/pages/image-import.js.nft.json')
)
const appDirRoute1Trace = await fs.readJSON(
join(appDir, '.next/server/app/route1/route.js.nft.json')
)
expect( const appTrace = await fs.readJSON(
appDirRoute1Trace.files.some( join(appDir, '.next/server/pages/_app.js.nft.json')
(file) => file === '../../../../include-me/hello.txt'
) )
).toBe(true) const indexTrace = await fs.readJSON(
expect( join(appDir, '.next/server/pages/index.js.nft.json')
appDirRoute1Trace.files.some(
(file) => file === '../../../../include-me/second.txt'
) )
).toBe(true) const anotherTrace = await fs.readJSON(
expect( join(appDir, '.next/server/pages/another.js.nft.json')
appDirRoute1Trace.files.some((file) => file.includes('exclude-me'))
).toBe(false)
expect(appTrace.files.some((file) => file.endsWith('hello.json'))).toBe(
true
)
expect(
indexTrace.files.filter(
(file) => file.includes('chunks') && file.endsWith('.js')
).length
).toBeGreaterThan(
anotherTrace.files.filter(
(file) => file.includes('chunks') && file.endsWith('.js')
).length
)
expect(
appTrace.files.some((file) => file.endsWith('lib/get-data.js'))
).toBe(true)
expect(
indexTrace.files.some((file) => file.endsWith('hello.json'))
).toBeFalsy()
expect(
indexTrace.files.some((file) => file.endsWith('some-dir'))
).toBeFalsy()
expect(
indexTrace.files.some((file) =>
file.endsWith('.dot-folder/another-file.txt')
) )
).toBe(true) const imageTrace = await fs.readJSON(
expect( join(appDir, '.next/server/pages/image-import.js.nft.json')
indexTrace.files.some((file) => file.endsWith('some-dir/file.txt'))
).toBe(true)
expect(
indexTrace.files.some((file) => file.includes('some-cms/index.js'))
).toBe(true)
expect(
indexTrace.files.some(
(file) => file === '../../../include-me/hello.txt'
) )
).toBe(true) const appDirRoute1Trace = await fs.readJSON(
expect( join(appDir, '.next/server/app/route1/route.js.nft.json')
indexTrace.files.some(
(file) => file === '../../../include-me/second.txt'
) )
).toBe(true)
expect(indexTrace.files.some((file) => file.includes('exclude-me'))).toBe(
false
)
expect( expect(
anotherTrace.files.some((file) => appDirRoute1Trace.files.some(
file.includes('nested-structure/constants/package.json') (file) => file === '../../../../include-me/hello.txt'
) )
).toBe(true) ).toBe(true)
expect( expect(
anotherTrace.files.some((file) => appDirRoute1Trace.files.some(
file.includes('nested-structure/package.json') (file) => file === '../../../../include-me/second.txt'
)
).toBe(true)
expect(
appDirRoute1Trace.files.some((file) => file.includes('exclude-me'))
).toBe(false)
expect(appTrace.files.some((file) => file.endsWith('hello.json'))).toBe(
true
) )
).toBe(true)
expect( expect(
anotherTrace.files.some((file) => indexTrace.files.filter(
file.includes('nested-structure/dist/constants.js') (file) => file.includes('chunks') && file.endsWith('.js')
).length
).toBeGreaterThan(
anotherTrace.files.filter(
(file) => file.includes('chunks') && file.endsWith('.js')
).length
) )
).toBe(true)
expect( expect(
imageTrace.files.some((file) => file.includes('public/another.jpg')) appTrace.files.some((file) => file.endsWith('lib/get-data.js'))
).toBe(true) ).toBe(true)
expect( expect(
imageTrace.files.some((file) => file.includes('public/test.jpg')) indexTrace.files.some((file) => file.endsWith('hello.json'))
).toBe(false) ).toBeFalsy()
}) expect(
}) indexTrace.files.some((file) => file.endsWith('some-dir'))
).toBeFalsy()
expect(
indexTrace.files.some((file) =>
file.endsWith('.dot-folder/another-file.txt')
)
).toBe(true)
expect(
indexTrace.files.some((file) => file.endsWith('some-dir/file.txt'))
).toBe(true)
expect(
indexTrace.files.some((file) => file.includes('some-cms/index.js'))
).toBe(true)
expect(
indexTrace.files.some(
(file) => file === '../../../include-me/hello.txt'
)
).toBe(true)
expect(
indexTrace.files.some(
(file) => file === '../../../include-me/second.txt'
)
).toBe(true)
expect(
indexTrace.files.some((file) => file.includes('exclude-me'))
).toBe(false)
expect(
anotherTrace.files.some((file) =>
file.includes('nested-structure/constants/package.json')
)
).toBe(true)
expect(
anotherTrace.files.some((file) =>
file.includes('nested-structure/package.json')
)
).toBe(true)
expect(
anotherTrace.files.some((file) =>
file.includes('nested-structure/dist/constants.js')
)
).toBe(true)
expect(
imageTrace.files.some((file) => file.includes('public/another.jpg'))
).toBe(true)
expect(
imageTrace.files.some((file) => file.includes('public/test.jpg'))
).toBe(false)
})
}
)
}) })
...@@ -7,85 +7,88 @@ import { join } from 'path' ...@@ -7,85 +7,88 @@ import { join } from 'path'
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
describe('Build warnings', () => { describe('Build warnings', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
it('should not shown warning about minification without any modification', async () => { 'production mode',
const { stderr } = await nextBuild(appDir, undefined, { stderr: true }) () => {
expect(stderr).not.toContain('optimization has been disabled') it('should not shown warning about minification without any modification', async () => {
}) const { stderr } = await nextBuild(appDir, undefined, { stderr: true })
expect(stderr).not.toContain('optimization has been disabled')
it('should shown warning about minification for minimize', async () => { })
const nextConfig = new File(join(appDir, 'next.config.js'))
await waitFor(500) it('should shown warning about minification for minimize', async () => {
const nextConfig = new File(join(appDir, 'next.config.js'))
nextConfig.replace('true', 'false') await waitFor(500)
const { stderr } = await nextBuild(appDir, undefined, { stderr: true }) nextConfig.replace('true', 'false')
expect(stderr).toContain('optimization has been disabled') const { stderr } = await nextBuild(appDir, undefined, { stderr: true })
nextConfig.restore() expect(stderr).toContain('optimization has been disabled')
})
it('should shown warning about minification for minimizer', async () => { nextConfig.restore()
const nextConfig = new File(join(appDir, 'next.config.js')) })
await waitFor(500) it('should shown warning about minification for minimizer', async () => {
const nextConfig = new File(join(appDir, 'next.config.js'))
nextConfig.replace( await waitFor(500)
'config.optimization.minimize = true',
'config.optimization.minimizer = []'
)
const { stderr } = await nextBuild(appDir, undefined, { stderr: true }) nextConfig.replace(
'config.optimization.minimize = true',
'config.optimization.minimizer = []'
)
expect(stderr).toContain('optimization has been disabled') const { stderr } = await nextBuild(appDir, undefined, { stderr: true })
nextConfig.restore() expect(stderr).toContain('optimization has been disabled')
})
it('should not warn about missing cache in non-CI', async () => { nextConfig.restore()
await remove(join(appDir, '.next')) })
const { stdout } = await nextBuild(appDir, undefined, { it('should not warn about missing cache in non-CI', async () => {
stdout: true, await remove(join(appDir, '.next'))
env: {
CI: '', const { stdout } = await nextBuild(appDir, undefined, {
CIRCLECI: '', stdout: true,
TRAVIS: '', env: {
SYSTEM_TEAMFOUNDATIONCOLLECTIONURI: '', CI: '',
GITHUB_ACTIONS: '', CIRCLECI: '',
GITHUB_EVENT_NAME: '', TRAVIS: '',
}, SYSTEM_TEAMFOUNDATIONCOLLECTIONURI: '',
GITHUB_ACTIONS: '',
GITHUB_EVENT_NAME: '',
},
})
expect(stdout).not.toContain('no-cache')
}) })
expect(stdout).not.toContain('no-cache')
})
it('should not warn about missing cache on supported platforms', async () => { it('should not warn about missing cache on supported platforms', async () => {
await remove(join(appDir, '.next')) await remove(join(appDir, '.next'))
const { stdout } = await nextBuild(appDir, undefined, { const { stdout } = await nextBuild(appDir, undefined, {
stdout: true, stdout: true,
env: { CI: '1', NOW_BUILDER: '1' }, env: { CI: '1', NOW_BUILDER: '1' },
})
expect(stdout).not.toContain('no-cache')
}) })
expect(stdout).not.toContain('no-cache')
})
it('should warn about missing cache in CI', async () => {
await remove(join(appDir, '.next'))
let { stdout } = await nextBuild(appDir, undefined, { it('should warn about missing cache in CI', async () => {
stdout: true, await remove(join(appDir, '.next'))
env: { CI: '1' },
let { stdout } = await nextBuild(appDir, undefined, {
stdout: true,
env: { CI: '1' },
})
expect(stdout).toContain('no-cache')
// Do not warn after cache is present
;({ stdout } = await nextBuild(appDir, undefined, {
stdout: true,
env: { CI: '1' },
}))
expect(stdout).not.toContain('no-cache')
}) })
expect(stdout).toContain('no-cache') }
)
// Do not warn after cache is present
;({ stdout } = await nextBuild(appDir, undefined, {
stdout: true,
env: { CI: '1' },
}))
expect(stdout).not.toContain('no-cache')
})
})
}) })
...@@ -14,7 +14,7 @@ const errorRegex = /getStaticPaths was added without a getStaticProps in/ ...@@ -14,7 +14,7 @@ const errorRegex = /getStaticPaths was added without a getStaticProps in/
describe('Catches Missing getStaticProps', () => { describe('Catches Missing getStaticProps', () => {
describe('development mode', () => { describe('development mode', () => {
it('should catch it in dev mode', async () => { it('should catch it in development mode', async () => {
const appPort = await findPort() const appPort = await findPort()
const app = await launchApp(appDir, appPort) const app = await launchApp(appDir, appPort)
const html = await renderViaHTTP(appPort, '/hello') const html = await renderViaHTTP(appPort, '/hello')
...@@ -23,12 +23,15 @@ describe('Catches Missing getStaticProps', () => { ...@@ -23,12 +23,15 @@ describe('Catches Missing getStaticProps', () => {
expect(html).toMatch(errorRegex) expect(html).toMatch(errorRegex)
}) })
}) })
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
it('should catch it in server build mode', async () => { 'production mode',
const { stderr } = await nextBuild(appDir, [], { () => {
stderr: true, it('should catch it in server build mode', async () => {
const { stderr } = await nextBuild(appDir, [], {
stderr: true,
})
expect(stderr).toMatch(errorRegex)
}) })
expect(stderr).toMatch(errorRegex) }
}) )
})
}) })
...@@ -24,112 +24,117 @@ const existsChunkNamed = (name) => { ...@@ -24,112 +24,117 @@ const existsChunkNamed = (name) => {
// Skipped as it uses webpack internals / stats.json. // Skipped as it uses webpack internals / stats.json.
;(process.env.TURBOPACK ? describe.skip : describe)('Chunking', () => { ;(process.env.TURBOPACK ? describe.skip : describe)('Chunking', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
try { () => {
// If a previous build has left chunks behind, delete them beforeAll(async () => {
const oldChunks = await readdir( try {
join(appDir, '.next', 'static', 'chunks') // If a previous build has left chunks behind, delete them
) const oldChunks = await readdir(
await Promise.all( join(appDir, '.next', 'static', 'chunks')
oldChunks.map((chunk) => { )
return unlink(join(appDir, '.next', 'static', 'chunks', chunk)) await Promise.all(
}) oldChunks.map((chunk) => {
) return unlink(join(appDir, '.next', 'static', 'chunks', chunk))
} catch (e) { })
// Error here means old chunks don't exist, so we don't need to do anything )
} } catch (e) {
await nextBuild(appDir, []) // Error here means old chunks don't exist, so we don't need to do anything
stats = (await readFile(join(appDir, '.next', 'stats.json'), 'utf8'))
// fixes backslashes in keyNames not being escaped on windows
.replace(/"static\\(.*?":?)/g, (match) => match.replace(/\\/g, '\\\\'))
stats = JSON.parse(stats)
appPort = await findPort()
app = await nextStart(appDir, appPort)
chunks = await readdir(join(appDir, '.next', 'static', 'chunks'))
})
afterAll(() => killApp(app))
it('should use all url friendly names', () => {
expect(chunks).toEqual(chunks.map((name) => encodeURIComponent(name)))
})
it('should create a framework chunk', () => {
expect(existsChunkNamed('framework')).toBe(true)
})
it('should not create a commons chunk', () => {
// This app has no dependency that is required by ALL pages, and should
// therefore not have a commons chunk
expect(existsChunkNamed('commons')).toBe(false)
})
it('should not create a lib chunk for react or react-dom', () => {
// These large dependencies would become lib chunks, except that they
// are preemptively moved into the framework chunk.
expect(existsChunkNamed('react|react-dom')).toBe(false)
})
it('should not preload the build manifest', async () => {
const html = await renderViaHTTP(appPort, '/')
const $ = cheerio.load(html)
expect(
[].slice
.call($('link[rel="preload"][as="script"]'))
.map((e) => e.attribs.href)
.some((entry) => entry.includes('_buildManifest'))
).toBe(false)
})
it('should execute the build manifest', async () => {
const html = await renderViaHTTP(appPort, '/')
const $ = cheerio.load(html)
expect(
Array.from($('script'))
.map((e) => e.attribs.src)
.some((entry) => entry && entry.includes('_buildManifest'))
).toBe(true)
})
it('should not include more than one instance of react-dom', async () => {
const misplacedReactDom = stats.chunks.some((chunk) => {
if (chunk.names.includes('framework')) {
// disregard react-dom in framework--it's supposed to be there
return false
} }
return chunk.modules.some((module) => { await nextBuild(appDir, [])
return /react-dom/.test(module.name)
}) stats = (await readFile(join(appDir, '.next', 'stats.json'), 'utf8'))
// fixes backslashes in keyNames not being escaped on windows
.replace(/"static\\(.*?":?)/g, (match) =>
match.replace(/\\/g, '\\\\')
)
stats = JSON.parse(stats)
appPort = await findPort()
app = await nextStart(appDir, appPort)
chunks = await readdir(join(appDir, '.next', 'static', 'chunks'))
})
afterAll(() => killApp(app))
it('should use all url friendly names', () => {
expect(chunks).toEqual(chunks.map((name) => encodeURIComponent(name)))
})
it('should create a framework chunk', () => {
expect(existsChunkNamed('framework')).toBe(true)
})
it('should not create a commons chunk', () => {
// This app has no dependency that is required by ALL pages, and should
// therefore not have a commons chunk
expect(existsChunkNamed('commons')).toBe(false)
})
it('should not create a lib chunk for react or react-dom', () => {
// These large dependencies would become lib chunks, except that they
// are preemptively moved into the framework chunk.
expect(existsChunkNamed('react|react-dom')).toBe(false)
}) })
expect(misplacedReactDom).toBe(false)
})
describe('Serving', () => { it('should not preload the build manifest', async () => {
it('should hydrate with aggressive chunking', async () => { const html = await renderViaHTTP(appPort, '/')
const browser = await webdriver(appPort, '/page2') const $ = cheerio.load(html)
const text = await browser.elementByCss('#padded-str').text() expect(
[].slice
.call($('link[rel="preload"][as="script"]'))
.map((e) => e.attribs.href)
.some((entry) => entry.includes('_buildManifest'))
).toBe(false)
})
expect(text).toBe('__rad__') it('should execute the build manifest', async () => {
const html = await renderViaHTTP(appPort, '/')
const $ = cheerio.load(html)
expect(
Array.from($('script'))
.map((e) => e.attribs.src)
.some((entry) => entry && entry.includes('_buildManifest'))
).toBe(true)
})
await browser.close() it('should not include more than one instance of react-dom', async () => {
const misplacedReactDom = stats.chunks.some((chunk) => {
if (chunk.names.includes('framework')) {
// disregard react-dom in framework--it's supposed to be there
return false
}
return chunk.modules.some((module) => {
return /react-dom/.test(module.name)
})
})
expect(misplacedReactDom).toBe(false)
}) })
it('should load chunks when navigating', async () => { describe('Serving', () => {
const browser = await webdriver(appPort, '/page3') it('should hydrate with aggressive chunking', async () => {
const text = await browser const browser = await webdriver(appPort, '/page2')
.elementByCss('#page2-link') const text = await browser.elementByCss('#padded-str').text()
.click()
.waitForElementByCss('#padded-str')
.elementByCss('#padded-str')
.text()
expect(text).toBe('__rad__') expect(text).toBe('__rad__')
await browser.close() await browser.close()
})
it('should load chunks when navigating', async () => {
const browser = await webdriver(appPort, '/page3')
const text = await browser
.elementByCss('#page2-link')
.click()
.waitForElementByCss('#padded-str')
.elementByCss('#padded-str')
.text()
expect(text).toBe('__rad__')
await browser.close()
})
}) })
}) }
}) )
}) })
...@@ -29,28 +29,31 @@ const runTests = () => { ...@@ -29,28 +29,31 @@ const runTests = () => {
} }
describe('Cleaning distDir', () => { describe('Cleaning distDir', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
runTests() 'production mode',
() => {
describe('disabled write', () => { runTests()
beforeAll(async () => {
nextConfigContent = await fs.readFile(nextConfig, 'utf8') describe('disabled write', () => {
await fs.writeFile( beforeAll(async () => {
nextConfig, nextConfigContent = await fs.readFile(nextConfig, 'utf8')
` await fs.writeFile(
nextConfig,
`
module.exports = { module.exports = {
cleanDistDir: false cleanDistDir: false
} }
` `
) )
})
afterAll(async () => {
await fs.writeFile(nextConfig, nextConfigContent)
})
it('should not clean up .next before build start', async () => {
await checkFileWrite(true)
})
}) })
afterAll(async () => { }
await fs.writeFile(nextConfig, nextConfigContent) )
})
it('should not clean up .next before build start', async () => {
await checkFileWrite(true)
})
})
})
}) })
This diff is collapsed.
...@@ -23,7 +23,7 @@ const runTests = (isProd = false) => { ...@@ -23,7 +23,7 @@ const runTests = (isProd = false) => {
} }
describe('Client 404', () => { describe('Client 404', () => {
describe('dev mode', () => { describe('development mode', () => {
beforeAll(async () => { beforeAll(async () => {
context.appPort = await findPort() context.appPort = await findPort()
context.server = await launchApp(appDir, context.appPort) context.server = await launchApp(appDir, context.appPort)
...@@ -35,23 +35,26 @@ describe('Client 404', () => { ...@@ -35,23 +35,26 @@ describe('Client 404', () => {
runTests() runTests()
}) })
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => { ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
beforeAll(async () => { 'production mode',
await nextBuild(appDir) () => {
context.appPort = await findPort() beforeAll(async () => {
context.server = await nextStart(appDir, context.appPort) await nextBuild(appDir)
context.appPort = await findPort()
const manifest = await getBuildManifest(appDir) context.server = await nextStart(appDir, context.appPort)
const files = manifest.pages['/missing'].filter((d) =>
/static[\\/]chunks[\\/]pages/.test(d) const manifest = await getBuildManifest(appDir)
) const files = manifest.pages['/missing'].filter((d) =>
if (files.length < 1) { /static[\\/]chunks[\\/]pages/.test(d)
throw new Error('oops!') )
} if (files.length < 1) {
await Promise.all(files.map((f) => fs.remove(join(appDir, '.next', f)))) throw new Error('oops!')
}) }
afterAll(() => killApp(context.server)) await Promise.all(files.map((f) => fs.remove(join(appDir, '.next', f))))
})
runTests(true) afterAll(() => killApp(context.server))
})
runTests(true)
}
)
}) })
...@@ -141,7 +141,7 @@ describe.each([ ...@@ -141,7 +141,7 @@ describe.each([
}) })
describe('with generateEtags enabled', () => { describe('with generateEtags enabled', () => {
;(process.env.TURBOPACK ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode', 'production mode',
() => { () => {
beforeAll(async () => { beforeAll(async () => {
...@@ -211,7 +211,7 @@ describe.each([ ...@@ -211,7 +211,7 @@ describe.each([
describe('Error when rendering without starting slash', () => { describe('Error when rendering without starting slash', () => {
afterEach(() => killApp(server)) afterEach(() => killApp(server))
it('should warn in dev mode', async () => { it('should warn in development mode', async () => {
let stderr = '' let stderr = ''
await startServer( await startServer(
{}, {},
...@@ -227,7 +227,7 @@ describe.each([ ...@@ -227,7 +227,7 @@ describe.each([
expect(html).toContain('made it to dashboard') expect(html).toContain('made it to dashboard')
expect(stderr).toContain('Cannot render page with path "dashboard"') expect(stderr).toContain('Cannot render page with path "dashboard"')
}) })
;(process.env.TURBOPACK ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode', 'production mode',
() => { () => {
it('should warn in production mode', async () => { it('should warn in production mode', async () => {
......
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