Unverified Commit 8e52126e authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Migrate prerender tests to new set-up (#29245)

parent 371ca582
......@@ -132,8 +132,6 @@
"seedrandom": "3.0.5",
"selenium-webdriver": "4.0.0-beta.4",
"shell-quote": "1.7.2",
"sqlite": "4.0.22",
"sqlite3": "5.0.2",
"styled-jsx-plugin-postcss": "3.0.2",
"tailwindcss": "1.1.3",
"taskr": "1.1.0",
......
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -136,7 +136,7 @@ describe('basePath', () => {
})
if (!dev) {
if (!(global as any).isDeploy) {
if (!(global as any).isNextDeploy) {
it('should add basePath to routes-manifest', async () => {
const routesManifest = JSON.parse(
await next.readFile('.next/routes-manifest.json')
......@@ -487,7 +487,7 @@ describe('basePath', () => {
)
})
if (!(global as any).isDeploy) {
if (!(global as any).isNextDeploy) {
it('should navigate an absolute local url with basePath', async () => {
const browser = await webdriver(
next.url,
......@@ -843,5 +843,5 @@ describe('basePath', () => {
}
})
}
runTests((global as any).isDev)
runTests((global as any).isNextDev)
})
/* eslint-env jest */
import fs from 'fs-extra'
import { join, sep } from 'path'
import path from 'path'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import webdriver from 'next-webdriver'
import {
findPort,
killApp,
launchApp,
nextBuild,
nextStart,
} from 'next-test-utils'
let app
let appPort
const appDir = join(__dirname, '..')
describe('prerender native module', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
pages: new FileRef(
path.join(__dirname, 'prerender-native-module/pages')
),
'data.sqlite': new FileRef(
path.join(__dirname, 'prerender-native-module/data.sqlite')
),
},
dependencies: {
sqlite: '4.0.22',
sqlite3: '5.0.2',
},
nextConfig: {
experimental: {
nftTracing: true,
},
},
})
})
afterAll(() => next.destroy())
const runTests = () => {
it('should render index correctly', async () => {
const browser = await webdriver(appPort, '/')
const browser = await webdriver(next.url, '/')
expect(await browser.elementByCss('#index').text()).toBe('index page')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
index: true,
......@@ -25,7 +38,7 @@ const runTests = () => {
})
it('should render /blog/first correctly', async () => {
const browser = await webdriver(appPort, '/blog/first')
const browser = await webdriver(next.url, '/blog/first')
expect(await browser.elementByCss('#blog').text()).toBe('blog page')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
......@@ -39,7 +52,7 @@ const runTests = () => {
})
it('should render /blog/second correctly', async () => {
const browser = await webdriver(appPort, '/blog/second')
const browser = await webdriver(next.url, '/blog/second')
await browser.waitForElementByCss('#blog')
expect(await browser.elementByCss('#blog').text()).toBe('blog page')
......@@ -52,26 +65,8 @@ const runTests = () => {
],
})
})
}
describe('Prerender native module', () => {
describe('production', () => {
beforeAll(async () => {
const result = await nextBuild(appDir, undefined, {
cwd: appDir,
stderr: true,
stdout: true,
})
if (result.code !== 0) {
console.error(result)
throw new Error(`Failed to build, exited with code ${result.code}`)
}
appPort = await findPort()
app = await nextStart(appDir, appPort, { cwd: appDir })
})
afterAll(() => killApp(app))
if ((global as any).isNextStart) {
it('should output traces', async () => {
const checks = [
{
......@@ -101,9 +96,8 @@ describe('Prerender native module', () => {
]
for (const check of checks) {
const contents = await fs.readFile(
join(appDir, '.next/server/pages/', check.page + '.js.nft.json'),
'utf8'
const contents = await next.readFile(
path.join('.next/server/pages/', check.page + '.js.nft.json')
)
const { version, files } = JSON.parse(contents)
expect(version).toBe(1)
......@@ -112,24 +106,12 @@ describe('Prerender native module', () => {
check.tests.every((item) => files.some((file) => item.test(file)))
).toBe(true)
if (sep === '/') {
if (path.sep === '/') {
expect(
check.notTests.some((item) => files.some((file) => item.test(file)))
).toBe(false)
}
}
})
runTests()
})
describe('dev', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort, { cwd: appDir })
})
afterAll(() => killApp(app))
runTests()
})
}
})
import cheerio from 'cheerio'
import { join, sep } from 'path'
import escapeRegex from 'escape-string-regexp'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import {
check,
fetchViaHTTP,
getBrowserBodyText,
getRedboxHeader,
hasRedbox,
normalizeRegEx,
renderViaHTTP,
waitFor,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
describe('Prerender', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
pages: new FileRef(join(__dirname, 'prerender/pages')),
'world.txt': new FileRef(join(__dirname, 'prerender/world.txt')),
},
dependencies: {
firebase: '7.14.5',
},
nextConfig: {
experimental: {
nftTracing: true,
},
async rewrites() {
return [
{
source: '/some-rewrite/:item',
destination: '/blog/post-:item',
},
{
source: '/about',
destination: '/lang/en/about',
},
{
source: '/blocked-create',
destination: '/blocking-fallback/blocked-create',
},
]
},
},
})
})
afterAll(() => next.destroy())
function isCachingHeader(cacheControl) {
return !cacheControl || !/no-store/.test(cacheControl)
}
const expectedManifestRoutes = () => ({
'/': {
dataRoute: `/_next/data/${next.buildId}/index.json`,
initialRevalidateSeconds: 2,
srcRoute: null,
},
'/blog/[post3]': {
dataRoute: `/_next/data/${next.buildId}/blog/[post3].json`,
initialRevalidateSeconds: 10,
srcRoute: '/blog/[post]',
},
'/blog/post-1': {
dataRoute: `/_next/data/${next.buildId}/blog/post-1.json`,
initialRevalidateSeconds: 10,
srcRoute: '/blog/[post]',
},
'/blog/post-2': {
dataRoute: `/_next/data/${next.buildId}/blog/post-2.json`,
initialRevalidateSeconds: 10,
srcRoute: '/blog/[post]',
},
'/blog/post-4': {
dataRoute: `/_next/data/${next.buildId}/blog/post-4.json`,
initialRevalidateSeconds: 10,
srcRoute: '/blog/[post]',
},
'/blog/post-1/comment-1': {
dataRoute: `/_next/data/${next.buildId}/blog/post-1/comment-1.json`,
initialRevalidateSeconds: 2,
srcRoute: '/blog/[post]/[comment]',
},
'/blog/post-2/comment-2': {
dataRoute: `/_next/data/${next.buildId}/blog/post-2/comment-2.json`,
initialRevalidateSeconds: 2,
srcRoute: '/blog/[post]/[comment]',
},
'/blog/post.1': {
dataRoute: `/_next/data/${next.buildId}/blog/post.1.json`,
initialRevalidateSeconds: 10,
srcRoute: '/blog/[post]',
},
'/catchall-explicit/another/value': {
dataRoute: `/_next/data/${next.buildId}/catchall-explicit/another/value.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/catchall-explicit/first': {
dataRoute: `/_next/data/${next.buildId}/catchall-explicit/first.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/catchall-explicit/hello/another': {
dataRoute: `/_next/data/${next.buildId}/catchall-explicit/hello/another.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/catchall-explicit/second': {
dataRoute: `/_next/data/${next.buildId}/catchall-explicit/second.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/catchall-explicit/[first]/[second]': {
dataRoute: `/_next/data/${next.buildId}/catchall-explicit/[first]/[second].json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/catchall-explicit/[third]/[fourth]': {
dataRoute: `/_next/data/${next.buildId}/catchall-explicit/[third]/[fourth].json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/catchall-optional': {
dataRoute: `/_next/data/${next.buildId}/catchall-optional.json`,
initialRevalidateSeconds: false,
srcRoute: '/catchall-optional/[[...slug]]',
},
'/catchall-optional/value': {
dataRoute: `/_next/data/${next.buildId}/catchall-optional/value.json`,
initialRevalidateSeconds: false,
srcRoute: '/catchall-optional/[[...slug]]',
},
'/another': {
dataRoute: `/_next/data/${next.buildId}/another.json`,
initialRevalidateSeconds: 1,
srcRoute: null,
},
'/api-docs/first': {
dataRoute: `/_next/data/${next.buildId}/api-docs/first.json`,
initialRevalidateSeconds: false,
srcRoute: '/api-docs/[...slug]',
},
'/blocking-fallback-some/a': {
dataRoute: `/_next/data/${next.buildId}/blocking-fallback-some/a.json`,
initialRevalidateSeconds: 1,
srcRoute: '/blocking-fallback-some/[slug]',
},
'/blocking-fallback-some/b': {
dataRoute: `/_next/data/${next.buildId}/blocking-fallback-some/b.json`,
initialRevalidateSeconds: 1,
srcRoute: '/blocking-fallback-some/[slug]',
},
'/blog': {
dataRoute: `/_next/data/${next.buildId}/blog.json`,
initialRevalidateSeconds: 10,
srcRoute: null,
},
'/default-revalidate': {
dataRoute: `/_next/data/${next.buildId}/default-revalidate.json`,
initialRevalidateSeconds: false,
srcRoute: null,
},
'/dynamic/[first]': {
dataRoute: `/_next/data/${next.buildId}/dynamic/[first].json`,
initialRevalidateSeconds: false,
srcRoute: '/dynamic/[slug]',
},
'/dynamic/[second]': {
dataRoute: `/_next/data/${next.buildId}/dynamic/[second].json`,
initialRevalidateSeconds: false,
srcRoute: '/dynamic/[slug]',
},
'/index': {
dataRoute: `/_next/data/${next.buildId}/index/index.json`,
initialRevalidateSeconds: false,
srcRoute: null,
},
'/lang/de/about': {
dataRoute: `/_next/data/${next.buildId}/lang/de/about.json`,
initialRevalidateSeconds: false,
srcRoute: '/lang/[lang]/about',
},
'/lang/en/about': {
dataRoute: `/_next/data/${next.buildId}/lang/en/about.json`,
initialRevalidateSeconds: false,
srcRoute: '/lang/[lang]/about',
},
'/lang/es/about': {
dataRoute: `/_next/data/${next.buildId}/lang/es/about.json`,
initialRevalidateSeconds: false,
srcRoute: '/lang/[lang]/about',
},
'/lang/fr/about': {
dataRoute: `/_next/data/${next.buildId}/lang/fr/about.json`,
initialRevalidateSeconds: false,
srcRoute: '/lang/[lang]/about',
},
'/something': {
dataRoute: `/_next/data/${next.buildId}/something.json`,
initialRevalidateSeconds: false,
srcRoute: null,
},
'/catchall/another/value': {
dataRoute: `/_next/data/${next.buildId}/catchall/another/value.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall/[...slug]',
},
'/catchall/first': {
dataRoute: `/_next/data/${next.buildId}/catchall/first.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall/[...slug]',
},
'/catchall/second': {
dataRoute: `/_next/data/${next.buildId}/catchall/second.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall/[...slug]',
},
'/catchall/hello/another': {
dataRoute: `/_next/data/${next.buildId}/catchall/hello/another.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall/[...slug]',
},
})
const navigateTest = (dev = false) => {
it('should navigate between pages successfully', async () => {
const toBuild = [
'/',
'/another',
'/something',
'/normal',
'/blog/post-1',
'/blog/post-1/comment-1',
'/catchall/first',
]
await waitFor(2500)
await Promise.all(toBuild.map((pg) => renderViaHTTP(next.url, pg)))
const browser = await webdriver(next.url, '/')
let text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
// go to /another
async function goFromHomeToAnother() {
await browser.eval('window.beforeAnother = true')
await browser.elementByCss('#another').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(await browser.eval('window.beforeAnother')).toBe(true)
expect(text).toMatch(/hello.*?world/)
}
await goFromHomeToAnother()
// go to /
async function goFromAnotherToHome() {
await browser.eval('window.didTransition = 1')
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#another')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
expect(await browser.eval('window.didTransition')).toBe(1)
}
await goFromAnotherToHome()
// Client-side SSG data caching test
// eslint-disable-next-line no-lone-blocks
{
// Let revalidation period lapse
await waitFor(2000)
// Trigger revalidation (visit page)
await goFromHomeToAnother()
const snapTime = await browser.elementByCss('#anotherTime').text()
// Wait for revalidation to finish
await waitFor(2000)
// Re-visit page
await goFromAnotherToHome()
await goFromHomeToAnother()
const nextTime = await browser.elementByCss('#anotherTime').text()
if (dev) {
expect(snapTime).not.toMatch(nextTime)
} else {
expect(snapTime).toMatch(nextTime)
}
// Reset to Home for next test
await goFromAnotherToHome()
}
// go to /something
await browser.elementByCss('#something').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#post-1')
// go to /blog/post-1
await browser.elementByCss('#post-1').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/Post:.*?post-1/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /index
await browser.elementByCss('#to-nested-index').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello nested index/)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /catchall-optional
await browser.elementByCss('#catchall-optional-root').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/Catch all: \[\]/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /dynamic/[first]
await browser.elementByCss('#dynamic-first').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('#param').text()
expect(text).toMatch(/Hi \[first\]!/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /dynamic/[second]
await browser.elementByCss('#dynamic-second').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('#param').text()
expect(text).toMatch(/Hi \[second\]!/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /catchall-explicit/[first]/[second]
await browser.elementByCss('#catchall-explicit-string').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('#catchall').text()
expect(text).toMatch(/Hi \[first\] \[second\]/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /catchall-explicit/[first]/[second]
await browser.elementByCss('#catchall-explicit-object').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('#catchall').text()
expect(text).toMatch(/Hi \[third\] \[fourth\]/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /catchall-optional/value
await browser.elementByCss('#catchall-optional-value').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/Catch all: \[value\]/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /blog/post-1/comment-1
await browser.elementByCss('#comment-1').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p:nth-child(2)').text()
expect(text).toMatch(/Comment:.*?comment-1/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /catchall/first
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#to-catchall')
await browser.elementByCss('#to-catchall').click()
await browser.waitForElementByCss('#catchall')
text = await browser.elementByCss('#catchall').text()
expect(text).toMatch(/Hi.*?first/)
expect(await browser.eval('window.didTransition')).toBe(1)
await browser.close()
})
}
const runTests = (dev = false) => {
navigateTest(dev)
it('should SSR normal page correctly', async () => {
const html = await renderViaHTTP(next.url, '/')
expect(html).toMatch(/hello.*?world/)
})
it('should SSR incremental page correctly', async () => {
const html = await renderViaHTTP(next.url, '/blog/post-1')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
expect(html).toMatch(/Post:.*?post-1/)
})
it('should SSR blocking path correctly (blocking)', async () => {
const html = await renderViaHTTP(
next.url,
'/blocking-fallback/random-path'
)
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
expect($('p').text()).toBe('Post: random-path')
})
it('should SSR blocking path correctly (pre-rendered)', async () => {
const html = await renderViaHTTP(next.url, '/blocking-fallback-some/a')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
expect($('p').text()).toBe('Post: a')
})
it('should have gsp in __NEXT_DATA__', async () => {
const html = await renderViaHTTP(next.url, '/')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).gsp).toBe(true)
})
it('should not have gsp in __NEXT_DATA__ for non-GSP page', async () => {
const html = await renderViaHTTP(next.url, '/normal')
const $ = cheerio.load(html)
expect('gsp' in JSON.parse($('#__NEXT_DATA__').text())).toBe(false)
})
it('should not supply query values to params or useRouter non-dynamic page SSR', async () => {
const html = await renderViaHTTP(next.url, '/something?hello=world')
const $ = cheerio.load(html)
const query = $('#query').text()
expect(JSON.parse(query)).toEqual({})
const params = $('#params').text()
expect(JSON.parse(params)).toEqual({})
})
it('should not supply query values to params in /_next/data request', async () => {
const data = JSON.parse(
await renderViaHTTP(
next.url,
`/_next/data/${next.buildId}/something.json?hello=world`
)
)
expect(data.pageProps.params).toEqual({})
})
it('should not supply query values to params or useRouter dynamic page SSR', async () => {
const html = await renderViaHTTP(next.url, '/blog/post-1?hello=world')
const $ = cheerio.load(html)
const params = $('#params').text()
expect(JSON.parse(params)).toEqual({ post: 'post-1' })
const query = $('#query').text()
expect(JSON.parse(query)).toEqual({ post: 'post-1' })
})
it('should return data correctly', async () => {
const data = JSON.parse(
await renderViaHTTP(
next.url,
expectedManifestRoutes()['/something'].dataRoute
)
)
expect(data.pageProps.world).toBe('world')
})
it('should return data correctly for dynamic page', async () => {
const data = JSON.parse(
await renderViaHTTP(
next.url,
expectedManifestRoutes()['/blog/post-1'].dataRoute
)
)
expect(data.pageProps.post).toBe('post-1')
})
it('should return data correctly for dynamic page (non-seeded)', async () => {
const data = JSON.parse(
await renderViaHTTP(
next.url,
expectedManifestRoutes()['/blog/post-1'].dataRoute.replace(
/post-1/,
'post-3'
)
)
)
expect(data.pageProps.post).toBe('post-3')
})
if (!dev) {
it('should use correct caching headers for a revalidate page', async () => {
const initialRes = await fetchViaHTTP(next.url, '/')
expect(initialRes.headers.get('cache-control')).toBe(
's-maxage=2, stale-while-revalidate'
)
})
}
it('should navigate to a normal page and back', async () => {
const browser = await webdriver(next.url, '/')
let text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
await browser.elementByCss('#normal').click()
await browser.waitForElementByCss('#normal-text')
text = await browser.elementByCss('#normal-text').text()
expect(text).toMatch(/a normal page/)
})
it('should parse query values on mount correctly', async () => {
const browser = await webdriver(next.url, '/blog/post-1?another=value')
const text = await browser.elementByCss('#query').text()
expect(text).toMatch(/another.*?value/)
expect(text).toMatch(/post.*?post-1/)
})
it('should reload page on failed data request', async () => {
const browser = await webdriver(next.url, '/')
await browser.eval('window.beforeClick = "abc"')
await browser.elementByCss('#broken-post').click()
expect(
await check(() => browser.eval('window.beforeClick'), {
test(v) {
return v !== 'abc'
},
})
).toBe(true)
})
it('should SSR dynamic page with brackets in param as object', async () => {
const html = await renderViaHTTP(next.url, '/dynamic/[first]')
const $ = cheerio.load(html)
expect($('#param').text()).toMatch(/Hi \[first\]!/)
})
it('should navigate to dynamic page with brackets in param as object', async () => {
const browser = await webdriver(next.url, '/')
await browser.elementByCss('#dynamic-first').click()
await browser.waitForElementByCss('#param')
const value = await browser.elementByCss('#param').text()
expect(value).toMatch(/Hi \[first\]!/)
})
it('should SSR dynamic page with brackets in param as string', async () => {
const html = await renderViaHTTP(next.url, '/dynamic/[second]')
const $ = cheerio.load(html)
expect($('#param').text()).toMatch(/Hi \[second\]!/)
})
it('should navigate to dynamic page with brackets in param as string', async () => {
const browser = await webdriver(next.url, '/')
await browser.elementByCss('#dynamic-second').click()
await browser.waitForElementByCss('#param')
const value = await browser.elementByCss('#param').text()
expect(value).toMatch(/Hi \[second\]!/)
})
it('should not return data for fallback: false and missing dynamic page', async () => {
const res1 = await fetchViaHTTP(
next.url,
`/_next/data/${next.buildId}/dynamic/oopsie.json`
)
expect(res1.status).toBe(404)
await waitFor(500)
const res2 = await fetchViaHTTP(
next.url,
`/_next/data/${next.buildId}/dynamic/oopsie.json`
)
expect(res2.status).toBe(404)
await waitFor(500)
const res3 = await fetchViaHTTP(
next.url,
`/_next/data/${next.buildId}/dynamic/oopsie.json`
)
expect(res3.status).toBe(404)
})
it('should server prerendered path correctly for SSG pages that starts with api-docs', async () => {
const html = await renderViaHTTP(next.url, '/api-docs/first')
const $ = cheerio.load(html)
expect($('#api-docs').text()).toBe('API Docs')
expect(JSON.parse($('#props').text())).toEqual({
hello: 'world',
})
})
it('should render correctly for SSG pages that starts with api-docs', async () => {
const browser = await webdriver(next.url, '/api-docs/second')
await browser.waitForElementByCss('#api-docs')
expect(await browser.elementByCss('#api-docs').text()).toBe('API Docs')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
hello: 'world',
})
})
it('should return data correctly for SSG pages that starts with api-docs', async () => {
const data = await renderViaHTTP(
next.url,
`/_next/data/${next.buildId}/api-docs/first.json`
)
const { pageProps } = JSON.parse(data)
expect(pageProps).toEqual({
hello: 'world',
})
})
it('should SSR catch-all page with brackets in param as string', async () => {
const html = await renderViaHTTP(
next.url,
'/catchall-explicit/[first]/[second]'
)
const $ = cheerio.load(html)
expect($('#catchall').text()).toMatch(/Hi \[first\] \[second\]/)
})
it('should navigate to catch-all page with brackets in param as string', async () => {
const browser = await webdriver(next.url, '/')
await browser.elementByCss('#catchall-explicit-string').click()
await browser.waitForElementByCss('#catchall')
const value = await browser.elementByCss('#catchall').text()
expect(value).toMatch(/Hi \[first\] \[second\]/)
})
it('should SSR catch-all page with brackets in param as object', async () => {
const html = await renderViaHTTP(
next.url,
'/catchall-explicit/[third]/[fourth]'
)
const $ = cheerio.load(html)
expect($('#catchall').text()).toMatch(/Hi \[third\] \[fourth\]/)
})
it('should navigate to catch-all page with brackets in param as object', async () => {
const browser = await webdriver(next.url, '/')
await browser.elementByCss('#catchall-explicit-object').click()
await browser.waitForElementByCss('#catchall')
const value = await browser.elementByCss('#catchall').text()
expect(value).toMatch(/Hi \[third\] \[fourth\]/)
})
if ((global as any).isNextStart) {
// TODO: dev currently renders this page as blocking, meaning it shows the
// server error instead of continuously retrying. Do we want to change this?
it.skip('should reload page on failed data request, and retry', async () => {
const browser = await webdriver(next.url, '/')
await browser.eval('window.beforeClick = "abc"')
await browser.elementByCss('#broken-at-first-post').click()
expect(
await check(() => browser.eval('window.beforeClick'), {
test(v) {
return v !== 'abc'
},
})
).toBe(true)
const text = await browser.elementByCss('#params').text()
expect(text).toMatch(/post.*?post-999/)
})
}
it('should support prerendered catchall route', async () => {
const html = await renderViaHTTP(next.url, '/catchall/another/value')
const $ = cheerio.load(html)
expect(
JSON.parse(cheerio.load(html)('#__NEXT_DATA__').text()).isFallback
).toBe(false)
expect($('#catchall').text()).toMatch(/Hi.*?another value/)
})
it('should support lazy catchall route', async () => {
const html = await renderViaHTTP(next.url, '/catchall/notreturnedinpaths')
const $ = cheerio.load(html)
expect($('#catchall').text()).toBe('fallback')
// hydration
const browser = await webdriver(next.url, '/catchall/delayby3s')
const text1 = await browser.elementByCss('#catchall').text()
expect(text1).toBe('fallback')
await check(
() => browser.elementByCss('#catchall').text(),
/Hi.*?delayby3s/
)
})
it('should support nested lazy catchall route', async () => {
// We will render fallback for a "lazy" route
const html = await renderViaHTTP(
next.url,
'/catchall/notreturnedinpaths/nested'
)
const $ = cheerio.load(html)
expect($('#catchall').text()).toBe('fallback')
// hydration
const browser = await webdriver(next.url, '/catchall/delayby3s/nested')
const text1 = await browser.elementByCss('#catchall').text()
expect(text1).toBe('fallback')
await check(
() => browser.elementByCss('#catchall').text(),
/Hi.*?delayby3s nested/
)
})
it('should support prerendered catchall-explicit route (nested)', async () => {
const html = await renderViaHTTP(
next.url,
'/catchall-explicit/another/value'
)
const $ = cheerio.load(html)
expect(
JSON.parse(cheerio.load(html)('#__NEXT_DATA__').text()).isFallback
).toBe(false)
expect($('#catchall').text()).toMatch(/Hi.*?another value/)
})
it('should support prerendered catchall-explicit route (single)', async () => {
const html = await renderViaHTTP(next.url, '/catchall-explicit/second')
const $ = cheerio.load(html)
expect(
JSON.parse(cheerio.load(html)('#__NEXT_DATA__').text()).isFallback
).toBe(false)
expect($('#catchall').text()).toMatch(/Hi.*?second/)
})
it('should handle fallback only page correctly HTML', async () => {
const browser = await webdriver(next.url, '/fallback-only/first%2Fpost')
const text = await browser.elementByCss('p').text()
expect(text).toContain('hi fallback')
// wait for fallback data to load
await check(() => browser.elementByCss('p').text(), /Post/)
// check fallback data
const post = await browser.elementByCss('p').text()
const query = JSON.parse(await browser.elementByCss('#query').text())
const params = JSON.parse(await browser.elementByCss('#params').text())
expect(post).toContain('first/post')
expect(params).toEqual({
slug: 'first/post',
})
expect(query).toEqual(params)
})
it('should handle fallback only page correctly data', async () => {
const data = JSON.parse(
await renderViaHTTP(
next.url,
`/_next/data/${next.buildId}/fallback-only/second%2Fpost.json`
)
)
expect(data.pageProps.params).toEqual({
slug: 'second/post',
})
})
it('should 404 for a missing catchall explicit route', async () => {
const res = await fetchViaHTTP(
next.url,
'/catchall-explicit/notreturnedinpaths'
)
expect(res.status).toBe(404)
const html = await res.text()
expect(html).toMatch(/This page could not be found/)
})
it('should allow rewriting to SSG page with fallback: false', async () => {
const html = await renderViaHTTP(next.url, '/about')
expect(html).toMatch(/About:.*?en/)
})
it("should allow rewriting to SSG page with fallback: 'blocking'", async () => {
const html = await renderViaHTTP(next.url, '/blocked-create')
expect(html).toMatch(/Post:.*?blocked-create/)
})
it('should fetch /_next/data correctly with mismatched href and as', async () => {
const browser = await webdriver(next.url, '/')
if (!dev) {
await browser.eval(() =>
document.querySelector('#to-rewritten-ssg').scrollIntoView()
)
await check(async () => {
const hrefs = await browser.eval(
`Object.keys(window.next.router.sdc)`
)
hrefs.sort()
expect(
hrefs.map((href) =>
new URL(href).pathname.replace(/^\/_next\/data\/[^/]+/, '')
)
).toContainEqual('/lang/en/about.json')
return 'yes'
}, 'yes')
}
await browser.eval('window.beforeNav = "hi"')
await browser.elementByCss('#to-rewritten-ssg').click()
await browser.waitForElementByCss('#about')
expect(await browser.eval('window.beforeNav')).toBe('hi')
expect(await browser.elementByCss('#about').text()).toBe('About: en')
})
it('should not error when rewriting to fallback dynamic SSG page', async () => {
const item = Math.round(Math.random() * 100)
const browser = await webdriver(next.url, `/some-rewrite/${item}`)
await check(
() => browser.elementByCss('p').text(),
new RegExp(`Post: post-${item}`)
)
expect(JSON.parse(await browser.elementByCss('#params').text())).toEqual({
post: `post-${item}`,
})
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({
post: `post-${item}`,
})
})
if ((global as any).isNextDev) {
it('should not show warning from url prop being returned', async () => {
const urlPropPage = 'pages/url-prop.js'
await next.patchFile(
urlPropPage,
`
export async function getStaticProps() {
return {
props: {
url: 'something'
}
}
}
export default ({ url }) => <p>url: {url}</p>
`
)
const html = await renderViaHTTP(next.url, '/url-prop')
await next.deleteFile(urlPropPage)
expect(next.cliOutput).not.toMatch(
/The prop `url` is a reserved prop in Next.js for legacy reasons and will be overridden on page \/url-prop/
)
expect(html).toMatch(/url:.*?something/)
})
it('should always show fallback for page not in getStaticPaths', async () => {
const html = await renderViaHTTP(next.url, '/blog/post-321')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(true)
// make another request to ensure it still is
const html2 = await renderViaHTTP(next.url, '/blog/post-321')
const $2 = cheerio.load(html2)
expect(JSON.parse($2('#__NEXT_DATA__').text()).isFallback).toBe(true)
})
it('should not show fallback for page in getStaticPaths', async () => {
const html = await renderViaHTTP(next.url, '/blog/post-1')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
// make another request to ensure it's still not
const html2 = await renderViaHTTP(next.url, '/blog/post-1')
const $2 = cheerio.load(html2)
expect(JSON.parse($2('#__NEXT_DATA__').text()).isFallback).toBe(false)
})
it('should never show fallback for page not in getStaticPaths when blocking', async () => {
const html = await renderViaHTTP(
next.url,
'/blocking-fallback-some/asf'
)
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
// make another request to ensure it still is
const html2 = await renderViaHTTP(
next.url,
'/blocking-fallback-some/asf'
)
const $2 = cheerio.load(html2)
expect(JSON.parse($2('#__NEXT_DATA__').text()).isFallback).toBe(false)
})
it('should not show fallback for page in getStaticPaths when blocking', async () => {
const html = await renderViaHTTP(next.url, '/blocking-fallback-some/b')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
// make another request to ensure it's still not
const html2 = await renderViaHTTP(next.url, '/blocking-fallback-some/b')
const $2 = cheerio.load(html2)
expect(JSON.parse($2('#__NEXT_DATA__').text()).isFallback).toBe(false)
})
it('should log error in console and browser in dev mode', async () => {
const indexPage = 'pages/index.js'
const origContent = await next.readFile(indexPage)
const browser = await webdriver(next.url, '/')
expect(await browser.elementByCss('p').text()).toMatch(/hello.*?world/)
await next.patchFile(
indexPage,
origContent
.replace('// throw new', 'throw new')
.replace('{/* <div', '<div')
.replace('</div> */}', '</div>')
)
await browser.waitForElementByCss('#after-change')
// we need to reload the page to trigger getStaticProps
await browser.refresh()
expect(await hasRedbox(browser)).toBe(true)
const errOverlayContent = await getRedboxHeader(browser)
await next.patchFile(indexPage, origContent)
const errorMsg = /oops from getStaticProps/
expect(next.cliOutput).toMatch(errorMsg)
expect(errOverlayContent).toMatch(errorMsg)
})
it('should always call getStaticProps without caching in dev', async () => {
const initialRes = await fetchViaHTTP(next.url, '/something')
expect(isCachingHeader(initialRes.headers.get('cache-control'))).toBe(
false
)
const initialHtml = await initialRes.text()
expect(initialHtml).toMatch(/hello.*?world/)
const newRes = await fetchViaHTTP(next.url, '/something')
expect(isCachingHeader(newRes.headers.get('cache-control'))).toBe(false)
const newHtml = await newRes.text()
expect(newHtml).toMatch(/hello.*?world/)
expect(initialHtml !== newHtml).toBe(true)
const newerRes = await fetchViaHTTP(next.url, '/something')
expect(isCachingHeader(newerRes.headers.get('cache-control'))).toBe(
false
)
const newerHtml = await newerRes.text()
expect(newerHtml).toMatch(/hello.*?world/)
expect(newHtml !== newerHtml).toBe(true)
})
it('should error on bad object from getStaticProps', async () => {
const indexPage = 'pages/index.js'
const origContent = await next.readFile(indexPage)
await next.patchFile(
indexPage,
origContent.replace(/\/\/ bad-prop/, 'another: true,')
)
await waitFor(1000)
try {
const html = await renderViaHTTP(next.url, '/')
expect(html).toMatch(/Additional keys were returned/)
} finally {
await next.patchFile(indexPage, origContent)
}
})
it('should error on dynamic page without getStaticPaths', async () => {
const curPage = 'pages/temp/[slug].js'
await next.patchFile(
curPage,
`
export async function getStaticProps() {
return {
props: {
hello: 'world'
}
}
}
export default () => 'oops'
`
)
await waitFor(1000)
try {
const html = await renderViaHTTP(next.url, '/temp/hello')
expect(html).toMatch(
/getStaticPaths is required for dynamic SSG pages and is missing for/
)
} finally {
await next.deleteFile(curPage)
}
})
it('should error on dynamic page without getStaticPaths returning fallback property', async () => {
const curPage = 'pages/temp2/[slug].js'
await next.patchFile(
curPage,
`
export async function getStaticPaths() {
return {
paths: []
}
}
export async function getStaticProps() {
return {
props: {
hello: 'world'
}
}
}
export default () => 'oops'
`
)
await waitFor(1000)
try {
const html = await renderViaHTTP(next.url, '/temp2/hello')
expect(html).toMatch(/`fallback` key must be returned from/)
} finally {
await next.deleteFile(curPage)
}
})
it('should not re-call getStaticProps when updating query', async () => {
const browser = await webdriver(next.url, '/something?hello=world')
await waitFor(2000)
const query = await browser.elementByCss('#query').text()
expect(JSON.parse(query)).toEqual({ hello: 'world' })
const {
props: {
pageProps: { random: initialRandom },
},
} = await browser.eval('window.__NEXT_DATA__')
const curRandom = await browser.elementByCss('#random').text()
expect(curRandom).toBe(initialRandom + '')
})
it('should show fallback before invalid JSON is returned from getStaticProps', async () => {
const html = await renderViaHTTP(next.url, '/non-json/foobar')
expect(html).toContain('"isFallback":true')
})
it('should not fallback before invalid JSON is returned from getStaticProps when blocking fallback', async () => {
const html = await renderViaHTTP(next.url, '/non-json-blocking/foobar')
expect(html).toContain('"isFallback":false')
})
it('should show error for invalid JSON returned from getStaticProps on SSR', async () => {
const browser = await webdriver(next.url, '/non-json/direct')
// FIXME: enable this
// expect(await getRedboxHeader(browser)).toMatch(
// /Error serializing `.time` returned from `getStaticProps`/
// )
// FIXME: disable this
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatch(
/Failed to load static props/
)
})
it('should show error for invalid JSON returned from getStaticProps on CST', async () => {
const browser = await webdriver(next.url, '/')
await browser.elementByCss('#non-json').click()
// FIXME: enable this
// expect(await getRedboxHeader(browser)).toMatch(
// /Error serializing `.time` returned from `getStaticProps`/
// )
// FIXME: disable this
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatch(
/Failed to load static props/
)
})
it('should not contain headers already sent error', async () => {
await renderViaHTTP(next.url, '/fallback-only/some-fallback-post')
expect(next.cliOutput).not.toContain('ERR_HTTP_HEADERS_SENT')
})
} else {
it('should use correct caching headers for a no-revalidate page', async () => {
const initialRes = await fetchViaHTTP(next.url, '/something')
expect(initialRes.headers.get('cache-control')).toBe(
's-maxage=31536000, stale-while-revalidate'
)
const initialHtml = await initialRes.text()
expect(initialHtml).toMatch(/hello.*?world/)
})
it('should not show error for invalid JSON returned from getStaticProps on SSR', async () => {
const browser = await webdriver(next.url, '/non-json/direct')
await check(() => getBrowserBodyText(browser), /hello /)
})
it('should not show error for invalid JSON returned from getStaticProps on CST', async () => {
const browser = await webdriver(next.url, '/')
await browser.elementByCss('#non-json').click()
await check(() => getBrowserBodyText(browser), /hello /)
})
if ((global as any).isNextStart) {
it('outputs dataRoutes in routes-manifest correctly', async () => {
const { dataRoutes } = JSON.parse(
await next.readFile('.next/routes-manifest.json')
)
for (const route of dataRoutes) {
route.dataRouteRegex = normalizeRegEx(route.dataRouteRegex)
}
expect(dataRoutes).toEqual([
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/index.json$`
),
page: '/',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/another.json$`
),
page: '/another',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/api\\-docs\\/(.+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
next.buildId
)}/api\\-docs/(?<slug>.+?)\\.json$`,
page: '/api-docs/[...slug]',
routeKeys: {
slug: 'slug',
},
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/bad-gssp.json$`
),
page: '/bad-gssp',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/bad-ssr.json$`
),
page: '/bad-ssr',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/blocking\\-fallback\\/([^\\/]+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
next.buildId
)}/blocking\\-fallback/(?<slug>[^/]+?)\\.json$`,
page: '/blocking-fallback/[slug]',
routeKeys: { slug: 'slug' },
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/blocking\\-fallback\\-once\\/([^\\/]+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
next.buildId
)}/blocking\\-fallback\\-once/(?<slug>[^/]+?)\\.json$`,
page: '/blocking-fallback-once/[slug]',
routeKeys: { slug: 'slug' },
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/blocking\\-fallback\\-some\\/([^\\/]+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
next.buildId
)}/blocking\\-fallback\\-some/(?<slug>[^/]+?)\\.json$`,
page: '/blocking-fallback-some/[slug]',
routeKeys: { slug: 'slug' },
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/blog.json$`
),
page: '/blog',
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
next.buildId
)}/blog/(?<post>[^/]+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/blog\\/([^\\/]+?)\\.json$`
),
page: '/blog/[post]',
routeKeys: {
post: 'post',
},
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
next.buildId
)}/blog/(?<post>[^/]+?)/(?<comment>[^/]+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/blog\\/([^\\/]+?)\\/([^\\/]+?)\\.json$`
),
page: '/blog/[post]/[comment]',
routeKeys: {
post: 'post',
comment: 'comment',
},
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
next.buildId
)}/catchall/(?<slug>.+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/catchall\\/(.+?)\\.json$`
),
page: '/catchall/[...slug]',
routeKeys: {
slug: 'slug',
},
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
next.buildId
)}/catchall\\-explicit/(?<slug>.+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/catchall\\-explicit\\/(.+?)\\.json$`
),
page: '/catchall-explicit/[...slug]',
routeKeys: {
slug: 'slug',
},
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
next.buildId
)}/catchall\\-optional(?:/(?<slug>.+?))?\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/catchall\\-optional(?:\\/(.+?))?\\.json$`
),
page: '/catchall-optional/[[...slug]]',
routeKeys: {
slug: 'slug',
},
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/default-revalidate.json$`
),
page: '/default-revalidate',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/dynamic\\/([^\\/]+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
next.buildId
)}/dynamic/(?<slug>[^/]+?)\\.json$`,
page: '/dynamic/[slug]',
routeKeys: {
slug: 'slug',
},
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/fallback\\-only\\/([^\\/]+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
next.buildId
)}/fallback\\-only/(?<slug>[^/]+?)\\.json$`,
page: '/fallback-only/[slug]',
routeKeys: {
slug: 'slug',
},
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/index\\/index.json$`
),
page: '/index',
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
next.buildId
)}/lang/(?<lang>[^/]+?)/about\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/lang\\/([^\\/]+?)\\/about\\.json$`
),
page: '/lang/[lang]/about',
routeKeys: {
lang: 'lang',
},
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
next.buildId
)}/non\\-json/(?<p>[^/]+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/non\\-json\\/([^\\/]+?)\\.json$`
),
page: '/non-json/[p]',
routeKeys: {
p: 'p',
},
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
next.buildId
)}/non\\-json\\-blocking/(?<p>[^/]+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/non\\-json\\-blocking\\/([^\\/]+?)\\.json$`
),
page: '/non-json-blocking/[p]',
routeKeys: {
p: 'p',
},
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/something.json$`
),
page: '/something',
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
next.buildId
)}/user/(?<user>[^/]+?)/profile\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
next.buildId
)}\\/user\\/([^\\/]+?)\\/profile\\.json$`
),
page: '/user/[user]/profile',
routeKeys: {
user: 'user',
},
},
])
})
it('outputs a prerender-manifest correctly', async () => {
const manifest = JSON.parse(
await next.readFile('.next/prerender-manifest.json')
)
const escapedBuildId = escapeRegex(next.buildId)
Object.keys(manifest.dynamicRoutes).forEach((key) => {
const item = manifest.dynamicRoutes[key]
if (item.dataRouteRegex) {
item.dataRouteRegex = normalizeRegEx(item.dataRouteRegex)
}
if (item.routeRegex) {
item.routeRegex = normalizeRegEx(item.routeRegex)
}
})
expect(manifest.version).toBe(3)
expect(manifest.routes).toEqual(expectedManifestRoutes())
expect(manifest.dynamicRoutes).toEqual({
'/api-docs/[...slug]': {
dataRoute: `/_next/data/${next.buildId}/api-docs/[...slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/api\\-docs\\/(.+?)\\.json$`
),
fallback: '/api-docs/[...slug].html',
routeRegex: normalizeRegEx(`^\\/api\\-docs\\/(.+?)(?:\\/)?$`),
},
'/blocking-fallback-once/[slug]': {
dataRoute: `/_next/data/${next.buildId}/blocking-fallback-once/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blocking\\-fallback\\-once\\/([^\\/]+?)\\.json$`
),
fallback: null,
routeRegex: normalizeRegEx(
'^\\/blocking\\-fallback\\-once\\/([^\\/]+?)(?:\\/)?$'
),
},
'/blocking-fallback-some/[slug]': {
dataRoute: `/_next/data/${next.buildId}/blocking-fallback-some/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blocking\\-fallback\\-some\\/([^\\/]+?)\\.json$`
),
fallback: null,
routeRegex: normalizeRegEx(
'^\\/blocking\\-fallback\\-some\\/([^\\/]+?)(?:\\/)?$'
),
},
'/blocking-fallback/[slug]': {
dataRoute: `/_next/data/${next.buildId}/blocking-fallback/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blocking\\-fallback\\/([^\\/]+?)\\.json$`
),
fallback: null,
routeRegex: normalizeRegEx(
'^\\/blocking\\-fallback\\/([^\\/]+?)(?:\\/)?$'
),
},
'/blog/[post]': {
fallback: '/blog/[post].html',
dataRoute: `/_next/data/${next.buildId}/blog/[post].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blog\\/([^\\/]+?)\\.json$`
),
routeRegex: normalizeRegEx('^\\/blog\\/([^\\/]+?)(?:\\/)?$'),
},
'/blog/[post]/[comment]': {
fallback: '/blog/[post]/[comment].html',
dataRoute: `/_next/data/${next.buildId}/blog/[post]/[comment].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blog\\/([^\\/]+?)\\/([^\\/]+?)\\.json$`
),
routeRegex: normalizeRegEx(
'^\\/blog\\/([^\\/]+?)\\/([^\\/]+?)(?:\\/)?$'
),
},
'/dynamic/[slug]': {
dataRoute: `/_next/data/${next.buildId}/dynamic/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/dynamic\\/([^\\/]+?)\\.json$`
),
fallback: false,
routeRegex: normalizeRegEx(`^\\/dynamic\\/([^\\/]+?)(?:\\/)?$`),
},
'/fallback-only/[slug]': {
dataRoute: `/_next/data/${next.buildId}/fallback-only/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/fallback\\-only\\/([^\\/]+?)\\.json$`
),
fallback: '/fallback-only/[slug].html',
routeRegex: normalizeRegEx(
'^\\/fallback\\-only\\/([^\\/]+?)(?:\\/)?$'
),
},
'/lang/[lang]/about': {
dataRoute: `/_next/data/${next.buildId}/lang/[lang]/about.json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/lang\\/([^\\/]+?)\\/about\\.json$`
),
fallback: false,
routeRegex: normalizeRegEx(
'^\\/lang\\/([^\\/]+?)\\/about(?:\\/)?$'
),
},
'/non-json-blocking/[p]': {
dataRoute: `/_next/data/${next.buildId}/non-json-blocking/[p].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/non\\-json\\-blocking\\/([^\\/]+?)\\.json$`
),
fallback: null,
routeRegex: normalizeRegEx(
'^\\/non\\-json\\-blocking\\/([^\\/]+?)(?:\\/)?$'
),
},
'/non-json/[p]': {
dataRoute: `/_next/data/${next.buildId}/non-json/[p].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/non\\-json\\/([^\\/]+?)\\.json$`
),
fallback: '/non-json/[p].html',
routeRegex: normalizeRegEx(
'^\\/non\\-json\\/([^\\/]+?)(?:\\/)?$'
),
},
'/user/[user]/profile': {
fallback: '/user/[user]/profile.html',
dataRoute: `/_next/data/${next.buildId}/user/[user]/profile.json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/user\\/([^\\/]+?)\\/profile\\.json$`
),
routeRegex: normalizeRegEx(
`^\\/user\\/([^\\/]+?)\\/profile(?:\\/)?$`
),
},
'/catchall/[...slug]': {
fallback: '/catchall/[...slug].html',
routeRegex: normalizeRegEx('^\\/catchall\\/(.+?)(?:\\/)?$'),
dataRoute: `/_next/data/${next.buildId}/catchall/[...slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/catchall\\/(.+?)\\.json$`
),
},
'/catchall-optional/[[...slug]]': {
dataRoute: `/_next/data/${next.buildId}/catchall-optional/[[...slug]].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/catchall\\-optional(?:\\/(.+?))?\\.json$`
),
fallback: false,
routeRegex: normalizeRegEx(
'^\\/catchall\\-optional(?:\\/(.+?))?(?:\\/)?$'
),
},
'/catchall-explicit/[...slug]': {
dataRoute: `/_next/data/${next.buildId}/catchall-explicit/[...slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/catchall\\-explicit\\/(.+?)\\.json$`
),
fallback: false,
routeRegex: normalizeRegEx(
'^\\/catchall\\-explicit\\/(.+?)(?:\\/)?$'
),
},
})
})
it('outputs prerendered files correctly', async () => {
const routes = [
'/another',
'/something',
'/blog/post-1',
'/blog/post-2/comment-2',
]
for (const route of routes) {
await next.readFile(join('.next/server/pages', `${route}.html`))
await next.readFile(join('.next/server/pages', `${route}.json`))
}
})
it('should handle de-duping correctly', async () => {
let vals = new Array(10).fill(null)
// use data route so we don't get the fallback
vals = await Promise.all(
vals.map(() =>
renderViaHTTP(
next.url,
`/_next/data/${next.buildId}/blog/post-10.json`
)
)
)
const val = vals[0]
expect(JSON.parse(val).pageProps.post).toBe('post-10')
expect(new Set(vals).size).toBe(1)
})
}
it('should not revalidate when set to false', async () => {
const route = '/something'
const initialHtml = await renderViaHTTP(next.url, route)
let newHtml = await renderViaHTTP(next.url, route)
expect(initialHtml).toBe(newHtml)
newHtml = await renderViaHTTP(next.url, route)
expect(initialHtml).toBe(newHtml)
newHtml = await renderViaHTTP(next.url, route)
expect(initialHtml).toBe(newHtml)
})
it('should not revalidate when set to false in blocking fallback mode', async () => {
const route = '/blocking-fallback-once/test-no-revalidate'
const initialHtml = await renderViaHTTP(next.url, route)
let newHtml = await renderViaHTTP(next.url, route)
expect(initialHtml).toBe(newHtml)
newHtml = await renderViaHTTP(next.url, route)
expect(initialHtml).toBe(newHtml)
newHtml = await renderViaHTTP(next.url, route)
expect(initialHtml).toBe(newHtml)
})
it('should handle revalidating HTML correctly', async () => {
const route = '/blog/post-2/comment-2'
await renderViaHTTP(next.url, route)
const initialHtml = await renderViaHTTP(next.url, route)
expect(initialHtml).toMatch(/Post:.*?post-2/)
expect(initialHtml).toMatch(/Comment:.*?comment-2/)
let newHtml = await renderViaHTTP(next.url, route)
expect(newHtml).toBe(initialHtml)
await waitFor(2 * 1000)
await renderViaHTTP(next.url, route)
await waitFor(2 * 1000)
newHtml = await renderViaHTTP(next.url, route)
expect(newHtml === initialHtml).toBe(false)
expect(newHtml).toMatch(/Post:.*?post-2/)
expect(newHtml).toMatch(/Comment:.*?comment-2/)
})
it('should handle revalidating JSON correctly', async () => {
const route = `/_next/data/${next.buildId}/blog/post-2/comment-3.json`
const initialJson = await renderViaHTTP(next.url, route)
expect(initialJson).toMatch(/post-2/)
expect(initialJson).toMatch(/comment-3/)
let newJson = await renderViaHTTP(next.url, route)
expect(newJson).toBe(initialJson)
await waitFor(2 * 1000)
await renderViaHTTP(next.url, route)
await waitFor(2 * 1000)
newJson = await renderViaHTTP(next.url, route)
expect(newJson === initialJson).toBe(false)
expect(newJson).toMatch(/post-2/)
expect(newJson).toMatch(/comment-3/)
})
it('should handle revalidating HTML correctly with blocking', async () => {
const route = '/blocking-fallback/pewpew'
const initialHtml = await renderViaHTTP(next.url, route)
expect(initialHtml).toMatch(/Post:.*?pewpew/)
let newHtml = await renderViaHTTP(next.url, route)
expect(newHtml).toBe(initialHtml)
await waitFor(2 * 1000)
await renderViaHTTP(next.url, route)
await waitFor(2 * 1000)
newHtml = await renderViaHTTP(next.url, route)
expect(newHtml === initialHtml).toBe(false)
expect(newHtml).toMatch(/Post:.*?pewpew/)
})
it('should handle revalidating JSON correctly with blocking', async () => {
const route = `/_next/data/${next.buildId}/blocking-fallback/pewpewdata.json`
const initialJson = await renderViaHTTP(next.url, route)
expect(initialJson).toMatch(/pewpewdata/)
let newJson = await renderViaHTTP(next.url, route)
expect(newJson).toBe(initialJson)
await waitFor(2 * 1000)
await renderViaHTTP(next.url, route)
await waitFor(2 * 1000)
newJson = await renderViaHTTP(next.url, route)
expect(newJson === initialJson).toBe(false)
expect(newJson).toMatch(/pewpewdata/)
})
it('should handle revalidating HTML correctly with blocking and seed', async () => {
const route = '/blocking-fallback/a'
const initialHtml = await renderViaHTTP(next.url, route)
const $initial = cheerio.load(initialHtml)
expect($initial('p').text()).toBe('Post: a')
let newHtml = await renderViaHTTP(next.url, route)
expect(newHtml).toBe(initialHtml)
await waitFor(2 * 1000)
await renderViaHTTP(next.url, route)
await waitFor(2 * 1000)
newHtml = await renderViaHTTP(next.url, route)
expect(newHtml === initialHtml).toBe(false)
const $new = cheerio.load(newHtml)
expect($new('p').text()).toBe('Post: a')
})
it('should handle revalidating JSON correctly with blocking and seed', async () => {
const route = `/_next/data/${next.buildId}/blocking-fallback/b.json`
const initialJson = await renderViaHTTP(next.url, route)
expect(JSON.parse(initialJson)).toMatchObject({
pageProps: { params: { slug: 'b' } },
})
let newJson = await renderViaHTTP(next.url, route)
expect(newJson).toBe(initialJson)
await waitFor(2 * 1000)
await renderViaHTTP(next.url, route)
await waitFor(2 * 1000)
newJson = await renderViaHTTP(next.url, route)
expect(newJson === initialJson).toBe(false)
expect(JSON.parse(newJson)).toMatchObject({
pageProps: { params: { slug: 'b' } },
})
})
it('should not fetch prerender data on mount', async () => {
const browser = await webdriver(next.url, '/blog/post-100')
await browser.eval('window.thisShouldStay = true')
await waitFor(2 * 1000)
const val = await browser.eval('window.thisShouldStay')
expect(val).toBe(true)
})
it('should not error when flushing cache files', async () => {
await fetchViaHTTP(next.url, '/user/user-1/profile')
await waitFor(500)
expect(next.cliOutput).not.toMatch(
/Failed to update prerender files for/
)
})
}
// this should come very last
it('should not have attempted sending invalid payload', async () => {
expect(next.cliOutput).not.toContain('argument entity must be string')
})
if ((global as any).isNextStart) {
it('should of formatted build output correctly', () => {
expect(next.cliOutput).toMatch(/○ \/normal/)
expect(next.cliOutput).toMatch(/● \/blog\/\[post\]/)
expect(next.cliOutput).toMatch(/\+2 more paths/)
})
it('should output traces', async () => {
const checks = [
{
page: '/_app',
tests: [
/webpack-runtime\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.min\.js/,
],
notTests: [/node_modules\/react\/cjs\/react\.development\.js/],
},
{
page: '/another',
tests: [
/webpack-runtime\.js/,
/chunks\/.*?\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.min\.js/,
/\/world.txt/,
],
notTests: [
/node_modules\/react\/cjs\/react\.development\.js/,
/node_modules\/@firebase\/firestore\/.*?\.js/,
/\/server\.js/,
],
},
{
page: '/blog/[post]',
tests: [
/webpack-runtime\.js/,
/chunks\/.*?\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.min\.js/,
/node_modules\/@firebase\/firestore\/.*?\.js/,
],
notTests: [
/node_modules\/react\/cjs\/react\.development\.js/,
/\/world.txt/,
],
},
]
for (const check of checks) {
const contents = await next.readFile(
join('.next/server/pages/', check.page + '.js.nft.json')
)
const { version, files } = JSON.parse(contents)
expect(version).toBe(1)
expect(
check.tests.every((item) => files.some((file) => item.test(file)))
).toBe(true)
if (sep === '/') {
expect(
check.notTests.some((item) =>
files.some((file) => item.test(file))
)
).toBe(false)
}
}
})
}
}
runTests((global as any).isNextDev)
})
import Link from 'next/link'
import fs from 'fs'
import path from 'path'
export async function getStaticProps() {
const text = fs
.readFileSync(path.join(process.cwd(), 'world.txt'), 'utf8')
.trim()
return {
props: {
world: text,
time: new Date().getTime(),
},
revalidate: true,
}
}
export default ({ world, time }) => (
<>
<p>hello {world}</p>
<span id="anotherTime">time: {time}</span>
<Link href="/">
<a id="home">to home</a>
</Link>
<br />
<Link href="/something">
<a id="something">to something</a>
</Link>
</>
)
import { useRouter } from 'next/router'
export const getStaticProps = () => {
return {
props: {
hello: 'world',
},
}
}
export const getStaticPaths = () => {
return {
paths: ['/api-docs/first'],
fallback: true,
}
}
export default function Slug(props) {
if (useRouter().isFallback) return 'Loading...'
return (
<>
<p id="api-docs">API Docs</p>
<p id="props">{JSON.stringify(props)}</p>
</>
)
}
export default function handler(req, res) {
throw new Error('lol')
}
export function getServerSideProps() {
throw new Error('lol')
}
export default function BadGssp() {
return <div />
}
export function getServerSideProps() {
return { props: {} }
}
export default function BadSsr() {
throw new Error('oops')
}
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getStaticPaths() {
return {
paths: [],
fallback: 'blocking',
}
}
export async function getStaticProps({ params }) {
await new Promise((resolve) => setTimeout(resolve, 1000))
return {
props: {
params,
hello: 'world',
post: params.slug,
random: Math.random(),
time: (await import('perf_hooks')).performance.now(),
},
revalidate: false,
}
}
export default ({ post, time, params }) => {
if (useRouter().isFallback) {
return <p>hi fallback</p>
}
return (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/">
<a id="home">to home</a>
</Link>
</>
)
}
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getStaticPaths() {
return {
paths: [{ params: { slug: 'a' } }, { params: { slug: 'b' } }],
fallback: 'blocking',
}
}
export async function getStaticProps({ params }) {
await new Promise((resolve) => setTimeout(resolve, 1000))
return {
props: {
params,
hello: 'world',
post: params.slug,
random: Math.random(),
time: (await import('perf_hooks')).performance.now(),
},
revalidate: 1,
}
}
export default ({ post, time, params }) => {
if (useRouter().isFallback) {
return <p>hi fallback</p>
}
return (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/">
<a id="home">to home</a>
</Link>
</>
)
}
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getStaticPaths() {
return {
paths: [],
fallback: 'blocking',
}
}
export async function getStaticProps({ params }) {
await new Promise((resolve) => setTimeout(resolve, 1000))
return {
props: {
params,
hello: 'world',
post: params.slug,
random: Math.random(),
time: (await import('perf_hooks')).performance.now(),
},
revalidate: 1,
}
}
export default ({ post, time, params }) => {
if (useRouter().isFallback) {
return <p>hi fallback</p>
}
return (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/">
<a id="home">to home</a>
</Link>
</>
)
}
import React from 'react'
import Link from 'next/link'
export async function getStaticPaths() {
return {
paths: [
'/blog/post-1/comment-1',
{ params: { post: 'post-2', comment: 'comment-2' } },
],
fallback: true,
}
}
export async function getStaticProps({ params }) {
return {
props: {
post: params.post,
comment: params.comment,
time: new Date().getTime(),
},
revalidate: 2,
}
}
export default ({ post, comment, time }) => {
// we're in a loading state
if (!post) {
return <p>loading...</p>
}
return (
<>
<p>Post: {post}</p>
<p>Comment: {comment}</p>
<span>time: {time}</span>
<Link href="/">
<a id="home">to home</a>
</Link>
</>
)
}
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import 'firebase/firestore'
export async function getStaticPaths() {
return {
paths: [
'/blog/post-1',
{ params: { post: 'post-2' } },
'/blog/[post3]',
'/blog/post-4',
'/blog/post.1',
'/blog/post.1', // handle duplicates
],
fallback: true,
}
}
let counter = 0
export async function getStaticProps({ params }) {
if (params.post === 'post-10') {
await new Promise((resolve) => {
setTimeout(() => resolve(), 1000)
})
}
if (params.post === 'post-100') {
throw new Error('such broken..')
}
if (params.post === 'post-999') {
if (++counter < 6) {
throw new Error('try again..')
}
}
return {
props: {
params,
post: params.post,
time: (await import('perf_hooks')).performance.now(),
},
revalidate: 10,
}
}
export default ({ post, time, params }) => {
return (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/">
<a id="home">to home</a>
</Link>
</>
)
}
import React from 'react'
import Link from 'next/link'
export async function getStaticProps() {
return {
props: {
slugs: ['post-1', 'post-2'],
time: (await import('perf_hooks')).performance.now(),
},
revalidate: 10,
}
}
export default ({ slugs, time }) => {
return (
<>
<p>Posts: {JSON.stringify(slugs)}</p>
<span>time: {time}</span>
<Link href="/">
<a id="home">to home</a>
</Link>
</>
)
}
import Link from 'next/link'
export async function getStaticProps({ params: { slug } }) {
if (slug[0] === 'delayby3s') {
await new Promise((resolve) => setTimeout(resolve, 3000))
}
return {
props: {
slug,
},
revalidate: 1,
}
}
export async function getStaticPaths() {
return {
paths: [
{ params: { slug: ['first'] } },
'/catchall-explicit/second',
{ params: { slug: ['another', 'value'] } },
'/catchall-explicit/hello/another',
'/catchall-explicit/[first]/[second]',
{ params: { slug: ['[third]', '[fourth]'] } },
],
fallback: false,
}
}
export default function Page({ slug }) {
// Important to not check for `slug` existence (testing that build does not
// render fallback version and error)
return (
<>
<p id="catchall">Hi {slug.join(' ')}</p>{' '}
<Link href="/">
<a id="home">to home</a>
</Link>
</>
)
}
import Link from 'next/link'
export async function getStaticProps({ params: { slug } }) {
return {
props: {
slug: slug || [],
},
}
}
export async function getStaticPaths() {
return {
paths: [{ params: { slug: [] } }, { params: { slug: ['value'] } }],
fallback: false,
}
}
export default ({ slug }) => {
// Important to not check for `slug` existence (testing that build does not
// render fallback version and error)
return (
<>
<p id="catchall">Catch all: [{slug.join(', ')}]</p>
<Link href="/">
<a id="home">to home</a>
</Link>
</>
)
}
import { useRouter } from 'next/router'
export async function getStaticProps({ params: { slug } }) {
if (slug[0] === 'delayby3s') {
await new Promise((resolve) => setTimeout(resolve, 3000))
}
return {
props: {
slug,
},
revalidate: 1,
}
}
export async function getStaticPaths() {
return {
paths: [
{ params: { slug: ['first'] } },
'/catchall/second',
{ params: { slug: ['another', 'value'] } },
'/catchall/hello/another',
],
fallback: true,
}
}
export default ({ slug }) => {
const { isFallback } = useRouter()
if (isFallback) {
return <p id="catchall">fallback</p>
}
return <p id="catchall">Hi {slug.join(' ')}</p>
}
import Link from 'next/link'
export async function getStaticProps() {
return {
props: {
world: 'world',
time: new Date().getTime(),
},
}
}
export default ({ world, time }) => (
<>
<p>hello {world}</p>
<span>time: {time}</span>
<Link href="/">
<a id="home">to home</a>
</Link>
<br />
<Link href="/something">
<a id="something">to something</a>
</Link>
</>
)
import Link from 'next/link'
export async function getStaticProps({ params: { slug } }) {
return {
props: { slug },
}
}
export async function getStaticPaths() {
return {
paths: [{ params: { slug: '[first]' } }, '/dynamic/[second]'],
fallback: false,
}
}
export default ({ slug }) => {
// Important to not check for `slug` existence (testing that build does not
// render fallback version and error)
return (
<>
<p id="param">Hi {slug}!</p>{' '}
<Link href="/">
<a id="home">to home</a>
</Link>
</>
)
}
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getStaticPaths() {
return {
paths: [],
fallback: true,
}
}
export async function getStaticProps({ params }) {
await new Promise((resolve) => setTimeout(resolve, 1000))
return {
props: {
params,
hello: 'world',
post: params.slug,
random: Math.random(),
time: (await import('perf_hooks')).performance.now(),
},
revalidate: 1,
}
}
export default ({ post, time, params }) => {
if (useRouter().isFallback) {
return <p>hi fallback</p>
}
return (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/">
<a id="home">to home</a>
</Link>
</>
)
}
import Link from 'next/link'
export async function getStaticProps() {
// throw new Error('oops from getStaticProps')
return {
props: { world: 'world', time: new Date().getTime() },
// bad-prop
revalidate: 2,
}
}
const Page = ({ world, time }) => {
return (
<>
{/* <div id='after-change'>idk</div> */}
<p>hello {world}</p>
<span>time: {time}</span>
<Link href="/non-json/[p]" as="/non-json/1">
<a id="non-json">to non-json</a>
</Link>
<br />
<Link href="/another?hello=world" as="/another/?hello=world">
<a id="another">to another</a>
</Link>
<br />
<Link href="/something">
<a id="something">to something</a>
</Link>
<br />
<Link href="/normal">
<a id="normal">to normal</a>
</Link>
<br />
<Link href="/blog/[post]" as="/blog/post-1">
<a id="post-1">to dynamic</a>
</Link>
<Link href="/blog/[post]" as="/blog/post-100">
<a id="broken-post">to broken</a>
</Link>
<Link href="/blog/[post]" as="/blog/post-999" prefetch={false}>
<a id="broken-at-first-post">to broken at first</a>
</Link>
<br />
<Link href="/blog/[post]/[comment]" as="/blog/post-1/comment-1">
<a id="comment-1">to another dynamic</a>
</Link>
<Link href="/catchall/[...slug]" as="/catchall/first">
<a id="to-catchall">to catchall</a>
</Link>
<br />
<Link href="/index">
<a id="to-nested-index">to nested index</a>
</Link>
<br />
<Link href="/lang/[lang]/about?lang=en" as="/about">
<a id="to-rewritten-ssg">to rewritten static path page</a>
</Link>
<br />
<Link href="/catchall-optional/[[...slug]]" as="/catchall-optional">
<a id="catchall-optional-root">to optional catchall root</a>
</Link>
<Link href="/catchall-optional/[[...slug]]" as="/catchall-optional/value">
<a id="catchall-optional-value">to optional catchall page /value</a>
</Link>
<br />
<Link href="/dynamic/[slug]" as="/dynamic/[first]">
<a id="dynamic-first">to dynamic [first] page</a>
</Link>
<Link href="/dynamic/[slug]" as="/dynamic/[second]">
<a id="dynamic-second">to dynamic [second] page</a>
</Link>
<br />
<Link
href="/catchall-explicit/[...slug]"
as="/catchall-explicit/[first]/[second]"
>
<a id="catchall-explicit-string">
to catchall-explicit [first]/[second] page
</a>
</Link>
<Link
href="/catchall-explicit/[...slug]"
as="/catchall-explicit/[third]/[fourth]"
>
<a id="catchall-explicit-object">
to catchall-explicit [third]/[fourth] page
</a>
</Link>
</>
)
}
export default Page
import Link from 'next/link'
export async function getStaticProps() {
return {
props: { world: 'nested index' },
}
}
export default ({ world }) => {
return (
<>
<p>hello {world}</p>
<Link href="/">
<a id="home">to home</a>
</Link>
</>
)
}
export default ({ lang }) => <p id="about">About: {lang}</p>
export const getStaticProps = ({ params: { lang } }) => ({
props: {
lang,
},
})
export const getStaticPaths = () => ({
paths: ['en', 'es', 'fr', 'de'].map((p) => `/lang/${p}/about`),
fallback: false,
})
import { useRouter } from 'next/router'
export async function getStaticProps() {
return {
props: { time: new Date() },
}
}
export async function getStaticPaths() {
return { paths: [], fallback: 'blocking' }
}
const Page = ({ time }) => {
const { isFallback } = useRouter()
if (isFallback) return null
return <p>hello blocking {time.toString()}</p>
}
export default Page
import { useRouter } from 'next/router'
export async function getStaticProps() {
return {
props: { time: new Date() },
}
}
export async function getStaticPaths() {
return { paths: [], fallback: true }
}
const Page = ({ time }) => {
const { isFallback } = useRouter()
if (isFallback) return null
return <p>hello {time.toString()}</p>
}
export default Page
export default () => <p id="normal-text">a normal page</p>
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getStaticProps({ params }) {
return {
props: {
world: 'world',
params: params || {},
time: new Date().getTime(),
random: Math.random(),
},
revalidate: false,
}
}
export default ({ world, time, params, random }) => {
return (
<>
<p>hello: {world}</p>
<span>time: {time}</span>
<div id="random">{random}</div>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/">
<a id="home">to home</a>
</Link>
<br />
<Link href="/another">
<a id="another">to another</a>
</Link>
</>
)
}
import React from 'react'
import Link from 'next/link'
export async function getStaticPaths() {
return { paths: [], fallback: true }
}
export async function getStaticProps({ params }) {
return {
props: {
user: params.user,
time: (await import('perf_hooks')).performance.now(),
},
revalidate: 10,
}
}
export default ({ user, time }) => {
return (
<>
<p>User: {user}</p>
<span>time: {time}</span>
<Link href="/">
<a id="home">to home</a>
</Link>
</>
)
}
module.exports = {
experimental: {
nftTracing: true,
},
}
module.exports = {
// target
rewrites() {
return [
{
source: '/some-rewrite/:item',
destination: '/blog/post-:item',
},
{
source: '/about',
destination: '/lang/en/about',
},
{
source: '/blocked-create',
destination: '/blocking-fallback/blocked-create',
},
]
},
experimental: {
nftTracing: true,
},
}
const http = require('http')
const url = require('url')
const fs = require('fs')
const path = require('path')
const server = http.createServer(async (req, res) => {
let { pathname } = url.parse(req.url)
pathname = pathname.replace(/\/$/, '')
let isDataReq = false
if (pathname.startsWith('/_next/data')) {
isDataReq = true
pathname = pathname
.replace(`/_next/data/${process.env.BUILD_ID}/`, '/')
.replace(/\.json$/, '')
}
console.log('serving', pathname)
if (pathname === '/favicon.ico') {
res.statusCode = 404
return res.end()
}
if (pathname.startsWith('/_next/static/')) {
res.write(
fs.readFileSync(
path.join(
__dirname,
'./.next/static/',
decodeURI(pathname.slice('/_next/static/'.length))
),
'utf8'
)
)
return res.end()
} else {
const ext = isDataReq ? 'json' : 'html'
if (
fs.existsSync(
path.join(__dirname, `./.next/serverless/pages${pathname}.${ext}`)
)
) {
res.write(
fs.readFileSync(
path.join(__dirname, `./.next/serverless/pages${pathname}.${ext}`),
'utf8'
)
)
return res.end()
}
let re
try {
re = require(`./.next/serverless/pages${pathname}`)
} catch {
const d = decodeURI(pathname)
if (
fs.existsSync(
path.join(__dirname, `./.next/serverless/pages${d}.${ext}`)
)
) {
res.write(
fs.readFileSync(
path.join(__dirname, `./.next/serverless/pages${d}.${ext}`),
'utf8'
)
)
return res.end()
}
const routesManifest = require('./.next/routes-manifest.json')
const { dynamicRoutes } = routesManifest
dynamicRoutes.some(({ page, regex }) => {
if (new RegExp(regex).test(pathname)) {
if (
fs.existsSync(
path.join(__dirname, `./.next/serverless/pages${page}.${ext}`)
)
) {
res.write(
fs.readFileSync(
path.join(__dirname, `./.next/serverless/pages${page}.${ext}`),
'utf8'
)
)
res.end()
return true
}
re = require(`./.next/serverless/pages${page}`)
return true
}
return false
})
}
if (!res.finished) {
try {
return await (typeof re.render === 'function'
? re.render(req, res)
: re.default(req, res))
} catch (e) {
console.log('FAIL_FUNCTION', e)
res.statusCode = 500
res.write('FAIL_FUNCTION')
res.end()
}
}
}
})
server.listen(process.env.PORT, () => {
console.log('ready on', process.env.PORT)
})
/* eslint-env jest */
import cheerio from 'cheerio'
import escapeRegex from 'escape-string-regexp'
import fs from 'fs-extra'
import { join } from 'path'
import webdriver from 'next-webdriver'
import {
check,
fetchViaHTTP,
File,
findPort,
getBrowserBodyText,
getRedboxHeader,
hasRedbox,
initNextServerScript,
killApp,
launchApp,
nextBuild,
nextExport,
nextStart,
normalizeRegEx,
renderViaHTTP,
startStaticServer,
stopApp,
waitFor,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import { dirname, join, sep } from 'path'
const appDir = join(__dirname, '..')
const nextConfigPath = join(appDir, 'next.config.js')
const indexPage = join(__dirname, '../pages/index.js')
const nextConfig = new File(nextConfigPath)
let app
let appPort
let buildId
let distPagesDir
let exportDir
let stderr
const startServer = async (optEnv = {}) => {
const scriptPath = join(appDir, 'server.js')
const env = Object.assign(
{},
{ ...process.env },
{ PORT: `${appPort}` },
optEnv
)
return initNextServerScript(
scriptPath,
/ready on/i,
env,
/ReferenceError: options is not defined/
)
}
const expectedManifestRoutes = () => ({
'/': {
dataRoute: `/_next/data/${buildId}/index.json`,
initialRevalidateSeconds: 2,
srcRoute: null,
},
'/blog/[post3]': {
dataRoute: `/_next/data/${buildId}/blog/[post3].json`,
initialRevalidateSeconds: 10,
srcRoute: '/blog/[post]',
},
'/blog/post-1': {
dataRoute: `/_next/data/${buildId}/blog/post-1.json`,
initialRevalidateSeconds: 10,
srcRoute: '/blog/[post]',
},
'/blog/post-2': {
dataRoute: `/_next/data/${buildId}/blog/post-2.json`,
initialRevalidateSeconds: 10,
srcRoute: '/blog/[post]',
},
'/blog/post-4': {
dataRoute: `/_next/data/${buildId}/blog/post-4.json`,
initialRevalidateSeconds: 10,
srcRoute: '/blog/[post]',
},
'/blog/post-1/comment-1': {
dataRoute: `/_next/data/${buildId}/blog/post-1/comment-1.json`,
initialRevalidateSeconds: 2,
srcRoute: '/blog/[post]/[comment]',
},
'/blog/post-2/comment-2': {
dataRoute: `/_next/data/${buildId}/blog/post-2/comment-2.json`,
initialRevalidateSeconds: 2,
srcRoute: '/blog/[post]/[comment]',
},
'/blog/post.1': {
dataRoute: `/_next/data/${buildId}/blog/post.1.json`,
initialRevalidateSeconds: 10,
srcRoute: '/blog/[post]',
},
'/catchall-explicit/another/value': {
dataRoute: `/_next/data/${buildId}/catchall-explicit/another/value.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/catchall-explicit/first': {
dataRoute: `/_next/data/${buildId}/catchall-explicit/first.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/catchall-explicit/hello/another': {
dataRoute: `/_next/data/${buildId}/catchall-explicit/hello/another.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/catchall-explicit/second': {
dataRoute: `/_next/data/${buildId}/catchall-explicit/second.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/catchall-explicit/[first]/[second]': {
dataRoute: `/_next/data/${buildId}/catchall-explicit/[first]/[second].json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/catchall-explicit/[third]/[fourth]': {
dataRoute: `/_next/data/${buildId}/catchall-explicit/[third]/[fourth].json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall-explicit/[...slug]',
},
'/catchall-optional': {
dataRoute: `/_next/data/${buildId}/catchall-optional.json`,
initialRevalidateSeconds: false,
srcRoute: '/catchall-optional/[[...slug]]',
},
'/catchall-optional/value': {
dataRoute: `/_next/data/${buildId}/catchall-optional/value.json`,
initialRevalidateSeconds: false,
srcRoute: '/catchall-optional/[[...slug]]',
},
'/another': {
dataRoute: `/_next/data/${buildId}/another.json`,
initialRevalidateSeconds: 1,
srcRoute: null,
},
'/api-docs/first': {
dataRoute: `/_next/data/${buildId}/api-docs/first.json`,
initialRevalidateSeconds: false,
srcRoute: '/api-docs/[...slug]',
},
'/blocking-fallback-some/a': {
dataRoute: `/_next/data/${buildId}/blocking-fallback-some/a.json`,
initialRevalidateSeconds: 1,
srcRoute: '/blocking-fallback-some/[slug]',
},
'/blocking-fallback-some/b': {
dataRoute: `/_next/data/${buildId}/blocking-fallback-some/b.json`,
initialRevalidateSeconds: 1,
srcRoute: '/blocking-fallback-some/[slug]',
},
'/blog': {
dataRoute: `/_next/data/${buildId}/blog.json`,
initialRevalidateSeconds: 10,
srcRoute: null,
},
'/default-revalidate': {
dataRoute: `/_next/data/${buildId}/default-revalidate.json`,
initialRevalidateSeconds: false,
srcRoute: null,
},
'/dynamic/[first]': {
dataRoute: `/_next/data/${buildId}/dynamic/[first].json`,
initialRevalidateSeconds: false,
srcRoute: '/dynamic/[slug]',
},
'/dynamic/[second]': {
dataRoute: `/_next/data/${buildId}/dynamic/[second].json`,
initialRevalidateSeconds: false,
srcRoute: '/dynamic/[slug]',
},
'/index': {
dataRoute: `/_next/data/${buildId}/index/index.json`,
initialRevalidateSeconds: false,
srcRoute: null,
},
'/lang/de/about': {
dataRoute: `/_next/data/${buildId}/lang/de/about.json`,
initialRevalidateSeconds: false,
srcRoute: '/lang/[lang]/about',
},
'/lang/en/about': {
dataRoute: `/_next/data/${buildId}/lang/en/about.json`,
initialRevalidateSeconds: false,
srcRoute: '/lang/[lang]/about',
},
'/lang/es/about': {
dataRoute: `/_next/data/${buildId}/lang/es/about.json`,
initialRevalidateSeconds: false,
srcRoute: '/lang/[lang]/about',
},
'/lang/fr/about': {
dataRoute: `/_next/data/${buildId}/lang/fr/about.json`,
initialRevalidateSeconds: false,
srcRoute: '/lang/[lang]/about',
},
'/something': {
dataRoute: `/_next/data/${buildId}/something.json`,
initialRevalidateSeconds: false,
srcRoute: null,
},
'/catchall/another/value': {
dataRoute: `/_next/data/${buildId}/catchall/another/value.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall/[...slug]',
},
'/catchall/first': {
dataRoute: `/_next/data/${buildId}/catchall/first.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall/[...slug]',
},
'/catchall/second': {
dataRoute: `/_next/data/${buildId}/catchall/second.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall/[...slug]',
},
'/catchall/hello/another': {
dataRoute: `/_next/data/${buildId}/catchall/hello/another.json`,
initialRevalidateSeconds: 1,
srcRoute: '/catchall/[...slug]',
},
})
function isCachingHeader(cacheControl) {
return !cacheControl || !/no-store/.test(cacheControl)
}
const navigateTest = (dev = false) => {
it('should navigate between pages successfully', async () => {
......@@ -419,1417 +210,11 @@ const navigateTest = (dev = false) => {
})
}
const runTests = (dev = false, isEmulatedServerless = false) => {
navigateTest(dev)
it('should SSR normal page correctly', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/hello.*?world/)
})
it('should SSR incremental page correctly', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-1')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
expect(html).toMatch(/Post:.*?post-1/)
})
it('should SSR blocking path correctly (blocking)', async () => {
const html = await renderViaHTTP(appPort, '/blocking-fallback/random-path')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
expect($('p').text()).toBe('Post: random-path')
})
it('should SSR blocking path correctly (pre-rendered)', async () => {
const html = await renderViaHTTP(appPort, '/blocking-fallback-some/a')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
expect($('p').text()).toBe('Post: a')
})
it('should have gsp in __NEXT_DATA__', async () => {
const html = await renderViaHTTP(appPort, '/')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).gsp).toBe(true)
})
it('should not have gsp in __NEXT_DATA__ for non-GSP page', async () => {
const html = await renderViaHTTP(appPort, '/normal')
const $ = cheerio.load(html)
expect('gsp' in JSON.parse($('#__NEXT_DATA__').text())).toBe(false)
})
it('should not supply query values to params or useRouter non-dynamic page SSR', async () => {
const html = await renderViaHTTP(appPort, '/something?hello=world')
const $ = cheerio.load(html)
const query = $('#query').text()
expect(JSON.parse(query)).toEqual({})
const params = $('#params').text()
expect(JSON.parse(params)).toEqual({})
})
it('should not supply query values to params in /_next/data request', async () => {
const data = JSON.parse(
await renderViaHTTP(
appPort,
`/_next/data/${buildId}/something.json?hello=world`
)
)
expect(data.pageProps.params).toEqual({})
})
it('should not supply query values to params or useRouter dynamic page SSR', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-1?hello=world')
const $ = cheerio.load(html)
const params = $('#params').text()
expect(JSON.parse(params)).toEqual({ post: 'post-1' })
const query = $('#query').text()
expect(JSON.parse(query)).toEqual({ post: 'post-1' })
})
it('should return data correctly', async () => {
const data = JSON.parse(
await renderViaHTTP(
appPort,
expectedManifestRoutes()['/something'].dataRoute
)
)
expect(data.pageProps.world).toBe('world')
})
it('should return data correctly for dynamic page', async () => {
const data = JSON.parse(
await renderViaHTTP(
appPort,
expectedManifestRoutes()['/blog/post-1'].dataRoute
)
)
expect(data.pageProps.post).toBe('post-1')
})
it('should return data correctly for dynamic page (non-seeded)', async () => {
const data = JSON.parse(
await renderViaHTTP(
appPort,
expectedManifestRoutes()['/blog/post-1'].dataRoute.replace(
/post-1/,
'post-3'
)
)
)
expect(data.pageProps.post).toBe('post-3')
})
if (!dev) {
it('should use correct caching headers for a revalidate page', async () => {
const initialRes = await fetchViaHTTP(appPort, '/')
expect(initialRes.headers.get('cache-control')).toBe(
's-maxage=2, stale-while-revalidate'
)
})
}
it('should navigate to a normal page and back', async () => {
const browser = await webdriver(appPort, '/')
let text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
await browser.elementByCss('#normal').click()
await browser.waitForElementByCss('#normal-text')
text = await browser.elementByCss('#normal-text').text()
expect(text).toMatch(/a normal page/)
})
it('should parse query values on mount correctly', async () => {
const browser = await webdriver(appPort, '/blog/post-1?another=value')
const text = await browser.elementByCss('#query').text()
expect(text).toMatch(/another.*?value/)
expect(text).toMatch(/post.*?post-1/)
})
it('should reload page on failed data request', async () => {
const browser = await webdriver(appPort, '/')
await browser.eval('window.beforeClick = "abc"')
await browser.elementByCss('#broken-post').click()
expect(
await check(() => browser.eval('window.beforeClick'), {
test(v) {
return v !== 'abc'
},
})
).toBe(true)
})
it('should SSR dynamic page with brackets in param as object', async () => {
const html = await renderViaHTTP(appPort, '/dynamic/[first]')
const $ = cheerio.load(html)
expect($('#param').text()).toMatch(/Hi \[first\]!/)
})
it('should navigate to dynamic page with brackets in param as object', async () => {
const browser = await webdriver(appPort, '/')
await browser.elementByCss('#dynamic-first').click()
await browser.waitForElementByCss('#param')
const value = await browser.elementByCss('#param').text()
expect(value).toMatch(/Hi \[first\]!/)
})
it('should SSR dynamic page with brackets in param as string', async () => {
const html = await renderViaHTTP(appPort, '/dynamic/[second]')
const $ = cheerio.load(html)
expect($('#param').text()).toMatch(/Hi \[second\]!/)
})
it('should navigate to dynamic page with brackets in param as string', async () => {
const browser = await webdriver(appPort, '/')
await browser.elementByCss('#dynamic-second').click()
await browser.waitForElementByCss('#param')
const value = await browser.elementByCss('#param').text()
expect(value).toMatch(/Hi \[second\]!/)
})
if (!isEmulatedServerless) {
it('should not return data for fallback: false and missing dynamic page', async () => {
const res1 = await fetchViaHTTP(
appPort,
`/_next/data/${buildId}/dynamic/oopsie.json`
)
expect(res1.status).toBe(404)
await waitFor(500)
const res2 = await fetchViaHTTP(
appPort,
`/_next/data/${buildId}/dynamic/oopsie.json`
)
expect(res2.status).toBe(404)
await waitFor(500)
const res3 = await fetchViaHTTP(
appPort,
`/_next/data/${buildId}/dynamic/oopsie.json`
)
expect(res3.status).toBe(404)
})
}
it('should server prerendered path correctly for SSG pages that starts with api-docs', async () => {
const html = await renderViaHTTP(appPort, '/api-docs/first')
const $ = cheerio.load(html)
expect($('#api-docs').text()).toBe('API Docs')
expect(JSON.parse($('#props').text())).toEqual({
hello: 'world',
})
})
it('should render correctly for SSG pages that starts with api-docs', async () => {
const browser = await webdriver(appPort, '/api-docs/second')
await browser.waitForElementByCss('#api-docs')
expect(await browser.elementByCss('#api-docs').text()).toBe('API Docs')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
hello: 'world',
})
})
it('should return data correctly for SSG pages that starts with api-docs', async () => {
const data = await renderViaHTTP(
appPort,
`/_next/data/${buildId}/api-docs/first.json`
)
const { pageProps } = JSON.parse(data)
expect(pageProps).toEqual({
hello: 'world',
})
})
it('should SSR catch-all page with brackets in param as string', async () => {
const html = await renderViaHTTP(
appPort,
'/catchall-explicit/[first]/[second]'
)
const $ = cheerio.load(html)
expect($('#catchall').text()).toMatch(/Hi \[first\] \[second\]/)
})
it('should navigate to catch-all page with brackets in param as string', async () => {
const browser = await webdriver(appPort, '/')
await browser.elementByCss('#catchall-explicit-string').click()
await browser.waitForElementByCss('#catchall')
const value = await browser.elementByCss('#catchall').text()
expect(value).toMatch(/Hi \[first\] \[second\]/)
})
it('should SSR catch-all page with brackets in param as object', async () => {
const html = await renderViaHTTP(
appPort,
'/catchall-explicit/[third]/[fourth]'
)
const $ = cheerio.load(html)
expect($('#catchall').text()).toMatch(/Hi \[third\] \[fourth\]/)
})
it('should navigate to catch-all page with brackets in param as object', async () => {
const browser = await webdriver(appPort, '/')
await browser.elementByCss('#catchall-explicit-object').click()
await browser.waitForElementByCss('#catchall')
const value = await browser.elementByCss('#catchall').text()
expect(value).toMatch(/Hi \[third\] \[fourth\]/)
})
// TODO: dev currently renders this page as blocking, meaning it shows the
// server error instead of continuously retrying. Do we want to change this?
if (!dev) {
it('should reload page on failed data request, and retry', async () => {
const browser = await webdriver(appPort, '/')
await browser.eval('window.beforeClick = "abc"')
await browser.elementByCss('#broken-at-first-post').click()
expect(
await check(() => browser.eval('window.beforeClick'), {
test(v) {
return v !== 'abc'
},
})
).toBe(true)
const text = await browser.elementByCss('#params').text()
expect(text).toMatch(/post.*?post-999/)
})
}
it('should support prerendered catchall route', async () => {
const html = await renderViaHTTP(appPort, '/catchall/another/value')
const $ = cheerio.load(html)
expect(
JSON.parse(cheerio.load(html)('#__NEXT_DATA__').text()).isFallback
).toBe(false)
expect($('#catchall').text()).toMatch(/Hi.*?another value/)
})
it('should support lazy catchall route', async () => {
const html = await renderViaHTTP(appPort, '/catchall/notreturnedinpaths')
const $ = cheerio.load(html)
expect($('#catchall').text()).toBe('fallback')
// hydration
const browser = await webdriver(appPort, '/catchall/delayby3s')
const text1 = await browser.elementByCss('#catchall').text()
expect(text1).toBe('fallback')
await check(
() => browser.elementByCss('#catchall').text(),
/Hi.*?delayby3s/
)
})
it('should support nested lazy catchall route', async () => {
// We will render fallback for a "lazy" route
const html = await renderViaHTTP(
appPort,
'/catchall/notreturnedinpaths/nested'
)
const $ = cheerio.load(html)
expect($('#catchall').text()).toBe('fallback')
// hydration
const browser = await webdriver(appPort, '/catchall/delayby3s/nested')
const text1 = await browser.elementByCss('#catchall').text()
expect(text1).toBe('fallback')
await check(
() => browser.elementByCss('#catchall').text(),
/Hi.*?delayby3s nested/
)
})
it('should support prerendered catchall-explicit route (nested)', async () => {
const html = await renderViaHTTP(
appPort,
'/catchall-explicit/another/value'
)
const $ = cheerio.load(html)
expect(
JSON.parse(cheerio.load(html)('#__NEXT_DATA__').text()).isFallback
).toBe(false)
expect($('#catchall').text()).toMatch(/Hi.*?another value/)
})
it('should support prerendered catchall-explicit route (single)', async () => {
const html = await renderViaHTTP(appPort, '/catchall-explicit/second')
const $ = cheerio.load(html)
expect(
JSON.parse(cheerio.load(html)('#__NEXT_DATA__').text()).isFallback
).toBe(false)
expect($('#catchall').text()).toMatch(/Hi.*?second/)
})
if (!isEmulatedServerless) {
it('should handle fallback only page correctly HTML', async () => {
const browser = await webdriver(appPort, '/fallback-only/first%2Fpost')
const text = await browser.elementByCss('p').text()
expect(text).toContain('hi fallback')
// wait for fallback data to load
await check(() => browser.elementByCss('p').text(), /Post/)
// check fallback data
const post = await browser.elementByCss('p').text()
const query = JSON.parse(await browser.elementByCss('#query').text())
const params = JSON.parse(await browser.elementByCss('#params').text())
expect(post).toContain('first/post')
expect(params).toEqual({
slug: 'first/post',
})
expect(query).toEqual(params)
})
it('should handle fallback only page correctly data', async () => {
const data = JSON.parse(
await renderViaHTTP(
appPort,
`/_next/data/${buildId}/fallback-only/second%2Fpost.json`
)
)
expect(data.pageProps.params).toEqual({
slug: 'second/post',
})
})
}
if (!isEmulatedServerless) {
it('should 404 for a missing catchall explicit route', async () => {
const res = await fetchViaHTTP(
appPort,
'/catchall-explicit/notreturnedinpaths'
)
expect(res.status).toBe(404)
const html = await res.text()
expect(html).toMatch(/This page could not be found/)
})
it('should allow rewriting to SSG page with fallback: false', async () => {
const html = await renderViaHTTP(appPort, '/about')
expect(html).toMatch(/About:.*?en/)
})
it("should allow rewriting to SSG page with fallback: 'blocking'", async () => {
const html = await renderViaHTTP(appPort, '/blocked-create')
expect(html).toMatch(/Post:.*?blocked-create/)
})
it('should fetch /_next/data correctly with mismatched href and as', async () => {
const browser = await webdriver(appPort, '/')
if (!dev) {
await browser.eval(() =>
document.querySelector('#to-rewritten-ssg').scrollIntoView()
)
await check(async () => {
const hrefs = await browser.eval(
`Object.keys(window.next.router.sdc)`
)
hrefs.sort()
expect(
hrefs.map((href) =>
new URL(href).pathname.replace(/^\/_next\/data\/[^/]+/, '')
)
).toContainEqual('/lang/en/about.json')
return 'yes'
}, 'yes')
}
await browser.eval('window.beforeNav = "hi"')
await browser.elementByCss('#to-rewritten-ssg').click()
await browser.waitForElementByCss('#about')
expect(await browser.eval('window.beforeNav')).toBe('hi')
expect(await browser.elementByCss('#about').text()).toBe('About: en')
})
it('should not error when rewriting to fallback dynamic SSG page', async () => {
const item = Math.round(Math.random() * 100)
const browser = await webdriver(appPort, `/some-rewrite/${item}`)
await check(
() => browser.elementByCss('p').text(),
new RegExp(`Post: post-${item}`)
)
expect(JSON.parse(await browser.elementByCss('#params').text())).toEqual({
post: `post-${item}`,
})
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({
post: `post-${item}`,
})
})
}
if (dev) {
it('should not show warning from url prop being returned', async () => {
const urlPropPage = join(appDir, 'pages/url-prop.js')
await fs.writeFile(
urlPropPage,
`
export async function getStaticProps() {
return {
props: {
url: 'something'
}
}
}
export default ({ url }) => <p>url: {url}</p>
`
)
const html = await renderViaHTTP(appPort, '/url-prop')
await fs.remove(urlPropPage)
expect(stderr).not.toMatch(
/The prop `url` is a reserved prop in Next.js for legacy reasons and will be overridden on page \/url-prop/
)
expect(html).toMatch(/url:.*?something/)
})
it('should always show fallback for page not in getStaticPaths', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-321')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(true)
// make another request to ensure it still is
const html2 = await renderViaHTTP(appPort, '/blog/post-321')
const $2 = cheerio.load(html2)
expect(JSON.parse($2('#__NEXT_DATA__').text()).isFallback).toBe(true)
})
it('should not show fallback for page in getStaticPaths', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-1')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
// make another request to ensure it's still not
const html2 = await renderViaHTTP(appPort, '/blog/post-1')
const $2 = cheerio.load(html2)
expect(JSON.parse($2('#__NEXT_DATA__').text()).isFallback).toBe(false)
})
it('should never show fallback for page not in getStaticPaths when blocking', async () => {
const html = await renderViaHTTP(appPort, '/blocking-fallback-some/asf')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
// make another request to ensure it still is
const html2 = await renderViaHTTP(appPort, '/blocking-fallback-some/asf')
const $2 = cheerio.load(html2)
expect(JSON.parse($2('#__NEXT_DATA__').text()).isFallback).toBe(false)
})
it('should not show fallback for page in getStaticPaths when blocking', async () => {
const html = await renderViaHTTP(appPort, '/blocking-fallback-some/b')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).isFallback).toBe(false)
// make another request to ensure it's still not
const html2 = await renderViaHTTP(appPort, '/blocking-fallback-some/b')
const $2 = cheerio.load(html2)
expect(JSON.parse($2('#__NEXT_DATA__').text()).isFallback).toBe(false)
})
it('should log error in console and browser in dev mode', async () => {
const origContent = await fs.readFile(indexPage, 'utf8')
const browser = await webdriver(appPort, '/')
expect(await browser.elementByCss('p').text()).toMatch(/hello.*?world/)
await fs.writeFile(
indexPage,
origContent
.replace('// throw new', 'throw new')
.replace('{/* <div', '<div')
.replace('</div> */}', '</div>')
)
await browser.waitForElementByCss('#after-change')
// we need to reload the page to trigger getStaticProps
await browser.refresh()
expect(await hasRedbox(browser)).toBe(true)
const errOverlayContent = await getRedboxHeader(browser)
await fs.writeFile(indexPage, origContent)
const errorMsg = /oops from getStaticProps/
expect(stderr).toMatch(errorMsg)
expect(errOverlayContent).toMatch(errorMsg)
})
it('should always call getStaticProps without caching in dev', async () => {
const initialRes = await fetchViaHTTP(appPort, '/something')
expect(isCachingHeader(initialRes.headers.get('cache-control'))).toBe(
false
)
const initialHtml = await initialRes.text()
expect(initialHtml).toMatch(/hello.*?world/)
const newRes = await fetchViaHTTP(appPort, '/something')
expect(isCachingHeader(newRes.headers.get('cache-control'))).toBe(false)
const newHtml = await newRes.text()
expect(newHtml).toMatch(/hello.*?world/)
expect(initialHtml !== newHtml).toBe(true)
const newerRes = await fetchViaHTTP(appPort, '/something')
expect(isCachingHeader(newerRes.headers.get('cache-control'))).toBe(false)
const newerHtml = await newerRes.text()
expect(newerHtml).toMatch(/hello.*?world/)
expect(newHtml !== newerHtml).toBe(true)
})
it('should error on bad object from getStaticProps', async () => {
const origContent = await fs.readFile(indexPage, 'utf8')
await fs.writeFile(
indexPage,
origContent.replace(/\/\/ bad-prop/, 'another: true,')
)
await waitFor(1000)
try {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/Additional keys were returned/)
} finally {
await fs.writeFile(indexPage, origContent)
}
})
it('should error on dynamic page without getStaticPaths', async () => {
const curPage = join(__dirname, '../pages/temp/[slug].js')
await fs.mkdirp(dirname(curPage))
await fs.writeFile(
curPage,
`
export async function getStaticProps() {
return {
props: {
hello: 'world'
}
}
}
export default () => 'oops'
`
)
await waitFor(1000)
try {
const html = await renderViaHTTP(appPort, '/temp/hello')
expect(html).toMatch(
/getStaticPaths is required for dynamic SSG pages and is missing for/
)
} finally {
await fs.remove(curPage)
}
})
it('should error on dynamic page without getStaticPaths returning fallback property', async () => {
const curPage = join(__dirname, '../pages/temp2/[slug].js')
await fs.mkdirp(dirname(curPage))
await fs.writeFile(
curPage,
`
export async function getStaticPaths() {
return {
paths: []
}
}
export async function getStaticProps() {
return {
props: {
hello: 'world'
}
}
}
export default () => 'oops'
`
)
await waitFor(1000)
try {
const html = await renderViaHTTP(appPort, '/temp2/hello')
expect(html).toMatch(/`fallback` key must be returned from/)
} finally {
await fs.remove(curPage)
}
})
it('should not re-call getStaticProps when updating query', async () => {
const browser = await webdriver(appPort, '/something?hello=world')
await waitFor(2000)
const query = await browser.elementByCss('#query').text()
expect(JSON.parse(query)).toEqual({ hello: 'world' })
const {
props: {
pageProps: { random: initialRandom },
},
} = await browser.eval('window.__NEXT_DATA__')
const curRandom = await browser.elementByCss('#random').text()
expect(curRandom).toBe(initialRandom + '')
})
it('should show fallback before invalid JSON is returned from getStaticProps', async () => {
const html = await renderViaHTTP(appPort, '/non-json/foobar')
expect(html).toContain('"isFallback":true')
})
it('should not fallback before invalid JSON is returned from getStaticProps when blocking fallback', async () => {
const html = await renderViaHTTP(appPort, '/non-json-blocking/foobar')
expect(html).toContain('"isFallback":false')
})
it('should show error for invalid JSON returned from getStaticProps on SSR', async () => {
const browser = await webdriver(appPort, '/non-json/direct')
// FIXME: enable this
// expect(await getRedboxHeader(browser)).toMatch(
// /Error serializing `.time` returned from `getStaticProps`/
// )
// FIXME: disable this
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatch(
/Failed to load static props/
)
})
it('should show error for invalid JSON returned from getStaticProps on CST', async () => {
const browser = await webdriver(appPort, '/')
await browser.elementByCss('#non-json').click()
// FIXME: enable this
// expect(await getRedboxHeader(browser)).toMatch(
// /Error serializing `.time` returned from `getStaticProps`/
// )
// FIXME: disable this
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatch(
/Failed to load static props/
)
})
it('should not contain headers already sent error', async () => {
await renderViaHTTP(appPort, '/fallback-only/some-fallback-post')
expect(stderr).not.toContain('ERR_HTTP_HEADERS_SENT')
})
} else {
if (!isEmulatedServerless) {
it('should use correct caching headers for a no-revalidate page', async () => {
const initialRes = await fetchViaHTTP(appPort, '/something')
expect(initialRes.headers.get('cache-control')).toBe(
's-maxage=31536000, stale-while-revalidate'
)
const initialHtml = await initialRes.text()
expect(initialHtml).toMatch(/hello.*?world/)
})
it('should not show error for invalid JSON returned from getStaticProps on SSR', async () => {
const browser = await webdriver(appPort, '/non-json/direct')
await check(() => getBrowserBodyText(browser), /hello /)
})
it('should not show error for invalid JSON returned from getStaticProps on CST', async () => {
const browser = await webdriver(appPort, '/')
await browser.elementByCss('#non-json').click()
await check(() => getBrowserBodyText(browser), /hello /)
})
}
it('outputs dataRoutes in routes-manifest correctly', async () => {
const { dataRoutes } = JSON.parse(
await fs.readFile(join(appDir, '.next/routes-manifest.json'), 'utf8')
)
for (const route of dataRoutes) {
route.dataRouteRegex = normalizeRegEx(route.dataRouteRegex)
}
expect(dataRoutes).toEqual([
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/index.json$`
),
page: '/',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/another.json$`
),
page: '/another',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/api\\-docs\\/(.+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/api\\-docs/(?<slug>.+?)\\.json$`,
page: '/api-docs/[...slug]',
routeKeys: {
slug: 'slug',
},
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/bad-gssp.json$`
),
page: '/bad-gssp',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/bad-ssr.json$`
),
page: '/bad-ssr',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/blocking\\-fallback\\/([^\\/]+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/blocking\\-fallback/(?<slug>[^/]+?)\\.json$`,
page: '/blocking-fallback/[slug]',
routeKeys: { slug: 'slug' },
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/blocking\\-fallback\\-once\\/([^\\/]+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/blocking\\-fallback\\-once/(?<slug>[^/]+?)\\.json$`,
page: '/blocking-fallback-once/[slug]',
routeKeys: { slug: 'slug' },
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/blocking\\-fallback\\-some\\/([^\\/]+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/blocking\\-fallback\\-some/(?<slug>[^/]+?)\\.json$`,
page: '/blocking-fallback-some/[slug]',
routeKeys: { slug: 'slug' },
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/blog.json$`
),
page: '/blog',
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/blog/(?<post>[^/]+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/blog\\/([^\\/]+?)\\.json$`
),
page: '/blog/[post]',
routeKeys: {
post: 'post',
},
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/blog/(?<post>[^/]+?)/(?<comment>[^/]+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/blog\\/([^\\/]+?)\\/([^\\/]+?)\\.json$`
),
page: '/blog/[post]/[comment]',
routeKeys: {
post: 'post',
comment: 'comment',
},
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/catchall/(?<slug>.+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/catchall\\/(.+?)\\.json$`
),
page: '/catchall/[...slug]',
routeKeys: {
slug: 'slug',
},
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/catchall\\-explicit/(?<slug>.+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/catchall\\-explicit\\/(.+?)\\.json$`
),
page: '/catchall-explicit/[...slug]',
routeKeys: {
slug: 'slug',
},
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/catchall\\-optional(?:/(?<slug>.+?))?\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/catchall\\-optional(?:\\/(.+?))?\\.json$`
),
page: '/catchall-optional/[[...slug]]',
routeKeys: {
slug: 'slug',
},
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/default-revalidate.json$`
),
page: '/default-revalidate',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/dynamic\\/([^\\/]+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/dynamic/(?<slug>[^/]+?)\\.json$`,
page: '/dynamic/[slug]',
routeKeys: {
slug: 'slug',
},
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/fallback\\-only\\/([^\\/]+?)\\.json$`
),
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/fallback\\-only/(?<slug>[^/]+?)\\.json$`,
page: '/fallback-only/[slug]',
routeKeys: {
slug: 'slug',
},
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/index\\/index.json$`
),
page: '/index',
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/lang/(?<lang>[^/]+?)/about\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/lang\\/([^\\/]+?)\\/about\\.json$`
),
page: '/lang/[lang]/about',
routeKeys: {
lang: 'lang',
},
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/non\\-json/(?<p>[^/]+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/non\\-json\\/([^\\/]+?)\\.json$`
),
page: '/non-json/[p]',
routeKeys: {
p: 'p',
},
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/non\\-json\\-blocking/(?<p>[^/]+?)\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/non\\-json\\-blocking\\/([^\\/]+?)\\.json$`
),
page: '/non-json-blocking/[p]',
routeKeys: {
p: 'p',
},
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/something.json$`
),
page: '/something',
},
{
namedDataRouteRegex: `^/_next/data/${escapeRegex(
buildId
)}/user/(?<user>[^/]+?)/profile\\.json$`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/user\\/([^\\/]+?)\\/profile\\.json$`
),
page: '/user/[user]/profile',
routeKeys: {
user: 'user',
},
},
])
})
it('outputs a prerender-manifest correctly', async () => {
const manifest = JSON.parse(
await fs.readFile(join(appDir, '.next/prerender-manifest.json'), 'utf8')
)
const escapedBuildId = escapeRegex(buildId)
Object.keys(manifest.dynamicRoutes).forEach((key) => {
const item = manifest.dynamicRoutes[key]
if (item.dataRouteRegex) {
item.dataRouteRegex = normalizeRegEx(item.dataRouteRegex)
}
if (item.routeRegex) {
item.routeRegex = normalizeRegEx(item.routeRegex)
}
})
expect(manifest.version).toBe(3)
expect(manifest.routes).toEqual(expectedManifestRoutes())
expect(manifest.dynamicRoutes).toEqual({
'/api-docs/[...slug]': {
dataRoute: `/_next/data/${buildId}/api-docs/[...slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/api\\-docs\\/(.+?)\\.json$`
),
fallback: '/api-docs/[...slug].html',
routeRegex: normalizeRegEx(`^\\/api\\-docs\\/(.+?)(?:\\/)?$`),
},
'/blocking-fallback-once/[slug]': {
dataRoute: `/_next/data/${buildId}/blocking-fallback-once/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blocking\\-fallback\\-once\\/([^\\/]+?)\\.json$`
),
fallback: null,
routeRegex: normalizeRegEx(
'^\\/blocking\\-fallback\\-once\\/([^\\/]+?)(?:\\/)?$'
),
},
'/blocking-fallback-some/[slug]': {
dataRoute: `/_next/data/${buildId}/blocking-fallback-some/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blocking\\-fallback\\-some\\/([^\\/]+?)\\.json$`
),
fallback: null,
routeRegex: normalizeRegEx(
'^\\/blocking\\-fallback\\-some\\/([^\\/]+?)(?:\\/)?$'
),
},
'/blocking-fallback/[slug]': {
dataRoute: `/_next/data/${buildId}/blocking-fallback/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blocking\\-fallback\\/([^\\/]+?)\\.json$`
),
fallback: null,
routeRegex: normalizeRegEx(
'^\\/blocking\\-fallback\\/([^\\/]+?)(?:\\/)?$'
),
},
'/blog/[post]': {
fallback: '/blog/[post].html',
dataRoute: `/_next/data/${buildId}/blog/[post].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blog\\/([^\\/]+?)\\.json$`
),
routeRegex: normalizeRegEx('^\\/blog\\/([^\\/]+?)(?:\\/)?$'),
},
'/blog/[post]/[comment]': {
fallback: '/blog/[post]/[comment].html',
dataRoute: `/_next/data/${buildId}/blog/[post]/[comment].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/blog\\/([^\\/]+?)\\/([^\\/]+?)\\.json$`
),
routeRegex: normalizeRegEx(
'^\\/blog\\/([^\\/]+?)\\/([^\\/]+?)(?:\\/)?$'
),
},
'/dynamic/[slug]': {
dataRoute: `/_next/data/${buildId}/dynamic/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/dynamic\\/([^\\/]+?)\\.json$`
),
fallback: false,
routeRegex: normalizeRegEx(`^\\/dynamic\\/([^\\/]+?)(?:\\/)?$`),
},
'/fallback-only/[slug]': {
dataRoute: `/_next/data/${buildId}/fallback-only/[slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/fallback\\-only\\/([^\\/]+?)\\.json$`
),
fallback: '/fallback-only/[slug].html',
routeRegex: normalizeRegEx(
'^\\/fallback\\-only\\/([^\\/]+?)(?:\\/)?$'
),
},
'/lang/[lang]/about': {
dataRoute: `/_next/data/${buildId}/lang/[lang]/about.json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/lang\\/([^\\/]+?)\\/about\\.json$`
),
fallback: false,
routeRegex: normalizeRegEx('^\\/lang\\/([^\\/]+?)\\/about(?:\\/)?$'),
},
'/non-json-blocking/[p]': {
dataRoute: `/_next/data/${buildId}/non-json-blocking/[p].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/non\\-json\\-blocking\\/([^\\/]+?)\\.json$`
),
fallback: null,
routeRegex: normalizeRegEx(
'^\\/non\\-json\\-blocking\\/([^\\/]+?)(?:\\/)?$'
),
},
'/non-json/[p]': {
dataRoute: `/_next/data/${buildId}/non-json/[p].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/non\\-json\\/([^\\/]+?)\\.json$`
),
fallback: '/non-json/[p].html',
routeRegex: normalizeRegEx('^\\/non\\-json\\/([^\\/]+?)(?:\\/)?$'),
},
'/user/[user]/profile': {
fallback: '/user/[user]/profile.html',
dataRoute: `/_next/data/${buildId}/user/[user]/profile.json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/user\\/([^\\/]+?)\\/profile\\.json$`
),
routeRegex: normalizeRegEx(
`^\\/user\\/([^\\/]+?)\\/profile(?:\\/)?$`
),
},
'/catchall/[...slug]': {
fallback: '/catchall/[...slug].html',
routeRegex: normalizeRegEx('^\\/catchall\\/(.+?)(?:\\/)?$'),
dataRoute: `/_next/data/${buildId}/catchall/[...slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/catchall\\/(.+?)\\.json$`
),
},
'/catchall-optional/[[...slug]]': {
dataRoute: `/_next/data/${buildId}/catchall-optional/[[...slug]].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/catchall\\-optional(?:\\/(.+?))?\\.json$`
),
fallback: false,
routeRegex: normalizeRegEx(
'^\\/catchall\\-optional(?:\\/(.+?))?(?:\\/)?$'
),
},
'/catchall-explicit/[...slug]': {
dataRoute: `/_next/data/${buildId}/catchall-explicit/[...slug].json`,
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapedBuildId}\\/catchall\\-explicit\\/(.+?)\\.json$`
),
fallback: false,
routeRegex: normalizeRegEx(
'^\\/catchall\\-explicit\\/(.+?)(?:\\/)?$'
),
},
})
})
it('outputs prerendered files correctly', async () => {
const routes = [
'/another',
'/something',
'/blog/post-1',
'/blog/post-2/comment-2',
]
for (const route of routes) {
await fs.access(join(distPagesDir, `${route}.html`), fs.constants.F_OK)
await fs.access(join(distPagesDir, `${route}.json`), fs.constants.F_OK)
}
})
if (!isEmulatedServerless) {
it('should handle de-duping correctly', async () => {
let vals = new Array(10).fill(null)
// use data route so we don't get the fallback
vals = await Promise.all(
vals.map(() =>
renderViaHTTP(appPort, `/_next/data/${buildId}/blog/post-10.json`)
)
)
const val = vals[0]
expect(JSON.parse(val).pageProps.post).toBe('post-10')
expect(new Set(vals).size).toBe(1)
})
}
it('should not revalidate when set to false', async () => {
const route = '/something'
const initialHtml = await renderViaHTTP(appPort, route)
let newHtml = await renderViaHTTP(appPort, route)
expect(initialHtml).toBe(newHtml)
newHtml = await renderViaHTTP(appPort, route)
expect(initialHtml).toBe(newHtml)
newHtml = await renderViaHTTP(appPort, route)
expect(initialHtml).toBe(newHtml)
})
if (!isEmulatedServerless) {
it('should not revalidate when set to false in blocking fallback mode', async () => {
const route = '/blocking-fallback-once/test-no-revalidate'
const initialHtml = await renderViaHTTP(appPort, route)
let newHtml = await renderViaHTTP(appPort, route)
expect(initialHtml).toBe(newHtml)
newHtml = await renderViaHTTP(appPort, route)
expect(initialHtml).toBe(newHtml)
newHtml = await renderViaHTTP(appPort, route)
expect(initialHtml).toBe(newHtml)
})
it('should handle revalidating HTML correctly', async () => {
const route = '/blog/post-2/comment-2'
await renderViaHTTP(appPort, route)
const initialHtml = await renderViaHTTP(appPort, route)
expect(initialHtml).toMatch(/Post:.*?post-2/)
expect(initialHtml).toMatch(/Comment:.*?comment-2/)
let newHtml = await renderViaHTTP(appPort, route)
expect(newHtml).toBe(initialHtml)
await waitFor(2 * 1000)
await renderViaHTTP(appPort, route)
await waitFor(2 * 1000)
newHtml = await renderViaHTTP(appPort, route)
expect(newHtml === initialHtml).toBe(false)
expect(newHtml).toMatch(/Post:.*?post-2/)
expect(newHtml).toMatch(/Comment:.*?comment-2/)
})
it('should handle revalidating JSON correctly', async () => {
const route = `/_next/data/${buildId}/blog/post-2/comment-3.json`
const initialJson = await renderViaHTTP(appPort, route)
expect(initialJson).toMatch(/post-2/)
expect(initialJson).toMatch(/comment-3/)
let newJson = await renderViaHTTP(appPort, route)
expect(newJson).toBe(initialJson)
await waitFor(2 * 1000)
await renderViaHTTP(appPort, route)
await waitFor(2 * 1000)
newJson = await renderViaHTTP(appPort, route)
expect(newJson === initialJson).toBe(false)
expect(newJson).toMatch(/post-2/)
expect(newJson).toMatch(/comment-3/)
})
it('should handle revalidating HTML correctly with blocking', async () => {
const route = '/blocking-fallback/pewpew'
const initialHtml = await renderViaHTTP(appPort, route)
expect(initialHtml).toMatch(/Post:.*?pewpew/)
let newHtml = await renderViaHTTP(appPort, route)
expect(newHtml).toBe(initialHtml)
await waitFor(2 * 1000)
await renderViaHTTP(appPort, route)
await waitFor(2 * 1000)
newHtml = await renderViaHTTP(appPort, route)
expect(newHtml === initialHtml).toBe(false)
expect(newHtml).toMatch(/Post:.*?pewpew/)
})
it('should handle revalidating JSON correctly with blocking', async () => {
const route = `/_next/data/${buildId}/blocking-fallback/pewpewdata.json`
const initialJson = await renderViaHTTP(appPort, route)
expect(initialJson).toMatch(/pewpewdata/)
let newJson = await renderViaHTTP(appPort, route)
expect(newJson).toBe(initialJson)
await waitFor(2 * 1000)
await renderViaHTTP(appPort, route)
await waitFor(2 * 1000)
newJson = await renderViaHTTP(appPort, route)
expect(newJson === initialJson).toBe(false)
expect(newJson).toMatch(/pewpewdata/)
})
it('should handle revalidating HTML correctly with blocking and seed', async () => {
const route = '/blocking-fallback/a'
const initialHtml = await renderViaHTTP(appPort, route)
const $initial = cheerio.load(initialHtml)
expect($initial('p').text()).toBe('Post: a')
let newHtml = await renderViaHTTP(appPort, route)
expect(newHtml).toBe(initialHtml)
await waitFor(2 * 1000)
await renderViaHTTP(appPort, route)
await waitFor(2 * 1000)
newHtml = await renderViaHTTP(appPort, route)
expect(newHtml === initialHtml).toBe(false)
const $new = cheerio.load(newHtml)
expect($new('p').text()).toBe('Post: a')
})
it('should handle revalidating JSON correctly with blocking and seed', async () => {
const route = `/_next/data/${buildId}/blocking-fallback/b.json`
const initialJson = await renderViaHTTP(appPort, route)
expect(JSON.parse(initialJson)).toMatchObject({
pageProps: { params: { slug: 'b' } },
})
let newJson = await renderViaHTTP(appPort, route)
expect(newJson).toBe(initialJson)
await waitFor(2 * 1000)
await renderViaHTTP(appPort, route)
await waitFor(2 * 1000)
newJson = await renderViaHTTP(appPort, route)
expect(newJson === initialJson).toBe(false)
expect(JSON.parse(newJson)).toMatchObject({
pageProps: { params: { slug: 'b' } },
})
})
}
it('should not fetch prerender data on mount', async () => {
const browser = await webdriver(appPort, '/blog/post-100')
await browser.eval('window.thisShouldStay = true')
await waitFor(2 * 1000)
const val = await browser.eval('window.thisShouldStay')
expect(val).toBe(true)
})
it('should not error when flushing cache files', async () => {
await fetchViaHTTP(appPort, '/user/user-1/profile')
await waitFor(500)
expect(stderr).not.toMatch(/Failed to update prerender files for/)
})
if (isEmulatedServerless) {
it('should fail the api function instead of rendering 500', async () => {
const res = await fetchViaHTTP(appPort, '/api/bad')
expect(res.status).toBe(500)
expect(await res.text()).toBe('FAIL_FUNCTION')
})
it('should fail the page function instead of rendering 500 (getServerSideProps)', async () => {
const res = await fetchViaHTTP(appPort, '/bad-gssp')
expect(res.status).toBe(500)
expect(await res.text()).toBe('FAIL_FUNCTION')
})
it('should fail the page function instead of rendering 500 (render)', async () => {
const res = await fetchViaHTTP(appPort, '/bad-ssr')
expect(res.status).toBe(500)
expect(await res.text()).toBe('FAIL_FUNCTION')
})
it('should call /_error GIP on 500', async () => {
stderr = ''
const res = await fetchViaHTTP(appPort, '/bad-gssp')
expect(res.status).toBe(500)
expect(await res.text()).toBe('FAIL_FUNCTION')
expect(stderr).toMatch('CUSTOM_ERROR_GIP_CALLED')
expect(stderr).not.toMatch('!!! WARNING !!!')
})
}
}
// this should come very last
it('should not have attempted sending invalid payload', async () => {
expect(stderr).not.toContain('argument entity must be string')
})
}
describe('SSG Prerender', () => {
describe('dev mode', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort, {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
onStderr: (msg) => {
stderr += msg
},
cwd: appDir,
})
buildId = 'development'
})
afterAll(async () => {
await killApp(app)
})
runTests(true)
})
describe('dev mode getStaticPaths', () => {
beforeAll(async () => {
nextConfig.write(
await fs.writeFile(
nextConfigPath,
// we set cpus to 1 so that we make sure the requests
// aren't being cached at the jest-worker level
`module.exports = { experimental: { cpus: 1 } }`
......@@ -1841,7 +226,7 @@ describe('SSG Prerender', () => {
})
})
afterAll(async () => {
nextConfig.restore()
await fs.remove(nextConfigPath)
await killApp(app)
})
......@@ -1877,261 +262,6 @@ describe('SSG Prerender', () => {
})
})
describe('serverless mode', () => {
const blogPagePath = join(appDir, 'pages/blog/[post]/index.js')
let origBlogPageContent
beforeAll(async () => {
// remove firebase import since it breaks in legacy serverless mode
origBlogPageContent = await fs.readFile(blogPagePath, 'utf8')
await fs.writeFile(
blogPagePath,
origBlogPageContent.replace(
`import 'firebase/firestore'`,
`// import 'firebase/firestore'`
)
)
nextConfig.replace('// target', `target: 'serverless',`)
await fs.remove(join(appDir, '.next'))
await nextBuild(appDir, undefined, { cwd: appDir })
stderr = ''
appPort = await findPort()
app = await nextStart(appDir, appPort, {
onStderr: (msg) => {
stderr += msg
},
cwd: appDir,
})
distPagesDir = join(appDir, '.next/serverless/pages')
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
})
afterAll(async () => {
nextConfig.restore()
await fs.writeFile(blogPagePath, origBlogPageContent)
await killApp(app)
})
it('renders data correctly', async () => {
const port = await findPort()
const server = await startServer({
BUILD_ID: buildId,
PORT: port,
})
const data = await renderViaHTTP(
port,
`/_next/data/${buildId}/index.json`
)
await killApp(server)
expect(JSON.parse(data).pageProps.world).toBe('world')
})
runTests()
it('should not show invalid error', async () => {
const brokenPage = join(appDir, 'pages/broken.js')
await fs.writeFile(
brokenPage,
`
export async function getStaticProps() {
return {
hello: 'world'
}
}
export default () => 'hello world'
`
)
await fs.remove(join(appDir, '.next'))
const { stderr } = await nextBuild(appDir, [], {
stderr: true,
cwd: appDir,
})
await fs.remove(brokenPage)
expect(stderr).toContain(
'Additional keys were returned from `getStaticProps`'
)
expect(stderr).not.toContain(
'You can not use getInitialProps with getStaticProps'
)
})
it('should show serialization error during build', async () => {
await fs.remove(join(appDir, '.next'))
const nonJsonPage = join(appDir, 'pages/non-json/[p].js')
const f = new File(nonJsonPage)
try {
f.replace('paths: []', `paths: [{ params: { p: 'testing' } }]`)
const { stderr } = await nextBuild(appDir, [], {
stderr: true,
cwd: appDir,
})
expect(stderr).toContain(
'Error serializing `.time` returned from `getStaticProps` in "/non-json/[p]".'
)
} finally {
f.restore()
}
})
})
describe('enumlated serverless mode', () => {
const cstmError = join(appDir, 'pages', '_error.js')
beforeAll(async () => {
const startServerlessEmulator = async (dir, port, buildId) => {
const scriptPath = join(dir, 'server.js')
const env = Object.assign(
{},
{ ...process.env },
{ PORT: port, BUILD_ID: buildId }
)
return initNextServerScript(scriptPath, /ready on/i, env, false, {
onStderr: (msg) => {
stderr += msg
},
cwd: appDir,
})
}
await nextConfig.replace(
'// target',
`target: 'experimental-serverless-trace',`
)
await fs.writeFile(
cstmError,
`
function Error() {
return <div />
}
Error.getInitialProps = () => {
console.error('CUSTOM_ERROR_GIP_CALLED')
return {}
}
export default Error
`
)
await fs.remove(join(appDir, '.next'))
await nextBuild(appDir, undefined, { cwd: appDir })
distPagesDir = join(appDir, '.next/serverless/pages')
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
stderr = ''
appPort = await findPort()
app = await startServerlessEmulator(appDir, appPort, buildId)
})
afterAll(async () => {
nextConfig.restore()
await fs.remove(cstmError)
await killApp(app)
})
runTests(false, true)
})
describe('production mode', () => {
let buildOutput = ''
beforeAll(async () => {
await fs.remove(join(appDir, '.next'))
const { stdout } = await nextBuild(appDir, [], {
stdout: true,
cwd: appDir,
})
buildOutput = stdout
stderr = ''
appPort = await findPort()
app = await nextStart(appDir, appPort, {
onStderr: (msg) => {
stderr += msg
},
cwd: appDir,
})
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
// TODO: Don't rely on this path
distPagesDir = join(appDir, '.next', 'server', 'pages')
})
afterAll(() => killApp(app))
it('should of formatted build output correctly', () => {
expect(buildOutput).toMatch(/○ \/normal/)
expect(buildOutput).toMatch(/● \/blog\/\[post\]/)
expect(buildOutput).toMatch(/\+2 more paths/)
})
it('should output traces', async () => {
const checks = [
{
page: '/_app',
tests: [
/webpack-runtime\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.min\.js/,
],
notTests: [/node_modules\/react\/cjs\/react\.development\.js/],
},
{
page: '/another',
tests: [
/webpack-runtime\.js/,
/chunks\/.*?\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.min\.js/,
/\/world.txt/,
],
notTests: [
/node_modules\/react\/cjs\/react\.development\.js/,
/node_modules\/@firebase\/firestore\/.*?\.js/,
/\/server\.js/,
],
},
{
page: '/blog/[post]',
tests: [
/webpack-runtime\.js/,
/chunks\/.*?\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.min\.js/,
/node_modules\/@firebase\/firestore\/.*?\.js/,
],
notTests: [
/node_modules\/react\/cjs\/react\.development\.js/,
/\/world.txt/,
],
},
]
for (const check of checks) {
const contents = await fs.readFile(
join(appDir, '.next/server/pages/', check.page + '.js.nft.json'),
'utf8'
)
const { version, files } = JSON.parse(contents)
expect(version).toBe(1)
expect(
check.tests.every((item) => files.some((file) => item.test(file)))
).toBe(true)
if (sep === '/') {
expect(
check.notTests.some((item) => files.some((file) => item.test(file)))
).toBe(false)
}
}
})
runTests()
})
describe('export mode', () => {
// disable fallback: true since this is an error during `next export`
const fallbackTruePages = [
......@@ -2157,7 +287,8 @@ describe('SSG Prerender', () => {
beforeAll(async () => {
exportDir = join(appDir, 'out')
nextConfig.write(
await fs.writeFile(
nextConfigPath,
`module.exports = {
exportTrailingSlash: true,
exportPathMap: function(defaultPathMap) {
......@@ -2206,7 +337,7 @@ describe('SSG Prerender', () => {
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
})
afterAll(async () => {
nextConfig.restore()
await fs.remove(nextConfigPath)
await stopApp(app)
for (const page of fallbackTruePages) {
......
......@@ -42,9 +42,11 @@ if (testModeFromFile === 'e2e') {
}
if (testMode === 'dev') {
;(global as any).isDev = true
;(global as any).isNextDev = true
} else if (testMode === 'deploy') {
;(global as any).isDeploy = true
;(global as any).isNextDeploy = true
} else {
;(global as any).isNextStart = true
}
if (!testMode) {
......
......@@ -165,6 +165,10 @@ export class NextInstance {
return ''
}
public get cliOutput(): string {
return ''
}
// TODO: block these in deploy mode
public async readFile(filename: string) {
return fs.readFile(path.join(this.testDir, filename), 'utf8')
......
......@@ -2,6 +2,8 @@ import { spawn } from 'child_process'
import { NextInstance } from './base'
export class NextDevInstance extends NextInstance {
private _cliOutput: string
public get buildId() {
return 'development'
}
......@@ -10,6 +12,10 @@ export class NextDevInstance extends NextInstance {
await super.createTestDir()
}
public get cliOutput() {
return this._cliOutput || ''
}
public async start() {
if (this.childProcess) {
throw new Error('next already started')
......@@ -32,11 +38,13 @@ export class NextDevInstance extends NextInstance {
this.childProcess.stdout.on('data', (chunk) => {
const msg = chunk.toString()
process.stdout.write(chunk)
this._cliOutput += msg
this.emit('stdout', [msg])
})
this.childProcess.stderr.on('data', (chunk) => {
const msg = chunk.toString()
process.stderr.write(chunk)
this._cliOutput += msg
this.emit('stderr', [msg])
})
......
......@@ -5,11 +5,16 @@ import { NextInstance } from './base'
export class NextStartInstance extends NextInstance {
private _buildId: string
private _cliOutput: string
public get buildId() {
return this._buildId
}
public get cliOutput() {
return this._cliOutput
}
public async setup() {
await super.createTestDir()
}
......@@ -33,11 +38,13 @@ export class NextStartInstance extends NextInstance {
this.childProcess.stdout.on('data', (chunk) => {
const msg = chunk.toString()
process.stdout.write(chunk)
this._cliOutput += msg
this.emit('stdout', [msg])
})
this.childProcess.stderr.on('data', (chunk) => {
const msg = chunk.toString()
process.stderr.write(chunk)
this._cliOutput += msg
this.emit('stderr', [msg])
})
}
......
......@@ -528,9 +528,8 @@ export async function retry(fn, duration = 3000, interval = 500, description) {
}
export async function hasRedbox(browser, expected = true) {
let attempts = 30
do {
const has = await evaluate(browser, () => {
for (let i = 0; i < 30; i++) {
const result = await evaluate(browser, () => {
return Boolean(
[].slice
.call(document.querySelectorAll('nextjs-portal'))
......@@ -541,15 +540,12 @@ export async function hasRedbox(browser, expected = true) {
)
)
})
if (has) {
return true
}
if (--attempts < 0) {
break
}
await new Promise((resolve) => setTimeout(resolve, 1000))
} while (expected)
if (result === expected) {
return result
}
await waitFor(1000)
}
return false
}
......
......@@ -6250,13 +6250,6 @@ bl@^4.1.0:
inherits "^2.0.4"
readable-stream "^3.4.0"
block-stream@*:
version "0.0.9"
resolved "https://registry.yarnpkg.com/block-stream/-/block-stream-0.0.9.tgz#13ebfe778a03205cfe03751481ebb4b3300c126a"
integrity sha1-E+v+d4oDIFz+A3UUgeu0szAMEmo=
dependencies:
inherits "~2.0.0"
bluebird@^3.5.0, bluebird@^3.5.5:
version "3.7.2"
resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.7.2.tgz#9f229c15be272454ffa973ace0dbee79a1b0c36f"
......@@ -9905,16 +9898,6 @@ fsevents@~2.3.1:
resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.1.tgz#b209ab14c61012636c8863507edf7fb68cc54e9f"
integrity sha512-YR47Eg4hChJGAB1O3yEAOkGO+rlzutoICGqGo9EZ4lKWokzZRSyIW1QmTzqjtw8MJdj9srP869CuWw/hyzSiBw==
fstream@^1.0.0, fstream@^1.0.12:
version "1.0.12"
resolved "https://registry.yarnpkg.com/fstream/-/fstream-1.0.12.tgz#4e8ba8ee2d48be4f7d0de505455548eae5932045"
integrity sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg==
dependencies:
graceful-fs "^4.1.2"
inherits "~2.0.0"
mkdirp ">=0.5 0"
rimraf "2"
function-bind@^1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d"
......@@ -11032,7 +11015,7 @@ inflight@^1.0.4:
once "^1.3.0"
wrappy "1"
inherits@2, inherits@2.0.4, inherits@^2.0.1, inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.0, inherits@~2.0.1, inherits@~2.0.3, inherits@~2.0.4:
inherits@2, inherits@2.0.4, inherits@^2.0.1, inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.1, inherits@~2.0.3, inherits@~2.0.4:
version "2.0.4"
resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c"
......@@ -13832,7 +13815,7 @@ mkdirp-infer-owner@^2.0.0:
infer-owner "^1.0.4"
mkdirp "^1.0.3"
"mkdirp@>=0.5 0", mkdirp@^0.5.0, mkdirp@^0.5.1, mkdirp@^0.5.3, mkdirp@~0.5.1:
mkdirp@^0.5.0, mkdirp@^0.5.1, mkdirp@^0.5.3, mkdirp@~0.5.1:
version "0.5.5"
resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def"
dependencies:
......@@ -14025,11 +14008,6 @@ no-case@^2.2.0, no-case@^2.3.2:
dependencies:
lower-case "^1.1.1"
node-addon-api@^3.0.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-3.1.0.tgz#98b21931557466c6729e51cb77cd39c965f42239"
integrity sha512-flmrDNB06LIl5lywUz7YlNGZH/5p0M7W28k8hzd9Lshtdh1wshD2Y+U4h9LD6KObOy1f+fEVdgprPrEymjM5uw==
node-dir@^0.1.17:
version "0.1.17"
resolved "https://registry.yarnpkg.com/node-dir/-/node-dir-0.1.17.tgz#5f5665d93351335caabef8f1c554516cf5f1e4e5"
......@@ -14064,24 +14042,6 @@ node-gyp-build@^4.2.2:
resolved "https://registry.yarnpkg.com/node-gyp-build/-/node-gyp-build-4.2.3.tgz#ce6277f853835f718829efb47db20f3e4d9c4739"
integrity sha512-MN6ZpzmfNCRM+3t57PTJHgHyw/h4OWnZ6mR8P5j/uZtqQr46RRuDE/P+g3n0YR/AiYXeWixZZzaip77gdICfRg==
node-gyp@3.x:
version "3.8.0"
resolved "https://registry.yarnpkg.com/node-gyp/-/node-gyp-3.8.0.tgz#540304261c330e80d0d5edce253a68cb3964218c"
integrity sha512-3g8lYefrRRzvGeSowdJKAKyks8oUpLEd/DyPV4eMhVlhJ0aNaZqIrNUIPuEWWTAoPqyFkfGrM67MC69baqn6vA==
dependencies:
fstream "^1.0.0"
glob "^7.0.3"
graceful-fs "^4.1.2"
mkdirp "^0.5.0"
nopt "2 || 3"
npmlog "0 || 1 || 2 || 3 || 4"
osenv "0"
request "^2.87.0"
rimraf "2"
semver "~5.3.0"
tar "^2.0.0"
which "1"
node-gyp@^5.0.2:
version "5.1.1"
resolved "https://registry.yarnpkg.com/node-gyp/-/node-gyp-5.1.1.tgz#eb915f7b631c937d282e33aed44cb7a025f62a3e"
......@@ -14169,22 +14129,6 @@ node-notifier@5.4.0:
shellwords "^0.1.1"
which "^1.3.0"
node-pre-gyp@^0.11.0:
version "0.11.0"
resolved "https://registry.yarnpkg.com/node-pre-gyp/-/node-pre-gyp-0.11.0.tgz#db1f33215272f692cd38f03238e3e9b47c5dd054"
integrity sha512-TwWAOZb0j7e9eGaf9esRx3ZcLaE5tQ2lvYy1pb5IAaG1a2e2Kv5Lms1Y4hpj+ciXJRofIxxlt5haeQ/2ANeE0Q==
dependencies:
detect-libc "^1.0.2"
mkdirp "^0.5.1"
needle "^2.2.1"
nopt "^4.0.1"
npm-packlist "^1.1.6"
npmlog "^4.0.2"
rc "^1.2.7"
rimraf "^2.6.1"
semver "^5.3.0"
tar "^4"
node-pre-gyp@^0.13.0:
version "0.13.0"
resolved "https://registry.yarnpkg.com/node-pre-gyp/-/node-pre-gyp-0.13.0.tgz#df9ab7b68dd6498137717838e4f92a33fc9daa42"
......@@ -14235,13 +14179,6 @@ node-version@^1.0.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/node-version/-/node-version-1.2.0.tgz#34fde3ffa8e1149bd323983479dda620e1b5060d"
"nopt@2 || 3":
version "3.0.6"
resolved "https://registry.yarnpkg.com/nopt/-/nopt-3.0.6.tgz#c6465dbf08abcd4db359317f79ac68a646b28ff9"
integrity sha1-xkZdvwirzU2zWTF/eaxopkayj/k=
dependencies:
abbrev "1"
nopt@^4.0.1:
version "4.0.3"
resolved "https://registry.yarnpkg.com/nopt/-/nopt-4.0.3.tgz#a375cad9d02fd921278d954c2254d5aa57e15e48"
......@@ -14437,7 +14374,7 @@ npm-run-path@^4.0.0, npm-run-path@^4.0.1:
dependencies:
path-key "^3.0.0"
"npmlog@0 || 1 || 2 || 3 || 4", npmlog@^4.0.0, npmlog@^4.0.2, npmlog@^4.1.2:
npmlog@^4.0.0, npmlog@^4.0.2, npmlog@^4.1.2:
version "4.1.2"
resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-4.1.2.tgz#08a7f2a8bf734604779a9efa4ad5cc717abb954b"
dependencies:
......@@ -14737,7 +14674,7 @@ os-tmpdir@^1.0.0, os-tmpdir@~1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274"
osenv@0, osenv@^0.1.4:
osenv@^0.1.4:
version "0.1.5"
resolved "https://registry.yarnpkg.com/osenv/-/osenv-0.1.5.tgz#85cdfafaeb28e8677f416e287592b5f3f49ea410"
integrity sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==
......@@ -17126,7 +17063,7 @@ request-promise-core@1.1.2:
dependencies:
lodash "^4.17.11"
request@^2.86.0, request@^2.87.0, request@^2.88.0, request@^2.88.2:
request@^2.86.0, request@^2.88.0, request@^2.88.2:
version "2.88.2"
resolved "https://registry.yarnpkg.com/request/-/request-2.88.2.tgz#d73c918731cb5a87da047e207234146f664d12b3"
integrity sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==
......@@ -17356,12 +17293,6 @@ rgba-regex@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/rgba-regex/-/rgba-regex-1.0.0.tgz#43374e2e2ca0968b0ef1523460b7d730ff22eeb3"
rimraf@2, rimraf@^2.5.4, rimraf@^2.6.1, rimraf@^2.6.3:
version "2.7.1"
resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec"
dependencies:
glob "^7.1.3"
rimraf@2.6.3, rimraf@~2.6.2:
version "2.6.3"
resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab"
......@@ -17374,6 +17305,12 @@ rimraf@3.0.0:
dependencies:
glob "^7.1.3"
rimraf@^2.5.4, rimraf@^2.6.1, rimraf@^2.6.3:
version "2.7.1"
resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec"
dependencies:
glob "^7.1.3"
rimraf@^3.0.0, rimraf@^3.0.2:
version "3.0.2"
resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-3.0.2.tgz#f1a5402ba6220ad52cc1282bac1ae3aa49fd061a"
......@@ -17668,11 +17605,6 @@ semver@^7.2.1, semver@^7.3.5:
dependencies:
lru-cache "^6.0.0"
semver@~5.3.0:
version "5.3.0"
resolved "https://registry.yarnpkg.com/semver/-/semver-5.3.0.tgz#9b2ce5d3de02d17c6012ad326aa6b4d0cf54f94f"
integrity sha1-myzl094C0XxgEq0yaqa00M9U+U8=
send@0.17.1:
version "0.17.1"
resolved "https://registry.yarnpkg.com/send/-/send-0.17.1.tgz#c1d8b059f7900f7466dd4938bdc44e11ddb376c8"
......@@ -18100,21 +18032,6 @@ sprintf-js@~1.0.2:
version "1.0.3"
resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c"
sqlite3@5.0.2:
version "5.0.2"
resolved "https://registry.yarnpkg.com/sqlite3/-/sqlite3-5.0.2.tgz#00924adcc001c17686e0a6643b6cbbc2d3965083"
integrity sha512-1SdTNo+BVU211Xj1csWa8lV6KM0CtucDwRyA0VHl91wEH1Mgh7RxUpI4rVvG7OhHrzCSGaVyW5g8vKvlrk9DJA==
dependencies:
node-addon-api "^3.0.0"
node-pre-gyp "^0.11.0"
optionalDependencies:
node-gyp "3.x"
sqlite@4.0.22:
version "4.0.22"
resolved "https://registry.yarnpkg.com/sqlite/-/sqlite-4.0.22.tgz#4a987dbcf8ccffa9a2ccc80d8a8491c62f5d19e0"
integrity sha512-i2qvk6PyZJ35cpdocdO1DF+wMU5a6eRkcn+Dmt+HpGvYJ+pKodK6tZM0DnouCf4tXt1Whs2T2smtrEyFWAauWg==
sshpk@^1.7.0:
version "1.16.1"
resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.16.1.tgz#fb661c0bef29b39db40769ee39fa70093d6f6877"
......@@ -18685,15 +18602,6 @@ tar@4.4.10:
safe-buffer "^5.1.2"
yallist "^3.0.3"
tar@^2.0.0:
version "2.2.2"
resolved "https://registry.yarnpkg.com/tar/-/tar-2.2.2.tgz#0ca8848562c7299b8b446ff6a4d60cdbb23edc40"
integrity sha512-FCEhQ/4rE1zYv9rYXJw/msRqsnmlje5jHP6huWeBZ704jUTy02c5AZyWujpMR1ax6mVw9NyJMfuK2CMDWVIfgA==
dependencies:
block-stream "*"
fstream "^1.0.12"
inherits "2"
tar@^4, tar@^4.4.12:
version "4.4.13"
resolved "https://registry.yarnpkg.com/tar/-/tar-4.4.13.tgz#43b364bc52888d555298637b10d60790254ab525"
......@@ -20154,18 +20062,18 @@ which-typed-array@^1.1.2:
has-symbols "^1.0.1"
is-typed-array "^1.1.3"
which@1, which@^1.2.12, which@^1.2.8, which@^1.2.9, which@^1.3.0, which@^1.3.1:
version "1.3.1"
resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a"
dependencies:
isexe "^2.0.0"
which@1.2.x:
version "1.2.14"
resolved "https://registry.yarnpkg.com/which/-/which-1.2.14.tgz#9a87c4378f03e827cecaf1acdf56c736c01c14e5"
dependencies:
isexe "^2.0.0"
which@^1.2.12, which@^1.2.8, which@^1.2.9, which@^1.3.0, which@^1.3.1:
version "1.3.1"
resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a"
dependencies:
isexe "^2.0.0"
which@^2.0.1, which@^2.0.2:
version "2.0.2"
resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1"
......
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