-
Notifications
You must be signed in to change notification settings - Fork 83
/
config.ts
273 lines (248 loc) · 7.74 KB
/
config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import type { Nuxt, NuxtConfig } from '@nuxt/schema'
import type { InlineConfig as VitestConfig } from 'vitest/node'
import { defineConfig } from 'vite'
import { setupDotenv } from 'c12'
import type { DotenvOptions } from 'c12'
import type { InlineConfig } from 'vite'
import type { DateString } from 'compatx'
import { defu } from 'defu'
import { createResolver } from '@nuxt/kit'
import { applyEnv } from './utils'
interface GetVitestConfigOptions {
nuxt: Nuxt
viteConfig: InlineConfig
}
interface LoadNuxtOptions {
dotenv?: Partial<DotenvOptions>
overrides?: Partial<NuxtConfig>
}
// https://github.com/nuxt/framework/issues/6496
async function startNuxtAndGetViteConfig(
rootDir = process.cwd(),
options: LoadNuxtOptions = {},
) {
const { loadNuxt, buildNuxt } = await import('@nuxt/kit')
const nuxt = await loadNuxt({
cwd: rootDir,
dev: false,
dotenv: defu(options.dotenv, {
cwd: rootDir,
fileName: '.env.test',
}),
defaults: {
// suppress compatibility date warning for runtime environment tests
compatibilityDate: '2024-04-03' as DateString,
},
overrides: defu(
{
appId: 'nuxt-app',
buildId: 'test',
ssr: false,
test: true,
modules: ['@nuxt/test-utils/module'],
},
options.overrides,
),
})
if (
!nuxt.options._installedModules.find(i => i?.meta?.name === '@nuxt/test-utils')
) {
throw new Error(
'Failed to load `@nuxt/test-utils/module`. You may need to add it to your nuxt.config.',
)
}
const promise = new Promise<GetVitestConfigOptions>((resolve, reject) => {
nuxt.hook('vite:configResolved', (viteConfig, { isClient }) => {
if (isClient) {
resolve({ nuxt, viteConfig })
throw new Error('_stop_')
}
})
buildNuxt(nuxt).catch((err) => {
if (!err.toString().includes('_stop_')) {
reject(err)
}
})
}).finally(() => nuxt.close())
return promise
}
const excludedPlugins = [
'nuxt:import-protection',
'nuxt:import-conditions',
'vite-plugin-checker',
]
export async function getVitestConfigFromNuxt(
options?: GetVitestConfigOptions,
loadNuxtOptions: LoadNuxtOptions = {},
): Promise<InlineConfig & { test: VitestConfig }> {
const { rootDir = process.cwd(), ..._overrides } = loadNuxtOptions.overrides || {}
if (!options) {
options = await startNuxtAndGetViteConfig(rootDir, {
dotenv: loadNuxtOptions.dotenv,
overrides: {
test: true,
..._overrides,
},
})
}
options.viteConfig.plugins = (options.viteConfig.plugins || []).filter(p => !p || !('name' in p) || !excludedPlugins.includes(p.name))
const resolvedConfig = defu(
// overrides
{
define: {
['process.env.NODE_ENV']: 'process.env.NODE_ENV',
},
test: {
dir: process.cwd(),
environmentOptions: {
nuxtRuntimeConfig: applyEnv(structuredClone(options.nuxt.options.runtimeConfig), {
prefix: 'NUXT_',
env: await setupDotenv(defu(loadNuxtOptions.dotenv, {
cwd: rootDir,
fileName: '.env.test',
})),
}),
nuxtRouteRules: defu(
{},
options.nuxt.options.routeRules,
options.nuxt.options.nitro?.routeRules,
),
},
environmentMatchGlobs: [
['**/*.nuxt.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}', 'nuxt'],
['{test,tests}/nuxt/**.*', 'nuxt'],
],
server: {
deps: {
inline: [
// vite-node defaults
/\/node_modules\/(.*\/)?(nuxt|nuxt3|nuxt-nightly)\//,
/^#/,
// additional deps
'@nuxt/test-utils',
'@nuxt/test-utils-nightly',
'@nuxt/test-utils-edge',
'vitest-environment-nuxt',
...(options.nuxt.options.build.transpile.filter(
r => typeof r === 'string' || r instanceof RegExp,
) as Array<string | RegExp>),
],
},
},
deps: {
optimizer: {
web: {
enabled: false,
},
},
},
} satisfies VitestConfig,
},
{
server: { middlewareMode: false },
plugins: [
{
name: 'disable-auto-execute',
enforce: 'pre',
transform(code, id) {
if (id.match(/nuxt(3|-nightly)?\/.*\/entry\./)) {
return code.replace(
/(?<!vueAppPromise = )entry\(\)/,
'Promise.resolve()',
)
}
},
},
],
} satisfies InlineConfig,
// resolved vite config
options.viteConfig,
// (overrideable) defaults
{
test: {
environmentOptions: {
nuxt: {
rootId: options.nuxt.options.app.rootId || undefined,
mock: {
intersectionObserver: true,
indexedDb: false,
},
},
},
} satisfies VitestConfig,
},
) as InlineConfig & { test: VitestConfig }
// TODO: fix this by separating nuxt/node vitest configs
// typescript currently checks this to determine if it can access the filesystem: https://github.com/microsoft/TypeScript/blob/d4fbc9b57d9aa7d02faac9b1e9bb7b37c687f6e9/src/compiler/core.ts#L2738-L2749
delete resolvedConfig.define!['process.browser']
// Remove built-in Nuxt logger: https://github.com/vitest-dev/vitest/issues/5211
delete resolvedConfig.customLogger
if (!Array.isArray(resolvedConfig.test.setupFiles)) {
resolvedConfig.test.setupFiles = [resolvedConfig.test.setupFiles].filter(Boolean) as string[]
}
const resolver = createResolver(import.meta.url)
resolvedConfig.test.setupFiles.unshift(resolver.resolve('./runtime/entry'))
return resolvedConfig
}
export function defineVitestConfig(config: InlineConfig & { test?: VitestConfig } = {}) {
// @ts-expect-error TODO: investigate type mismatch
return defineConfig(async () => {
// When Nuxt module calls `startVitest`, we don't need to call `getVitestConfigFromNuxt` again
if (process.env.__NUXT_VITEST_RESOLVED__) return config
const overrides = config.test?.environmentOptions?.nuxt?.overrides || {}
overrides.rootDir = config.test?.environmentOptions?.nuxt?.rootDir
if (config.test?.setupFiles && !Array.isArray(config.test.setupFiles)) {
config.test.setupFiles = [config.test.setupFiles].filter(Boolean) as string[]
}
return defu(
config,
await getVitestConfigFromNuxt(undefined, {
dotenv: config.test?.environmentOptions?.nuxt?.dotenv,
overrides: structuredClone(overrides),
}),
)
})
}
interface NuxtEnvironmentOptions {
rootDir?: string
/**
* The starting URL for your Nuxt window environment
* @default {http://localhost:3000}
*/
url?: string
/**
* You can define how environment options are read when loading the Nuxt configuration.
*/
dotenv?: Partial<DotenvOptions>
/**
* Configuration that will override the values in your `nuxt.config` file.
*/
overrides?: NuxtConfig
/**
* The id of the root div to which the app should be mounted. You should also set `app.rootId` to the same value.
* @default {nuxt-test}
*/
rootId?: string
/**
* The name of the DOM environment to use.
*
* It also needs to be installed as a dev dependency in your project.
* @default {happy-dom}
*/
domEnvironment?: 'happy-dom' | 'jsdom'
mock?: {
intersectionObserver?: boolean
indexedDb?: boolean
}
}
declare module 'vitest/node' {
interface EnvironmentOptions {
nuxt?: NuxtEnvironmentOptions
}
}
declare module 'vitest' {
// @ts-expect-error Duplicate augmentation for backwards-compatibility
interface EnvironmentOptions {
nuxt?: NuxtEnvironmentOptions
}
}