import { nextTestSetup } from 'e2e-utils' import { check, retry, waitFor } from 'next-test-utils' import cheerio from 'cheerio' import stripAnsi from 'strip-ansi' import { NEXT_RSC_UNION_QUERY, RSC_HEADER, } from 'next/dist/client/components/app-router-headers' // TODO: We should decide on an established pattern for gating test assertions // on experimental flags. For example, as a first step we could all the common // gates like this one into a single module. const isPPREnabledByDefault = process.env.__NEXT_EXPERIMENTAL_PPR === 'true' describe('app dir - basic', () => { const { next, isNextDev, isNextStart, isNextDeploy, isTurbopack } = nextTestSetup({ files: __dirname, buildCommand: process.env.NEXT_EXPERIMENTAL_COMPILE ? 'pnpm compile-mode' : undefined, packageJson: { scripts: { 'compile-mode': process.env.NEXT_EXPERIMENTAL_COMPILE ? `next build --experimental-build-mode=compile && next build --experimental-build-mode=generate-env` : undefined, }, }, dependencies: { nanoid: '4.0.1', }, env: { NEXT_PUBLIC_TEST_ID: Date.now() + '', }, }) if (isNextStart) { it('should have correct cache-control for SSR routes', async () => { for (const path of ['/catch-all/first', '/ssr']) { const res = await next.fetch(path) expect(res.status).toBe(200) expect(res.headers.get('Cache-Control')).toBe( 'private, no-cache, no-store, max-age=0, must-revalidate' ) } }) } if (process.env.NEXT_EXPERIMENTAL_COMPILE) { it('should provide query for getStaticProps page correctly', async () => { const res = await next.fetch('/ssg?hello=world') expect(res.status).toBe(200) const $ = cheerio.load(await res.text()) expect(JSON.parse($('#query').text())).toEqual({ hello: 'world' }) }) } if (isNextStart) { it('should contain framework.json', async () => { const frameworksJson = await next.readJSON( '.next/diagnostics/framework.json' ) expect(frameworksJson).toEqual({ name: 'Next.js', version: require('next/package.json').version, }) }) it('outputs correct build-diagnostics.json', async () => { const buildDiagnosticsJson = await next.readJSON( '.next/diagnostics/build-diagnostics.json' ) expect(buildDiagnosticsJson).toMatchObject({ buildStage: 'static-generation', buildOptions: {}, }) }) } if (isNextStart && !process.env.NEXT_EXPERIMENTAL_COMPILE) { if (!process.env.NEXT_EXPERIMENTAL_COMPILE) { it('should have correct size in build output', async () => { expect(next.cliOutput).toMatch( /\/dashboard\/another.*? *?[^0]\d{1,} [\w]{1,}B/ ) }) } it('should have correct preferredRegion values in manifest', async () => { const middlewareManifest = JSON.parse( await next.readFile('.next/server/middleware-manifest.json') ) expect( middlewareManifest.functions['/(rootonly)/dashboard/hello/page'].regions ).toEqual(['iad1', 'sfo1']) expect(middlewareManifest.functions['/dashboard/page'].regions).toEqual([ 'iad1', ]) expect( middlewareManifest.functions['/slow-page-no-loading/page'].regions ).toEqual(['global']) expect(middlewareManifest.functions['/test-page/page'].regions).toEqual([ 'home', ]) // Inherits from the root layout. expect( middlewareManifest.functions['/slow-page-with-loading/page'].regions ).toEqual(['sfo1']) }) } it('should work for catch-all edge page', async () => { const html = await next.render('/catch-all-edge/hello123') const $ = cheerio.load(html) expect(JSON.parse($('#params').text())).toEqual({ slug: ['hello123'], }) }) it('should return normalized dynamic route params for catch-all edge page', async () => { const html = await next.render('/catch-all-edge/a/b/c') const $ = cheerio.load(html) expect(JSON.parse($('#params').text())).toEqual({ slug: ['a', 'b', 'c'], }) }) it('should have correct searchParams and params (server)', async () => { const html = await next.render('/dynamic/category-1/id-2?query1=value2') const $ = cheerio.load(html) expect(JSON.parse($('#id-page-params').text())).toEqual({ category: 'category-1', id: 'id-2', }) expect(JSON.parse($('#search-params').text())).toEqual({ query1: 'value2', }) }) it('should have correct searchParams and params (client)', async () => { const browser = await next.browser( '/dynamic-client/category-1/id-2?query1=value2' ) const html = await browser.eval('document.documentElement.innerHTML') const $ = cheerio.load(html) expect(JSON.parse($('#id-page-params').text())).toEqual({ category: 'category-1', id: 'id-2', }) expect(JSON.parse($('#search-params').text())).toEqual({ query1: 'value2', }) }) if (!isNextDev) { it('should successfully detect app route during prefetch', async () => { const browser = await next.browser('/') await check(async () => { const found = await browser.eval( '!!window.next.router.components["/dashboard"]' ) return found ? 'success' : await browser.eval('Object.keys(window.next.router.components)') }, 'success') await browser.elementByCss('a').click() await browser.waitForElementByCss('#from-dashboard') }) } // Turbopack has different chunking in dev/production which results in the entrypoint name not being included in the outputs. if (!process.env.IS_TURBOPACK_TEST) { it('should encode chunk path correctly', async () => { await next.fetch('/dynamic-client/first/second') const browser = await next.browser('/') const requests = [] browser.on('request', (req) => { requests.push(req.url()) }) await browser.eval( 'window.location.href = "/dynamic-client/first/second"' ) await browser.waitForElementByCss('#id-page-params') expect( requests.some( (req) => req.includes( encodeURI(isTurbopack ? '[category]_[id]' : '/[category]/[id]') ) && req.includes('.js') ) ).toBe(true) }) } it.each([ { pathname: '/redirect-1' }, { pathname: '/redirect-2' }, { pathname: '/blog/old-post' }, { pathname: '/redirect-3/some' }, { pathname: '/redirect-4' }, { pathname: '/redirect-4/?q=1&=' }, ])( 'should match redirects in pages correctly $path', async ({ pathname }) => { let browser = await next.browser('/') await browser.eval(`next.router.push("${pathname}")`) await check(async () => { const href = await browser.eval('location.href') return href.includes('example.vercel.sh') ? 'yes' : href }, 'yes') if (pathname.includes('/blog')) { browser = await next.browser('/blog/first') await browser.eval('window.beforeNav = 1') // check 5 times to ensure a reload didn't occur for (let i = 0; i < 5; i++) { await waitFor(500) expect( await browser.eval('document.documentElement.innerHTML') ).toContain('hello from pages/blog/[slug]') expect(await browser.eval('window.beforeNav')).toBe(1) } } } ) it('should not apply client router filter on shallow', async () => { const browser = await next.browser('/') await browser.eval('window.beforeNav = 1') await check(async () => { await browser.eval( `window.next.router.push('/', '/redirect-1', { shallow: true })` ) return await browser.eval('window.location.pathname') }, '/redirect-1') expect(await browser.eval('window.beforeNav')).toBe(1) }) if (isNextDev) { it('should not have duplicate config warnings', async () => { await next.fetch('/') expect( stripAnsi(next.cliOutput).match(/Experiments \(use with caution\):/g) .length ).toBe(1) }) } if (!isNextDeploy) { it('should not share edge workers', async () => { const controller1 = new AbortController() const controller2 = new AbortController() next .fetch('/slow-page-no-loading', { signal: controller1.signal, }) .catch(() => {}) next .fetch('/slow-page-no-loading', { signal: controller2.signal, }) .catch(() => {}) await waitFor(1000) controller1.abort() const controller3 = new AbortController() next .fetch('/slow-page-no-loading', { signal: controller3.signal, }) .catch(() => {}) await waitFor(1000) controller2.abort() controller3.abort() const res = await next.fetch('/slow-page-no-loading') expect(res.status).toBe(200) expect(await res.text()).toContain('hello from slow page') expect(next.cliOutput).not.toContain( 'A separate worker must be used for each render' ) }) } if (isNextStart) { it('should generate build traces correctly', async () => { const trace = JSON.parse( await next.readFile( '.next/server/app/dashboard/deployments/[id]/page.js.nft.json' ) ) as { files: string[] } expect(trace.files.some((file) => file.endsWith('data.json'))).toBe(true) }) } it('should use text/x-component for flight', async () => { const res = await next.fetch( `/dashboard/deployments/123?${NEXT_RSC_UNION_QUERY}`, { headers: { [RSC_HEADER]: '1', }, } ) expect(res.headers.get('Content-Type')).toBe('text/x-component') }) it('should use text/x-component for flight with edge runtime', async () => { const res = await next.fetch(`/dashboard?${NEXT_RSC_UNION_QUERY}`, { headers: { [RSC_HEADER]: '1', }, }) expect(res.headers.get('Content-Type')).toBe('text/x-component') }) it('should return the `vary` header from edge runtime', async () => { const res = await next.fetch('/dashboard') expect(res.headers.get('x-edge-runtime')).toBe('1') expect(res.headers.get('vary')).toBe( 'RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Router-Segment-Prefetch' ) }) it('should return the `vary` header from pages for flight requests', async () => { const res = await next.fetch(`/?${NEXT_RSC_UNION_QUERY}`, { headers: { [RSC_HEADER]: '1', }, }) expect(res.headers.get('vary')).toBe( isNextDeploy ? 'RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Router-Segment-Prefetch' : 'RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Router-Segment-Prefetch, Accept-Encoding' ) }) it('should pass props from getServerSideProps in root layout', async () => { const $ = await next.render$('/dashboard') expect($('title').first().text()).toBe('hello world') }) it('should serve from pages', async () => { const html = await next.render('/') expect(html).toContain('hello from pages/index') }) it('should serve dynamic route from pages', async () => { const html = await next.render('/blog/first') expect(html).toContain('hello from pages/blog/[slug]') }) it('should serve from public', async () => { const html = await next.render('/hello.txt') expect(html).toContain('hello world') }) it('should serve from app', async () => { const html = await next.render('/dashboard') expect(html).toContain('hello from app/dashboard') }) it('should ensure the suffix is at the end of the stream', async () => { const html = await next.render('/dashboard') // It must end with the suffix and not contain it anywhere else. const suffix = '' expect(html).toEndWith(suffix) expect(html.slice(0, -suffix.length)).not.toContain(suffix) }) if (!isNextDeploy) { it('should serve /index as separate page', async () => { const stderr = [] next.on('stderr', (err) => { stderr.push(err) }) const html = await next.render('/dashboard/index') expect(html).toContain('hello from app/dashboard/index') expect(stderr.some((err) => err.includes('Invalid hook call'))).toBe( false ) }) it('should serve polyfills for browsers that do not support modules', async () => { const html = await next.render('/dashboard/index') expect(html).toMatch( isTurbopack ? /