Unverified Commit fdb3c1a4 authored by Jan Kaifer's avatar Jan Kaifer Committed by GitHub

Refactor `next export` tests (#45227)

parent d022ccb4
/* eslint-env jest */
import { join } from 'path'
import { File, runNextCommand } from 'next-test-utils'
export default function (context) {
describe('API routes export', () => {
const nextConfig = new File(join(context.appDir, 'next.config.js'))
beforeEach(() => {
nextConfig.replace('// API route', `'/data': { page: '/api/data' },`)
})
afterEach(() => {
nextConfig.restore()
})
it('Should throw if a route is matched', async () => {
const outdir = join(context.appDir, 'outApi')
const { stderr } = await runNextCommand(
['export', context.appDir, '--outdir', outdir],
{ stderr: true }
)
expect(stderr).toContain(
'https://nextjs.org/docs/messages/api-routes-static-export'
)
})
})
}
/* eslint-env jest */
import webdriver from 'next-webdriver'
import { check, getBrowserBodyText } from 'next-test-utils'
export default function (context) {
describe('Render via browser', () => {
it('should render the home page', async () => {
const browser = await webdriver(context.port, '/')
const text = await browser.elementByCss('#home-page p').text()
expect(text).toBe('This is the home page')
await browser.close()
})
it('should add trailing slash on Link', async () => {
const browser = await webdriver(context.port, '/')
const link = await browser
.elementByCss('#about-via-link')
.getAttribute('href')
expect(link.slice(-1)).toBe('/')
})
it('should not add any slash on hash Link', async () => {
const browser = await webdriver(context.port, '/hash-link')
const link = await browser.elementByCss('#hash-link').getAttribute('href')
expect(link).toMatch(/\/hash-link\/#hash$/)
})
it('should preserve hash symbol on empty hash Link', async () => {
const browser = await webdriver(context.port, '/empty-hash-link')
const link = await browser
.elementByCss('#empty-hash-link')
.getAttribute('href')
expect(link).toMatch(/\/hello\/#$/)
})
it('should preserve question mark on empty query Link', async () => {
const browser = await webdriver(context.port, '/empty-query-link')
const link = await browser
.elementByCss('#empty-query-link')
.getAttribute('href')
expect(link).toMatch(/\/hello\/\?$/)
})
it('should not add trailing slash on Link when disabled', async () => {
const browser = await webdriver(context.portNoTrailSlash, '/')
const link = await browser
.elementByCss('#about-via-link')
.getAttribute('href')
expect(link.slice(-1)).not.toBe('/')
})
it('should do navigations via Link', async () => {
const browser = await webdriver(context.port, '/')
const text = await browser
.elementByCss('#about-via-link')
.click()
.waitForElementByCss('#about-page')
.elementByCss('#about-page p')
.text()
expect(text).toBe('This is the About page foo')
await browser.close()
})
it('should do navigations via Router', async () => {
const browser = await webdriver(context.port, '/')
const text = await browser
.elementByCss('#about-via-router')
.click()
.waitForElementByCss('#about-page')
.elementByCss('#about-page p')
.text()
expect(text).toBe('This is the About page foo')
await browser.close()
})
it('should do run client side javascript', async () => {
const browser = await webdriver(context.port, '/')
const text = await browser
.elementByCss('#counter')
.click()
.waitForElementByCss('#counter-page')
.elementByCss('#counter-increase')
.click()
.elementByCss('#counter-increase')
.click()
.elementByCss('#counter-page p')
.text()
expect(text).toBe('Counter: 2')
await browser.close()
})
it('should render pages using getInitialProps', async () => {
const browser = await webdriver(context.port, '/')
const text = await browser
.elementByCss('#get-initial-props')
.click()
.waitForElementByCss('#dynamic-page')
.elementByCss('#dynamic-page p')
.text()
expect(text).toBe('cool dynamic text')
await browser.close()
})
it('should render dynamic pages with custom urls', async () => {
const browser = await webdriver(context.port, '/')
const text = await browser
.elementByCss('#dynamic-1')
.click()
.waitForElementByCss('#dynamic-page')
.elementByCss('#dynamic-page p')
.text()
expect(text).toBe('next export is nice')
await browser.close()
})
it('should support client side navigation', async () => {
const browser = await webdriver(context.port, '/')
const text = await browser
.elementByCss('#counter')
.click()
.waitForElementByCss('#counter-page')
.elementByCss('#counter-increase')
.click()
.elementByCss('#counter-increase')
.click()
.elementByCss('#counter-page p')
.text()
expect(text).toBe('Counter: 2')
// let's go back and come again to this page:
const textNow = await browser
.elementByCss('#go-back')
.click()
.waitForElementByCss('#home-page')
.elementByCss('#counter')
.click()
.waitForElementByCss('#counter-page')
.elementByCss('#counter-page p')
.text()
expect(textNow).toBe('Counter: 2')
await browser.close()
})
it('should render dynamic import components in the client', async () => {
const browser = await webdriver(context.port, '/')
await browser
.elementByCss('#dynamic-imports-link')
.click()
.waitForElementByCss('#dynamic-imports-page')
await check(
() => getBrowserBodyText(browser),
/Welcome to dynamic imports/
)
await browser.close()
})
it('should render pages with url hash correctly', async () => {
let browser
try {
browser = await webdriver(context.port, '/')
// Check for the query string content
const text = await browser
.elementByCss('#with-hash')
.click()
.waitForElementByCss('#dynamic-page')
.elementByCss('#dynamic-page p')
.text()
expect(text).toBe('Vercel is awesome')
await check(() => browser.elementByCss('#hash').text(), /cool/)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should render 404 when visiting a page that returns notFound from gsp', async () => {
let browser
try {
browser = await webdriver(context.port, '/')
const text = await browser
.elementByCss('#gsp-notfound-link')
.click()
.waitForElementByCss('pre')
.elementByCss('pre')
.text()
expect(text).toBe('Cannot GET /gsp-notfound/')
} finally {
if (browser) {
await browser.close()
}
}
})
it('should navigate even if used a button inside <Link />', async () => {
const browser = await webdriver(context.port, '/button-link')
const text = await browser
.elementByCss('button')
.click()
.waitForElementByCss('#home-page')
.elementByCss('#home-page p')
.text()
expect(text).toBe('This is the home page')
await browser.close()
})
it('should update query after mount', async () => {
const browser = await webdriver(context.port, '/query-update?hello=world')
const query = await browser.elementByCss('#query').text()
expect(JSON.parse(query)).toEqual({ hello: 'world', a: 'blue' })
await browser.close()
})
describe('pages in the nested level: level1', () => {
it('should render the home page', async () => {
const browser = await webdriver(context.port, '/')
await browser.eval(
'document.getElementById("level1-home-page").click()'
)
await check(
() => getBrowserBodyText(browser),
/This is the Level1 home page/
)
await browser.close()
})
it('should render the about page', async () => {
const browser = await webdriver(context.port, '/')
await browser.eval(
'document.getElementById("level1-about-page").click()'
)
await check(
() => getBrowserBodyText(browser),
/This is the Level1 about page/
)
await browser.close()
})
})
})
}
/* eslint-env jest */
import webdriver from 'next-webdriver'
import { renderViaHTTP, getBrowserBodyText, check } from 'next-test-utils'
import cheerio from 'cheerio'
const loadJSONInPage = (pageContent) => {
const page = cheerio.load(pageContent)
return JSON.parse(page('#__next').text())
}
export default function (context) {
describe('Render in development mode', () => {
it('should render the home page', async () => {
const browser = await webdriver(context.port, '/')
await check(() => getBrowserBodyText(browser), /This is the home page/)
await browser.close()
})
it('should render pages only existent in exportPathMap page', async () => {
const browser = await webdriver(context.port, '/dynamic/one')
const text = await browser.elementByCss('#dynamic-page p').text()
expect(text).toBe('next export is nice')
await browser.close()
})
})
describe(`ExportPathMap's query in development mode`, () => {
it('should be present in ctx.query', async () => {
const pageContent = await renderViaHTTP(context.port, '/query')
const json = loadJSONInPage(pageContent)
expect(json).toEqual({ a: 'blue' })
})
it('should replace url query params in ctx.query when conflicting', async () => {
const pageContent = await renderViaHTTP(context.port, '/query?a=red')
const json = loadJSONInPage(pageContent)
expect(json).toEqual({ a: 'blue' })
})
it('should be merged with url query params in ctx.query', async () => {
const pageContent = await renderViaHTTP(context.port, '/query?b=green')
const json = loadJSONInPage(pageContent)
expect(json).toEqual({ a: 'blue', b: 'green' })
})
})
}
/* eslint-env jest */
import { join } from 'path'
import { File, runNextCommand } from 'next-test-utils'
export default function (context) {
describe('Dynamic routes export', () => {
const nextConfig = new File(join(context.appDir, 'next.config.js'))
beforeEach(() => {
nextConfig.replace('/blog/nextjs/comment/test', '/bad/path')
})
afterEach(() => {
nextConfig.restore()
})
it('Should throw error not matched route', async () => {
const outdir = join(context.appDir, 'outDynamic')
const { stderr } = await runNextCommand(
['export', context.appDir, '--outdir', outdir],
{ stderr: true }
).catch((err) => err)
expect(stderr).toContain(
'https://nextjs.org/docs/messages/export-path-mismatch'
)
})
})
}
/* eslint-env jest */
import { join } from 'path'
import {
nextBuild,
nextExport,
startStaticServer,
launchApp,
stopApp,
killApp,
findPort,
renderViaHTTP,
File,
} from 'next-test-utils'
import ssr from './ssr'
import browser from './browser'
import dev from './dev'
import { promises } from 'fs'
import dynamic from './dynamic'
import apiRoutes from './api-routes'
const { access, mkdir, writeFile, stat } = promises
const appDir = join(__dirname, '../')
const outdir = join(appDir, 'out')
const outNoTrailSlash = join(appDir, 'outNoTrailSlash')
const context = {}
context.appDir = appDir
const devContext = {}
const nextConfig = new File(join(appDir, 'next.config.js'))
const fileExist = (path) =>
access(path)
.then(() => stat(path))
.then((stats) => (stats.isFile() ? true : false))
.catch(() => false)
describe('Static Export', () => {
it('should delete existing exported files', async () => {
const tempfile = join(outdir, 'temp.txt')
await mkdir(outdir).catch((e) => {
if (e.code !== 'EEXIST') throw e
})
await writeFile(tempfile, 'Hello there')
await nextBuild(appDir)
await nextExport(appDir, { outdir })
let doesNotExist = false
await access(tempfile).catch((e) => {
if (e.code === 'ENOENT') doesNotExist = true
})
expect(doesNotExist).toBe(true)
})
beforeAll(async () => {
await nextBuild(appDir)
await nextExport(appDir, { outdir })
nextConfig.replace(
`exportTrailingSlash: true`,
`exportTrailingSlash: false`
)
await nextBuild(appDir)
await nextExport(appDir, { outdir: outNoTrailSlash })
nextConfig.restore()
context.server = await startStaticServer(outdir)
context.port = context.server.address().port
context.serverNoTrailSlash = await startStaticServer(outNoTrailSlash)
context.portNoTrailSlash = context.serverNoTrailSlash.address().port
devContext.port = await findPort()
devContext.server = await launchApp(
join(__dirname, '../'),
devContext.port,
true
)
// pre-build all pages at the start
await Promise.all([
renderViaHTTP(devContext.port, '/'),
renderViaHTTP(devContext.port, '/dynamic/one'),
])
})
afterAll(async () => {
await Promise.all([
stopApp(context.server),
killApp(devContext.server),
stopApp(context.serverNoTrailSlash),
])
})
it('should honor exportTrailingSlash for 404 page', async () => {
expect(await fileExist(join(outdir, '404/index.html'))).toBe(true)
// we still output 404.html for backwards compat
expect(await fileExist(join(outdir, '404.html'))).toBe(true)
})
it('should handle trailing slash in getStaticPaths', async () => {
expect(await fileExist(join(outdir, 'gssp/foo/index.html'))).toBe(true)
expect(await fileExist(join(outNoTrailSlash, 'gssp/foo.html'))).toBe(true)
})
it('should only output 404.html without exportTrailingSlash', async () => {
expect(await fileExist(join(outNoTrailSlash, '404/index.html'))).toBe(false)
expect(await fileExist(join(outNoTrailSlash, '404.html'))).toBe(true)
})
it('should not duplicate /index with exportTrailingSlash', async () => {
expect(await fileExist(join(outdir, 'index/index.html'))).toBe(false)
expect(await fileExist(join(outdir, 'index.html'))).toBe(true)
})
ssr(context)
browser(context)
dev(devContext)
dynamic(context)
apiRoutes(context)
})
/* eslint-env jest */
import { renderViaHTTP } from 'next-test-utils'
import cheerio from 'cheerio'
export default function (context) {
describe('Render via SSR', () => {
it('should render the home page', async () => {
const html = await renderViaHTTP(context.port, '/')
expect(html).toMatch(/This is the home page/)
})
it('should render the about page', async () => {
const html = await renderViaHTTP(context.port, '/about')
expect(html).toMatch(/This is the About page foobar/)
})
it('should render links correctly', async () => {
const html = await renderViaHTTP(context.port, '/')
const $ = cheerio.load(html)
const dynamicLink = $('#dynamic-1').prop('href')
const filePathLink = $('#path-with-extension').prop('href')
expect(dynamicLink).toEqual('/dynamic/one/')
expect(filePathLink).toEqual('/file-name.md')
})
it('should render a page with getInitialProps', async () => {
const html = await renderViaHTTP(context.port, '/dynamic')
expect(html).toMatch(/cool dynamic text/)
})
it('should render a dynamically rendered custom url page', async () => {
const html = await renderViaHTTP(context.port, '/dynamic/one')
expect(html).toMatch(/next export is nice/)
})
it('should render pages with dynamic imports', async () => {
const html = await renderViaHTTP(context.port, '/dynamic-imports')
expect(html).toMatch(/Welcome to dynamic imports/)
})
it('should render paths with extensions', async () => {
const html = await renderViaHTTP(context.port, '/file-name.md')
expect(html).toMatch(/this file has an extension/)
})
it('should give empty object for query if there is no query', async () => {
const html = await renderViaHTTP(
context.port,
'/get-initial-props-with-no-query'
)
expect(html).toMatch(/Query is: {}/)
})
it('should render _error on 404.html even if not provided in exportPathMap', async () => {
const html = await renderViaHTTP(context.port, '/404.html')
// The default error page from the test server
// contains "404", so need to be specific here
expect(html).toMatch(/404.*page.*not.*found/i)
})
// since exportTrailingSlash is enabled we should allow this
it('should render _error on /404/index.html', async () => {
const html = await renderViaHTTP(context.port, '/404/index.html')
// The default error page from the test server
// contains "404", so need to be specific here
expect(html).toMatch(/404.*page.*not.*found/i)
})
it('Should serve static files', async () => {
const data = await renderViaHTTP(context.port, '/static/data/item.txt')
expect(data).toBe('item')
})
it('Should serve public files', async () => {
const html = await renderViaHTTP(context.port, '/about')
const data = await renderViaHTTP(context.port, '/about/data.txt')
expect(html).toMatch(/This is the About page foobar/)
expect(data).toBe('data')
})
it('Should render dynamic files with query', async () => {
const html = await renderViaHTTP(
context.port,
'/blog/nextjs/comment/test'
)
expect(html).toMatch(/Blog post nextjs comment test/)
})
})
}
......@@ -8,6 +8,8 @@ import { NextStartInstance } from './next-modes/next-start'
import { NextDeployInstance } from './next-modes/next-deploy'
import { shouldRunTurboDevTest } from './next-test-utils'
export type { NextInstance }
// increase timeout to account for yarn install time
jest.setTimeout(240 * 1000)
......
......@@ -293,8 +293,13 @@ export class NextInstance {
await this.writeInitialFiles()
}
public async export(): Promise<{ exitCode?: number; cliOutput?: string }> {
return {}
public async build(): Promise<{ exitCode?: number; cliOutput?: string }> {
throw new Error('Not implemented')
}
public async export(args?: {
outdir?: string
}): Promise<{ exitCode?: number; cliOutput?: string }> {
throw new Error('Not implemented')
}
public async setup(parentSpan: Span): Promise<void> {}
public async start(useDirArg: boolean = false): Promise<void> {}
......
......@@ -134,10 +134,42 @@ export class NextStartInstance extends NextInstance {
})
}
public async export() {
public async build() {
return new Promise((resolve) => {
const curOutput = this._cliOutput.length
const exportArgs = ['yarn', 'next', 'export']
const exportArgs = ['pnpm', 'next', 'build']
if (this.childProcess) {
throw new Error(
`can not run export while server is running, use next.stop() first`
)
}
console.log('running', exportArgs.join(' '))
this.childProcess = spawn(
exportArgs[0],
exportArgs.slice(1),
this.spawnOpts
)
this.handleStdio(this.childProcess)
this.childProcess.on('exit', (code, signal) => {
this.childProcess = undefined
resolve({
exitCode: signal || code,
cliOutput: this.cliOutput.slice(curOutput),
})
})
})
}
public async export(...[args]: Parameters<NextInstance['export']>) {
return new Promise((resolve) => {
const curOutput = this._cliOutput.length
const exportArgs = ['pnpm', 'next', 'export']
if (args?.outdir) exportArgs.push('--outdir', args.outdir)
if (this.childProcess) {
throw new Error(
......
This diff is collapsed.
const { PHASE_DEVELOPMENT_SERVER } = require('next/constants')
module.exports = (phase) => {
return {
distDir: phase === PHASE_DEVELOPMENT_SERVER ? '.next-dev' : '.next',
publicRuntimeConfig: {
foo: 'foo',
},
serverRuntimeConfig: {
bar: 'bar',
},
exportTrailingSlash: true,
trailingSlash: true,
exportPathMap: function () {
return {
'/': { page: '/' },
......
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