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 @@ ...@@ -132,8 +132,6 @@
"seedrandom": "3.0.5", "seedrandom": "3.0.5",
"selenium-webdriver": "4.0.0-beta.4", "selenium-webdriver": "4.0.0-beta.4",
"shell-quote": "1.7.2", "shell-quote": "1.7.2",
"sqlite": "4.0.22",
"sqlite3": "5.0.2",
"styled-jsx-plugin-postcss": "3.0.2", "styled-jsx-plugin-postcss": "3.0.2",
"tailwindcss": "1.1.3", "tailwindcss": "1.1.3",
"taskr": "1.1.0", "taskr": "1.1.0",
......
This diff is collapsed.
...@@ -136,7 +136,7 @@ describe('basePath', () => { ...@@ -136,7 +136,7 @@ describe('basePath', () => {
}) })
if (!dev) { if (!dev) {
if (!(global as any).isDeploy) { if (!(global as any).isNextDeploy) {
it('should add basePath to routes-manifest', async () => { it('should add basePath to routes-manifest', async () => {
const routesManifest = JSON.parse( const routesManifest = JSON.parse(
await next.readFile('.next/routes-manifest.json') await next.readFile('.next/routes-manifest.json')
...@@ -487,7 +487,7 @@ describe('basePath', () => { ...@@ -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 () => { it('should navigate an absolute local url with basePath', async () => {
const browser = await webdriver( const browser = await webdriver(
next.url, next.url,
...@@ -843,5 +843,5 @@ describe('basePath', () => { ...@@ -843,5 +843,5 @@ describe('basePath', () => {
} }
}) })
} }
runTests((global as any).isDev) runTests((global as any).isNextDev)
}) })
/* eslint-env jest */ import path from 'path'
import { createNext, FileRef } from 'e2e-utils'
import fs from 'fs-extra' import { NextInstance } from 'test/lib/next-modes/base'
import { join, sep } from 'path'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import {
findPort,
killApp,
launchApp,
nextBuild,
nextStart,
} from 'next-test-utils'
let app describe('prerender native module', () => {
let appPort let next: NextInstance
const appDir = join(__dirname, '..')
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 () => { 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(await browser.elementByCss('#index').text()).toBe('index page')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({ expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
index: true, index: true,
...@@ -25,7 +38,7 @@ const runTests = () => { ...@@ -25,7 +38,7 @@ const runTests = () => {
}) })
it('should render /blog/first correctly', async () => { 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(await browser.elementByCss('#blog').text()).toBe('blog page')
expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({ expect(JSON.parse(await browser.elementByCss('#props').text())).toEqual({
...@@ -39,7 +52,7 @@ const runTests = () => { ...@@ -39,7 +52,7 @@ const runTests = () => {
}) })
it('should render /blog/second correctly', async () => { 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') await browser.waitForElementByCss('#blog')
expect(await browser.elementByCss('#blog').text()).toBe('blog page') expect(await browser.elementByCss('#blog').text()).toBe('blog page')
...@@ -52,26 +65,8 @@ const runTests = () => { ...@@ -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 () => { it('should output traces', async () => {
const checks = [ const checks = [
{ {
...@@ -101,9 +96,8 @@ describe('Prerender native module', () => { ...@@ -101,9 +96,8 @@ describe('Prerender native module', () => {
] ]
for (const check of checks) { for (const check of checks) {
const contents = await fs.readFile( const contents = await next.readFile(
join(appDir, '.next/server/pages/', check.page + '.js.nft.json'), path.join('.next/server/pages/', check.page + '.js.nft.json')
'utf8'
) )
const { version, files } = JSON.parse(contents) const { version, files } = JSON.parse(contents)
expect(version).toBe(1) expect(version).toBe(1)
...@@ -112,24 +106,12 @@ describe('Prerender native module', () => { ...@@ -112,24 +106,12 @@ describe('Prerender native module', () => {
check.tests.every((item) => files.some((file) => item.test(file))) check.tests.every((item) => files.some((file) => item.test(file)))
).toBe(true) ).toBe(true)
if (sep === '/') { if (path.sep === '/') {
expect( expect(
check.notTests.some((item) => files.some((file) => item.test(file))) check.notTests.some((item) => files.some((file) => item.test(file)))
).toBe(false) ).toBe(false)
} }
} }
}) })
}
runTests()
})
describe('dev', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort, { cwd: appDir })
})
afterAll(() => killApp(app))
runTests()
})
}) })
This diff is collapsed.
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)
})
...@@ -42,9 +42,11 @@ if (testModeFromFile === 'e2e') { ...@@ -42,9 +42,11 @@ if (testModeFromFile === 'e2e') {
} }
if (testMode === 'dev') { if (testMode === 'dev') {
;(global as any).isDev = true ;(global as any).isNextDev = true
} else if (testMode === 'deploy') { } else if (testMode === 'deploy') {
;(global as any).isDeploy = true ;(global as any).isNextDeploy = true
} else {
;(global as any).isNextStart = true
} }
if (!testMode) { if (!testMode) {
......
...@@ -165,6 +165,10 @@ export class NextInstance { ...@@ -165,6 +165,10 @@ export class NextInstance {
return '' return ''
} }
public get cliOutput(): string {
return ''
}
// TODO: block these in deploy mode // TODO: block these in deploy mode
public async readFile(filename: string) { public async readFile(filename: string) {
return fs.readFile(path.join(this.testDir, filename), 'utf8') return fs.readFile(path.join(this.testDir, filename), 'utf8')
......
...@@ -2,6 +2,8 @@ import { spawn } from 'child_process' ...@@ -2,6 +2,8 @@ import { spawn } from 'child_process'
import { NextInstance } from './base' import { NextInstance } from './base'
export class NextDevInstance extends NextInstance { export class NextDevInstance extends NextInstance {
private _cliOutput: string
public get buildId() { public get buildId() {
return 'development' return 'development'
} }
...@@ -10,6 +12,10 @@ export class NextDevInstance extends NextInstance { ...@@ -10,6 +12,10 @@ export class NextDevInstance extends NextInstance {
await super.createTestDir() await super.createTestDir()
} }
public get cliOutput() {
return this._cliOutput || ''
}
public async start() { public async start() {
if (this.childProcess) { if (this.childProcess) {
throw new Error('next already started') throw new Error('next already started')
...@@ -32,11 +38,13 @@ export class NextDevInstance extends NextInstance { ...@@ -32,11 +38,13 @@ export class NextDevInstance extends NextInstance {
this.childProcess.stdout.on('data', (chunk) => { this.childProcess.stdout.on('data', (chunk) => {
const msg = chunk.toString() const msg = chunk.toString()
process.stdout.write(chunk) process.stdout.write(chunk)
this._cliOutput += msg
this.emit('stdout', [msg]) this.emit('stdout', [msg])
}) })
this.childProcess.stderr.on('data', (chunk) => { this.childProcess.stderr.on('data', (chunk) => {
const msg = chunk.toString() const msg = chunk.toString()
process.stderr.write(chunk) process.stderr.write(chunk)
this._cliOutput += msg
this.emit('stderr', [msg]) this.emit('stderr', [msg])
}) })
......
...@@ -5,11 +5,16 @@ import { NextInstance } from './base' ...@@ -5,11 +5,16 @@ import { NextInstance } from './base'
export class NextStartInstance extends NextInstance { export class NextStartInstance extends NextInstance {
private _buildId: string private _buildId: string
private _cliOutput: string
public get buildId() { public get buildId() {
return this._buildId return this._buildId
} }
public get cliOutput() {
return this._cliOutput
}
public async setup() { public async setup() {
await super.createTestDir() await super.createTestDir()
} }
...@@ -33,11 +38,13 @@ export class NextStartInstance extends NextInstance { ...@@ -33,11 +38,13 @@ export class NextStartInstance extends NextInstance {
this.childProcess.stdout.on('data', (chunk) => { this.childProcess.stdout.on('data', (chunk) => {
const msg = chunk.toString() const msg = chunk.toString()
process.stdout.write(chunk) process.stdout.write(chunk)
this._cliOutput += msg
this.emit('stdout', [msg]) this.emit('stdout', [msg])
}) })
this.childProcess.stderr.on('data', (chunk) => { this.childProcess.stderr.on('data', (chunk) => {
const msg = chunk.toString() const msg = chunk.toString()
process.stderr.write(chunk) process.stderr.write(chunk)
this._cliOutput += msg
this.emit('stderr', [msg]) this.emit('stderr', [msg])
}) })
} }
......
...@@ -528,9 +528,8 @@ export async function retry(fn, duration = 3000, interval = 500, description) { ...@@ -528,9 +528,8 @@ export async function retry(fn, duration = 3000, interval = 500, description) {
} }
export async function hasRedbox(browser, expected = true) { export async function hasRedbox(browser, expected = true) {
let attempts = 30 for (let i = 0; i < 30; i++) {
do { const result = await evaluate(browser, () => {
const has = await evaluate(browser, () => {
return Boolean( return Boolean(
[].slice [].slice
.call(document.querySelectorAll('nextjs-portal')) .call(document.querySelectorAll('nextjs-portal'))
...@@ -541,15 +540,12 @@ export async function hasRedbox(browser, expected = true) { ...@@ -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)) if (result === expected) {
} while (expected) return result
}
await waitFor(1000)
}
return false return false
} }
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment