Nuxt/test/dev/basic.generate.test.js
Sébastien Chopin 917adc0618
feat: options.target and full-static export (#6159)
* feat: add options.target

* fix(lint): lint

* fix(test): update snapshots

* fix(builder): default value for target

* fix(test): fix test

* fix(test): test fixing

* fix: use this.options.target

* fix: final test

* Update packages/vue-renderer/src/renderer.js

Co-Authored-By: Alexander Lichter <manniL@gmx.net>

* feat: Add target option and update banner

* fix(lint): fix

* feat: Add warning when using serverMiddleware in static target

* chore(utils): add TARGETS and MODES as constants

* hotfix: lint

* chore(module): add filename as alias of fileName

* feat: introducing nuxt export and router/routes.json

* hotfix: Fix the linting lord

* chore(core): add comment for filename vs fileName

* fix: use targets constant

* chore: remove warning

* fix: unit testing

* wip: refactor and use TARGETS

* fix: lint

* feat: add target as alias for first arg value

* fix: generate only for SPA

* chore: explain to use nuxt static X

* fix: render SPA fallback on redirect for static target

* fix: lint issue

* fix: only target is useful for now

* wip

* wip: nuxt static export is looking good

* Update packages/generator/src/generator.js

Co-Authored-By: Devon Rueckner <indirectlylit@users.noreply.github.com>

* Update packages/cli/src/options/common.js

Co-Authored-By: Alexander Lichter <manniL@gmx.net>

* feat: add options.target

* fix(lint): lint

* fix(test): update snapshots

* fix(builder): default value for target

* fix(test): fix test

* fix(test): test fixing

* fix: use this.options.target

* fix: final test

* Update packages/vue-renderer/src/renderer.js

Co-Authored-By: Alexander Lichter <manniL@gmx.net>

* feat: Add target option and update banner

* fix(lint): fix

* feat: Add warning when using serverMiddleware in static target

* chore(utils): add TARGETS and MODES as constants

* hotfix: lint

* chore(module): add filename as alias of fileName

* feat: introducing nuxt export and router/routes.json

* hotfix: Fix the linting lord

* chore(core): add comment for filename vs fileName

* fix: use targets constant

* chore: remove warning

* fix: unit testing

* wip: refactor and use TARGETS

* fix: lint

* feat: add target as alias for first arg value

* chore: explain to use nuxt static X

* fix: render SPA fallback on redirect for static target

* fix: lint issue

* fix: only target is useful for now

* wip

* wip: nuxt static export is looking good

* Update packages/generator/src/generator.js

Co-Authored-By: Devon Rueckner <indirectlylit@users.noreply.github.com>

* Update packages/cli/src/options/common.js

Co-Authored-By: Alexander Lichter <manniL@gmx.net>

* fix: duplicate imports

* chore: don't server render if an error happens on static target

* test: update unit and add export

* lint: fix

* lint: fix

* fix: e2e test

* fix: fallback only for static target

* fix: dev test

* feat: add generate.crawler

* fix: full static is when generate.static is given

* chore: improvements

* fix: Add isFullStatic in nuxt/config.json

* feat: handle fetch for full static

* feat: router.prefetchPayloads for full static

* chore: use fetch in async-data example

* fix: add target only if given

* fix: use created to have access to props in fetchOnServer

* chore: add console.error in dev for easy debugging

* feat: payload smart pre-fetching

* fix: remove alias for target

* fix: increment payloadFetchIndex is static set to false

* chore: lint

* chore: add serve command

* chore: rename universal to server-side

* fix: handle payloadPath on SPA fallback

* fix: lint

* chore lint again

* feat: handle spa fallback

* feat: support string for exclude

* fix: fallback only if no extension or html

* chore: use JSON.stringify() for static target

* chore: lint again, dammit

* chore: fix tests and remove too early return

* fix: early return only for server target

* fix: update tests

* fix: unit tests

* chore: add ssr option

* chore: add logic for ssr option

* fix: #6682

* chore(dx): add next command to run

* fix: lint

* fix: tests

* chore: keep old behaviour for nuxt build in spa

* fix: test again, oh boy

* fix: alright this is good now

* chore: add comment for spa fallback

* chore: move routes.json to dot nuxt dir

* chore: simplify check for promise

* chore: unique lock id

* chore: refactor isFullStatic

* fix: dont set default in build context

* chore: add test for serve

* chore: update tests

* hotfix: lint tests

* chore(dx): improve message for bundling

* feat: js payload extraction with jsonp

* fix: keep serialized session script for legacy generate

* fix: call to setPagePayload from fetchPayload

* use devalue for payload chunks

* feat: add initial load state chunk

* feat: preload payload and state scripts

* fix(vue-app): don't re-render the app if trailing slash on SSG

* hotfix: remove console.log

* chore(dx): add deploy infos for nuxt export

Co-authored-by: Pooya Parsa <pyapar@gmail.com>

* chore: handle fetching payload.js for nuxt state

* chore(dx): error when using nuxt generate and static

* chore: remove static option for clarity

* chore: remove serverless target

* hotfix: lint

* hotfix: unit tests

* chore: update legacy js resource

* chore: remove query params from url in static target

* fix: use globalName and urlJoin

* chore: typo

* feat: previewMode 👀

* chore: rename to enablePreview

* fix: wait next tick to avoid error on spa

* chore: try 1 sec

* hotfix: test only for linux, wtf azure

* refactor: static assets

- generalize logic for modules need emit export static assets
- allow customization for version, dir and base
- serialization logic is only in ssr now

* feat: smart state chunk creates

* fix(client): ignore payload load error

* perf: avoide payload loading for spa initial

* perf: avoid loading failed chunks again

* chore(cli): add simple compression for nuxt serve

* test: update snapshots

* fix version snapshot

* fix(generator): set staticAssetsBase on context only for full static

* fix tests

* fix: honor shouldHashCspScriptSrc

* chore(dx): add log for client-side fallback creation

Co-authored-by: Xin Du (Clark) <clark.duxin@gmail.com>
Co-authored-by: Alexander Lichter <manniL@gmx.net>
Co-authored-by: Pooya Parsa <pooya@pi0.ir>
Co-authored-by: Devon Rueckner <indirectlylit@users.noreply.github.com>
Co-authored-by: Pooya Parsa <pyapar@gmail.com>
2020-05-07 21:08:01 +02:00

257 lines
8.4 KiB
JavaScript

import { existsSync, writeFileSync } from 'fs'
import http from 'http'
import { resolve } from 'path'
import { remove } from 'fs-extra'
import serveStatic from 'serve-static'
import finalhandler from 'finalhandler'
import { TARGETS } from '@nuxt/utils'
import { Builder, Generator, getPort, loadFixture, Nuxt, rp, listPaths, equalOrStartsWith } from '../utils'
let port
const url = route => 'http://localhost:' + port + route
const rootDir = resolve(__dirname, '..', 'fixtures/basic')
const distDir = resolve(rootDir, '.nuxt-generate')
let builder
let server = null
let generator = null
let pathsBefore
let changedFileName
describe('basic generate', () => {
beforeAll(async () => {
const config = await loadFixture('basic', {
generate: {
static: false,
dir: '.nuxt-generate'
}
})
const nuxt = new Nuxt(config)
await nuxt.ready()
pathsBefore = listPaths(nuxt.options.rootDir)
// Make sure our check for changed files is really working
changedFileName = resolve(nuxt.options.generate.dir, '..', '.nuxt-generate', '.nuxt-generate-changed')
nuxt.hook('generate:done', () => {
writeFileSync(changedFileName, '')
})
builder = new Builder(nuxt)
builder.build = jest.fn()
generator = new Generator(nuxt, builder)
await generator.generate()
const serve = serveStatic(distDir)
server = http.createServer((req, res) => {
serve(req, res, finalhandler(req, res))
})
port = await getPort()
server.listen(port)
})
test('Check builder', () => {
expect(builder.bundleBuilder.buildContext.target).toBe(TARGETS.static)
expect(builder.build).toHaveBeenCalledTimes(1)
})
test('Check ready hook called', () => {
expect(generator.nuxt.__hook_ready_called__).toBe(true)
})
test('Check changed files', () => {
// When generating Nuxt we only expect files to change
// within nuxt.options.generate.dir, but also allow other
// .nuxt dirs for when tests are runInBand
const allowChangesDir = resolve(generator.nuxt.options.generate.dir, '..', '.nuxt')
let changedFileFound = false
const paths = listPaths(generator.nuxt.options.rootDir, pathsBefore)
paths.forEach((item) => {
if (item.path === changedFileName) {
changedFileFound = true
} else {
expect(equalOrStartsWith(allowChangesDir, item.path)).toBe(true)
}
})
expect(changedFileFound).toBe(true)
})
test('Format errors', () => {
const error = generator._formatErrors([
{ type: 'handled', route: '/h1', error: 'page not found' },
{ type: 'unhandled', route: '/h2', error: { stack: 'unhandled error stack' } }
])
expect(error).toMatch(' /h1')
expect(error).toMatch(' /h2')
expect(error).toMatch('"page not found"')
expect(error).toMatch('unhandled error stack')
})
test('/stateless', async () => {
const window = await generator.nuxt.server.renderAndGetWindow(url('/stateless'))
const html = window.document.body.innerHTML
expect(html).toContain('<h1>My component!</h1>')
})
test('/store-module', async () => {
const window = await generator.nuxt.server.renderAndGetWindow(url('/store-module'))
const html = window.document.body.innerHTML
expect(html).toContain('<h1>mutated</h1>')
})
test('/css', async () => {
const window = await generator.nuxt.server.renderAndGetWindow(url('/css'))
const headHtml = window.document.head.innerHTML
expect(headHtml).toContain('.red{color:red')
const element = window.document.querySelector('.red')
expect(element).not.toBe(null)
expect(element.textContent).toContain('This is red')
expect(element.className).toBe('red')
// t.is(window.getComputedStyle(element), 'red')
})
test('/stateful', async () => {
const window = await generator.nuxt.server.renderAndGetWindow(url('/stateful'))
const html = window.document.body.innerHTML
expect(html).toContain('<div><p>The answer is 42</p></div>')
})
test('/head', async () => {
const window = await generator.nuxt.server.renderAndGetWindow(url('/head'))
const html = window.document.body.innerHTML
const metas = window.document.getElementsByTagName('meta')
expect(window.document.title).toBe('My title - Nuxt.js')
expect(metas[0].getAttribute('content')).toBe('my meta')
expect(html).toContain('<div><h1>I can haz meta tags</h1></div>')
})
test('/async-data', async () => {
const window = await generator.nuxt.server.renderAndGetWindow(url('/async-data'))
const html = window.document.body.innerHTML
expect(html).toContain('<p>Nuxt.js</p>')
})
test('/тест雨 (test non ascii route)', async () => {
const window = await generator.nuxt.server.renderAndGetWindow(url('/тест雨'))
const html = window.document.body.innerHTML
expect(html).toContain('Hello unicode')
})
test('/users/1/index.html', async () => {
const { body: html } = await rp(url('/users/1/index.html'))
expect(html).toContain('<h1>User: 1</h1>')
expect(
existsSync(resolve(distDir, 'users/1/index.html'))
).toBe(true)
expect(existsSync(resolve(distDir, 'users/1.html'))).toBe(false)
})
test('/users/2', async () => {
const { body: html } = await rp(url('/users/2'))
expect(html).toContain('<h1>User: 2</h1>')
})
test('/users/3 (payload given)', async () => {
const { body: html } = await rp(url('/users/3'))
expect(html).toContain('<h1>User: 3000</h1>')
})
test('/users/4 -> Not found', async () => {
await expect(rp(url('/users/4'))).rejects.toMatchObject({
response: {
statusCode: 404,
body: expect.stringContaining('Cannot GET /users/4')
}
})
})
test('/validate should not be server-rendered', async () => {
const { body: html } = await rp(url('/validate'))
expect(html).toContain('<div id="__nuxt"></div>')
})
test.posix('/validate -> should display a 404', async () => {
const window = await generator.nuxt.server.renderAndGetWindow(url('/validate'))
const html = window.document.body.innerHTML
expect(html).toContain('This page could not be found')
})
test('/validate?valid=true', async () => {
const window = await generator.nuxt.server.renderAndGetWindow(url('/validate?valid=true'))
const html = window.document.body.innerHTML
expect(html).toContain('I am valid</h1>')
})
test('/redirect should not be server-rendered', async () => {
const { body: html } = await rp(url('/redirect'))
expect(html).toContain('<div id="__nuxt"></div>')
})
test('/redirect -> check redirected source', async () => {
const window = await generator.nuxt.server.renderAndGetWindow(url('/redirect'))
const html = window.document.body.innerHTML
expect(html).toContain('<h1>Index page</h1>')
})
test('/users/1 not found', async () => {
await remove(resolve(distDir, 'users'))
await expect(rp(url('/users/1'))).rejects.toMatchObject({
response: {
statusCode: 404,
body: expect.stringContaining('Cannot GET /users/1')
}
})
})
test('nuxt re-generating with no subfolders', async () => {
generator.nuxt.options.generate.subFolders = false
generator.getAppRoutes = jest.fn(() => [])
await expect(generator.generate()).resolves.toBeTruthy()
})
test('/users/1.html', async () => {
const { body } = await rp(url('/users/1.html'))
expect(body).toContain('<h1>User: 1</h1>')
expect(existsSync(resolve(distDir, 'users/1.html'))).toBe(true)
expect(
existsSync(resolve(distDir, 'users/1/index.html'))
).toBe(false)
})
test('/-ignored', async () => {
await expect(rp(url('/-ignored'))).rejects.toMatchObject({
response: {
statusCode: 404,
body: expect.stringContaining('Cannot GET /-ignored')
}
})
})
test('/ignored.test', async () => {
await expect(rp(url('/ignored.test'))).rejects.toMatchObject({
response: {
statusCode: 404,
body: expect.stringContaining('Cannot GET /ignored.test')
}
})
})
test('creates /200.html as fallback', async () => {
const { body: html } = await rp(url('/200.html'))
expect(html.includes('<h1>Index page</h1>')).toBe(false)
expect(html.includes('data-server-rendered')).toBe(false)
expect(existsSync(resolve(distDir, '200.html'))).toBe(true)
expect(existsSync(resolve(distDir, '404.html'))).toBe(false)
})
// Close server and ask nuxt to stop listening to file changes
afterAll(async () => {
await server.close()
})
})