Nuxt/packages/config/test/options.test.js

334 lines
12 KiB
JavaScript
Raw Normal View History

2019-01-14 17:40:10 +00:00
import path from 'path'
import consola from 'consola'
2019-01-14 20:31:39 +00:00
import { getNuxtConfig } from '../src/options'
2019-01-14 19:47:00 +00:00
jest.mock('std-env', () => ({
isBrowser: false,
isTest: true,
isDevelopment: false,
isProduction: true,
isDebug: false,
isCI: true,
isWindows: false,
isMacOS: false,
isLinux: true
2019-01-14 19:47:00 +00:00
}))
2019-01-14 17:40:10 +00:00
2019-01-14 20:31:39 +00:00
jest.mock('@nuxt/utils', () => ({
...jest.requireActual('@nuxt/utils'),
2020-06-03 19:34:10 +00:00
getMainModule: () => ({ paths: ['/var/nuxt/node_modules'] }),
getPKG: () => ({ name: 'fake' })
2019-01-14 20:31:39 +00:00
}))
2019-01-14 17:40:10 +00:00
describe('config: options', () => {
test('should return default nuxt config', () => {
2019-01-14 19:47:00 +00:00
jest.spyOn(process, 'cwd').mockReturnValue('/var/nuxt/test')
jest.spyOn(path, 'resolve').mockImplementation((...args) => args.join('/').replace(/\\+/, '/'))
2019-05-06 13:59:37 +00:00
jest.spyOn(path, 'join').mockImplementation((...args) => args.join('/').replace(/\\+/, '/'))
2019-01-14 19:47:00 +00:00
2023-04-25 21:17:00 +00:00
const config = getNuxtConfig({
createRequire: jest.fn(),
generate: {
staticAssets: {
version: 'x'
}
}
2023-04-25 21:17:00 +00:00
})
config.buildModules = config.buildModules.filter(p => p.name !== 'patchMD4')
expect(config).toMatchSnapshot()
2019-01-14 19:47:00 +00:00
process.cwd.mockRestore()
path.resolve.mockRestore()
2019-05-06 13:59:37 +00:00
path.join.mockRestore()
2019-01-14 17:40:10 +00:00
})
test('should prevent duplicate calls with same options', () => {
const options = {}
2019-01-14 20:31:39 +00:00
const firstConfig = getNuxtConfig(options)
const secondConfig = getNuxtConfig(firstConfig)
2019-01-14 17:40:10 +00:00
expect(firstConfig).toBe(secondConfig)
expect(firstConfig.__normalized__).toBe(true)
})
test('should return default loading when loading is true', () => {
2019-01-14 20:31:39 +00:00
const { loading } = getNuxtConfig({ loading: true })
2019-01-14 17:40:10 +00:00
expect(loading).toEqual({
color: 'black',
failedColor: 'red',
height: '2px',
throttle: 200,
duration: 5000,
continuous: false,
rtl: false,
css: true
})
})
test('[Compatibility] should transform transition to pageTransition', () => {
const { pageTransition, transition } = getNuxtConfig({
transition: 'test-tran'
})
expect(pageTransition).toMatchObject({ name: 'test-tran' })
expect(transition).toBeUndefined()
})
test('should transform pageTransition/layoutTransition to name', () => {
const { pageTransition, layoutTransition } = getNuxtConfig({
pageTransition: 'test-tran',
2019-01-14 17:40:10 +00:00
layoutTransition: 'test-layout-tran'
})
expect(pageTransition).toMatchObject({ name: 'test-tran' })
2019-01-14 17:40:10 +00:00
expect(layoutTransition).toMatchObject({ name: 'test-layout-tran' })
})
test('should transform extensions to array', () => {
2019-01-14 20:31:39 +00:00
const { extensions } = getNuxtConfig({ extensions: 'ext' })
expect(extensions).toEqual(['js', 'mjs', 'ext'])
2019-01-14 17:40:10 +00:00
})
test('should support custom global name', () => {
2019-01-14 20:31:39 +00:00
const { globalName } = getNuxtConfig({ globalName: 'globalNuxt' })
2019-01-14 17:40:10 +00:00
expect(globalName).toEqual('globalnuxt')
})
test('should detect store dir', () => {
2019-01-14 20:31:39 +00:00
const { store } = getNuxtConfig({ rootDir: path.resolve(__dirname, 'fixtures') })
2019-01-14 17:40:10 +00:00
expect(store).toEqual(true)
})
test('should unset and warn when etag.hash not a function', () => {
const { render: { etag } } = getNuxtConfig({ render: { etag: { hash: true } } })
expect(etag).toMatchObject({ hash: undefined })
expect(consola.warn).not.toHaveBeenCalledWith('render.etag.hash should be a function, received boolean instead')
const { render: { etag: etagDev } } = getNuxtConfig({ dev: true, render: { etag: { hash: true } } })
expect(etagDev).toMatchObject({ hash: undefined })
expect(consola.warn).toHaveBeenCalledWith('render.etag.hash should be a function, received boolean instead')
})
2019-01-14 17:40:10 +00:00
test('should enable csp', () => {
const { render: { csp } } = getNuxtConfig({ render: { csp: { allowedSources: ['/nuxt/*'], test: true } } })
2019-01-14 17:40:10 +00:00
expect(csp).toEqual({
hashAlgorithm: 'sha256',
addMeta: false,
unsafeInlineCompatibility: false,
allowedSources: ['/nuxt/*'],
policies: undefined,
reportOnly: false,
test: true,
generateNonce: false
})
})
// TODO: Remove this test in Nuxt 3, we will stop supporting this typo (more on: https://github.com/nuxt/nuxt.js/pull/6583)
test('should enable csp with old typo property name, avoiding breaking changes', () => {
const { render: { csp } } = getNuxtConfig({ render: { csp: { allowedSources: ['/nuxt/*'], test: true, unsafeInlineCompatiblity: true } } })
expect(csp).toEqual({
hashAlgorithm: 'sha256',
addMeta: false,
unsafeInlineCompatibility: true,
allowedSources: ['/nuxt/*'],
2019-01-14 17:40:10 +00:00
policies: undefined,
reportOnly: false,
test: true,
generateNonce: false
2019-01-14 17:40:10 +00:00
})
})
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 19:08:01 +00:00
test('should fallback to server target', () => {
const { target } = getNuxtConfig({ target: 0 })
expect(target).toEqual('server')
})
test('should check unknown target', () => {
const { target } = getNuxtConfig({ target: 'test' })
expect(consola.warn).toHaveBeenCalledWith('Unknown target: test. Falling back to server')
expect(target).toEqual('server')
})
2019-01-14 17:40:10 +00:00
test('should check unknown mode', () => {
2019-01-14 20:31:39 +00:00
const { build, render } = getNuxtConfig({ mode: 'test' })
2019-01-14 17:40:10 +00:00
expect(consola.warn).toHaveBeenCalledWith('Unknown mode: test. Falling back to universal')
expect(build.ssr).toEqual(true)
expect(render.ssr).toEqual(true)
})
test('should add appear true in pageTransition when no ssr', () => {
const { pageTransition } = getNuxtConfig({ render: { ssr: false } })
expect(pageTransition.appear).toEqual(true)
})
test('should return 200.html as default generate.fallback', () => {
const { generate: { fallback } } = getNuxtConfig({})
expect(fallback).toEqual('200.html')
})
test('should return 404.html when generate.fallback is true', () => {
2019-01-14 20:31:39 +00:00
const { generate: { fallback } } = getNuxtConfig({ generate: { fallback: true } })
2019-01-14 17:40:10 +00:00
expect(fallback).toEqual('404.html')
})
test('should return fallback html when generate.fallback is string', () => {
const { generate: { fallback } } = getNuxtConfig({ generate: { fallback: 'fallback.html' } })
expect(fallback).toEqual('fallback.html')
})
test('export should alias to generate', () => {
const { generate: { fallback } } = getNuxtConfig({ export: { fallback: 'fallback.html' } })
expect(fallback).toEqual('fallback.html')
})
test('should disable parallel if extractCSS is enabled', () => {
const { build: { parallel } } = getNuxtConfig({ build: { extractCSS: true, parallel: true } })
expect(parallel).toEqual(false)
expect(consola.warn).toHaveBeenCalledWith('extractCSS cannot work with parallel build due to limited work pool in thread-loader')
})
2019-01-14 17:40:10 +00:00
describe('config: router dir', () => {
test('should transform middleware to array', () => {
2019-01-14 20:31:39 +00:00
const { router: { middleware } } = getNuxtConfig({ router: { middleware: 'midd' } })
2019-01-14 17:40:10 +00:00
expect(middleware).toEqual(['midd'])
})
test('should set _routerBaseSpecified when base is specified', () => {
2019-01-14 20:31:39 +00:00
const { _routerBaseSpecified } = getNuxtConfig({ router: { base: '/test' } })
2019-01-14 17:40:10 +00:00
expect(_routerBaseSpecified).toEqual(true)
})
})
describe('config: options dir', () => {
test('should support custom root dir', () => {
2019-01-14 20:31:39 +00:00
const { rootDir } = getNuxtConfig({
2019-01-14 17:40:10 +00:00
rootDir: 'root'
})
expect(rootDir).toEqual(path.resolve('root'))
})
test('should support custom src dir', () => {
2019-01-14 20:31:39 +00:00
const { srcDir } = getNuxtConfig({
2019-01-14 17:40:10 +00:00
rootDir: 'root',
srcDir: 'src'
})
expect(srcDir).toEqual(path.resolve('root', 'src'))
})
test('should support custom generate dir', () => {
2019-01-14 20:31:39 +00:00
const { generate: { dir } } = getNuxtConfig({
2019-01-14 17:40:10 +00:00
rootDir: 'root',
generate: { dir: 'generate' }
})
expect(dir).toEqual(path.resolve('root', 'generate'))
})
})
describe('config: options template', () => {
test('should use default appTemplatePath', () => {
2019-01-14 20:31:39 +00:00
const { appTemplatePath } = getNuxtConfig({})
2019-01-14 17:40:10 +00:00
expect(appTemplatePath).toEqual(path.resolve('.nuxt', 'views', 'app.template.html'))
})
test('should use custom appTemplatePath', () => {
2019-01-14 20:31:39 +00:00
const { appTemplatePath } = getNuxtConfig({ appTemplatePath: 'templates' })
2019-01-14 17:40:10 +00:00
expect(appTemplatePath).toEqual(path.resolve('templates'))
})
test('should use custom app.html', () => {
2019-01-14 20:31:39 +00:00
const { appTemplatePath } = getNuxtConfig({ rootDir: path.resolve(__dirname, 'fixtures') })
2019-01-14 17:40:10 +00:00
expect(appTemplatePath).toEqual(path.resolve(__dirname, 'fixtures', 'app.html'))
})
})
describe('config: options publicPath', () => {
test('should fallback to default when publicPath is falsy', () => {
2019-01-14 20:31:39 +00:00
const { build: { publicPath } } = getNuxtConfig({ build: { publicPath: false } })
2019-01-14 17:40:10 +00:00
expect(publicPath).toEqual('/_nuxt/')
})
test('should append slash in publicPath', () => {
2019-01-14 20:31:39 +00:00
const { build: { publicPath } } = getNuxtConfig({ build: { publicPath: '/nuxt_public' } })
2019-01-14 17:40:10 +00:00
expect(publicPath).toEqual('/nuxt_public/')
})
test('should ignore url publicPath in dev', () => {
2019-01-14 20:31:39 +00:00
const { build: { publicPath } } = getNuxtConfig({ dev: true, build: { publicPath: 'http://nuxt_public' } })
2019-01-14 17:40:10 +00:00
expect(publicPath).toEqual('/_nuxt/')
})
})
describe('config: options babel', () => {
test('should replace and deprecate @nuxtjs/babel-preset-app', () => {
2019-01-14 20:31:39 +00:00
const { build: { babel } } = getNuxtConfig({
2019-01-14 17:40:10 +00:00
build: { babel: { presets: ['@nuxtjs/babel-preset-app'] } }
})
expect(consola.warn).toHaveBeenCalledWith('@nuxtjs/babel-preset-app has been deprecated, please use @nuxt/babel-preset-app.')
expect(babel).toEqual({
configFile: false,
babelrc: false,
cacheDirectory: false,
presets: ['@nuxt/babel-preset-app']
2019-01-14 17:40:10 +00:00
})
})
test('should support options in babel presets', () => {
2019-01-14 20:31:39 +00:00
const { build: { babel } } = getNuxtConfig({
2019-01-14 17:40:10 +00:00
build: { babel: { presets: [['@nuxt/babel-preset-app', { test: true }]] } }
})
expect(babel).toEqual({
configFile: false,
babelrc: false,
cacheDirectory: false,
presets: [['@nuxt/babel-preset-app', { test: true }]]
2019-01-14 17:40:10 +00:00
})
})
})
describe('config: options deprecated', () => {
test('should deprecate render.gzip', () => {
2019-01-14 20:31:39 +00:00
getNuxtConfig({ render: { gzip: true } })
2019-01-14 17:40:10 +00:00
expect(consola.warn).toHaveBeenCalledWith('render.gzip is deprecated and will be removed in a future version! Please switch to render.compressor')
})
test('should deprecate build.vendor', () => {
2019-01-14 20:31:39 +00:00
getNuxtConfig({ build: { vendor: ['lodash'] } })
2019-01-14 17:40:10 +00:00
expect(consola.warn).toHaveBeenCalledWith('vendor has been deprecated due to webpack4 optimization')
})
test('should deprecate devModules', () => {
const config = getNuxtConfig({ devModules: ['foo'], buildModules: ['bar'] })
expect(consola.warn).toHaveBeenCalledWith('`devModules` has been renamed to `buildModules` and will be removed in Nuxt 3.')
expect(config.devModules).toBe(undefined)
2023-04-25 21:17:00 +00:00
expect(config.buildModules.filter(p => p.name !== 'patchMD4')).toEqual(['bar', 'foo'])
})
2019-01-14 17:40:10 +00:00
test('should deprecate build.extractCSS.allChunks', () => {
2019-01-14 20:31:39 +00:00
getNuxtConfig({ build: { extractCSS: { allChunks: true } } })
2019-01-14 17:40:10 +00:00
expect(consola.warn).toHaveBeenCalledWith('build.extractCSS.allChunks has no effect from v2.0.0. Please use build.optimization.splitChunks settings instead.')
})
test('should deprecate build.crossorigin', () => {
getNuxtConfig({ build: { crossorigin: 'use-credentials' } })
expect(consola.warn).toHaveBeenCalledWith('Using `build.crossorigin` is deprecated and will be removed in Nuxt 3. Please use `render.crossorigin` instead.')
})
2019-01-14 17:40:10 +00:00
})
})
describe('config: serverMiddleware', () => {
test('should transform serverMiddleware hash', () => {
const serverMiddleware = {
'/resource': (req, res, next) => {
}
}
const config = getNuxtConfig({ serverMiddleware })
expect(config.serverMiddleware[0].path).toBe('/resource')
expect(config.serverMiddleware[0].handler).toBe(serverMiddleware['/resource'])
})
})
describe('config: router', () => {
test('should sanitize router.base', () => {
const config = getNuxtConfig({ router: { base: '/foo' } })
expect(config.router.base).toBe('/foo/')
})
})