@ohos-ports/nuxt-test-utils 0.0.0-stage → 4.4.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/dirs.js +4 -0
  4. package/dist/browser/index.d.mts +7 -0
  5. package/dist/browser/index.mjs +12 -0
  6. package/dist/browser/pure.d.mts +2 -0
  7. package/dist/browser/pure.mjs +1 -0
  8. package/dist/config.d.mts +82 -0
  9. package/dist/config.mjs +336 -0
  10. package/dist/e2e/dev-server.d.mts +1 -0
  11. package/dist/e2e/dev-server.mjs +10 -0
  12. package/dist/e2e-BO5mj9tk.d.mts +244 -0
  13. package/dist/e2e-DzsWJ8cS.mjs +373 -0
  14. package/dist/e2e.d.mts +2 -0
  15. package/dist/e2e.mjs +3 -0
  16. package/dist/experimental.d.mts +5 -0
  17. package/dist/experimental.mjs +20 -0
  18. package/dist/interface-Dhh_nx8F.mjs +34 -0
  19. package/dist/module.d.mts +32 -0
  20. package/dist/module.mjs +987 -0
  21. package/dist/playwright.d.mts +33 -0
  22. package/dist/playwright.mjs +68 -0
  23. package/dist/pure-Ba9-jZYN.d.mts +56 -0
  24. package/dist/pure-C_CSGRkt.mjs +114 -0
  25. package/dist/runtime/browser-entry.mjs +15 -0
  26. package/dist/runtime/entry.mjs +19 -0
  27. package/dist/runtime/global-setup.mjs +15 -0
  28. package/dist/runtime/mocks/vue-devtools.mjs +11 -0
  29. package/dist/runtime/nuxt-root.mjs +17 -0
  30. package/dist/runtime/shared/environment.mjs +67 -0
  31. package/dist/runtime/shared/h3-v1.mjs +32 -0
  32. package/dist/runtime/shared/h3-v2.mjs +34 -0
  33. package/dist/runtime/shared/h3.mjs +5 -0
  34. package/dist/runtime/shared/nuxt.mjs +17 -0
  35. package/dist/runtime/shared/vue-wrapper-plugin.mjs +42 -0
  36. package/dist/runtime-utils/index.d.mts +208 -0
  37. package/dist/runtime-utils/index.mjs +276 -0
  38. package/dist/server-Vl1UKNYB.mjs +301 -0
  39. package/dist/suspended-BbyJTvUP.d.mts +45 -0
  40. package/dist/suspended-Bjq6Zao6.mjs +1 -0
  41. package/dist/suspended-UrdAzOmb.mjs +255 -0
  42. package/dist/utils-CCklE0VI.mjs +196 -0
  43. package/dist/vitest-environment.d.mts +42 -0
  44. package/dist/vitest-environment.mjs +318 -0
  45. package/dist/vitest-wrapper/cli.d.mts +1 -0
  46. package/dist/vitest-wrapper/cli.mjs +81 -0
  47. package/package.json +145 -4
@@ -0,0 +1,987 @@
1
+ import { a as resolveH3Package, i as loadKit } from "./utils-CCklE0VI.mjs";
2
+ import { i as sendMessageToCli, n as listenCliMessages, t as createVitestTestSummary } from "./interface-Dhh_nx8F.mjs";
3
+ import { hasTTY, isCI, provider } from "std-env";
4
+ import { distDir } from "#dirs";
5
+ import { x } from "tinyexec";
6
+ import { dirname, extname, join, relative, resolve } from "pathe";
7
+ import process$1 from "node:process";
8
+ import { existsSync, promises, readFileSync } from "node:fs";
9
+ import { addDevServerHandler, createResolver, defineNuxtModule, logger, resolveIgnorePatterns, resolvePath, useNuxt } from "@nuxt/kit";
10
+ import { addCustomTab, onDevToolsInitialized, refreshCustomTabs } from "@nuxt/devtools-kit";
11
+ import { walk } from "oxc-walker";
12
+ import MagicString from "magic-string";
13
+ import { createUnplugin } from "unplugin";
14
+ import { cancel, confirm, intro, isCancel, multiselect, outro, select } from "@clack/prompts";
15
+ import { colors } from "consola/utils";
16
+ import { detect, resolveCommand } from "package-manager-detector";
17
+ import { h } from "vue";
18
+ import { debounce } from "perfect-debounce";
19
+ import { fork } from "node:child_process";
20
+ // src/module/plugins/mock.ts
21
+ const PLUGIN_NAME$1 = "nuxt:vitest:mock-transform";
22
+ const HELPER_MOCK_IMPORT = "mockNuxtImport";
23
+ const HELPER_UNMOCK_IMPORT = "unmockNuxtImport";
24
+ const HELPER_MOCK_COMPONENT = "mockComponent";
25
+ const HELPER_MOCK_HOIST = "__NUXT_VITEST_MOCKS";
26
+ const HELPER_MOCK_HOIST_ORIGINAL = "__NUXT_VITEST_MOCKS_ORIGINAL";
27
+ const HELPER_MOCK_HOIST_PREVIOUS = "__NUXT_VITEST_MOCKS_PREVIOUS";
28
+ const VITEST_SOURCES = /* @__PURE__ */ new Set(["vitest", "vite-plus/test"]);
29
+ const HELPERS_NAME = [
30
+ HELPER_MOCK_IMPORT,
31
+ HELPER_UNMOCK_IMPORT,
32
+ HELPER_MOCK_COMPONENT
33
+ ];
34
+ const createMockPlugin = (ctx) => createUnplugin(() => {
35
+ return {
36
+ name: PLUGIN_NAME$1,
37
+ enforce: "post",
38
+ vite: {
39
+ transform(code, id) {
40
+ if (!HELPERS_NAME.some((n) => code.includes(n))) return;
41
+ if (id.includes("/node_modules/")) return;
42
+ let ast;
43
+ try {
44
+ ast = this.parse(code);
45
+ } catch {
46
+ return;
47
+ }
48
+ let insertionPoint = 0;
49
+ let hasViImport = false;
50
+ let vitestSource;
51
+ const s = new MagicString(code);
52
+ const mocksImport = [];
53
+ const unmocksFrom = /* @__PURE__ */ new Set();
54
+ const mocksComponent = [];
55
+ const importPathsList = /* @__PURE__ */ new Set();
56
+ walk(ast, { enter: (node, parent) => {
57
+ const removeCallExpression = (start, end = start) => s.overwrite(isExpressionStatement(parent) ? parent.start : start.start, isExpressionStatement(parent) ? parent.end : end.end, "");
58
+ const parseMockImportTarget = (importTarget, helperName) => {
59
+ const name = isLiteral(importTarget) ? importTarget.value : isIdentifier(importTarget) ? importTarget.name : void 0;
60
+ if (typeof name !== "string") return this.error(/* @__PURE__ */ new Error(`The first argument of ${helperName}() must be a string literal or mocked target`), importTarget.start);
61
+ return {
62
+ name,
63
+ importItem: ctx.imports.find((_) => name === (_.as || _.name))
64
+ };
65
+ };
66
+ if (isImportDeclaration(node)) {
67
+ if (VITEST_SOURCES.has(node.source.value) && !hasViImport) {
68
+ vitestSource ??= node.source.value;
69
+ if (node.specifiers.find((i) => isImportSpecifier(i) && i.imported.type === "Identifier" && i.imported.name === "vi" && i.local.name === "vi")) {
70
+ insertionPoint = node.end;
71
+ hasViImport = true;
72
+ }
73
+ return;
74
+ }
75
+ }
76
+ if (!isCallExpression(node)) return;
77
+ if (isIdentifier(node.callee) && node.callee.name === HELPER_MOCK_IMPORT) {
78
+ if (node.arguments.length !== 2) return this.error(/* @__PURE__ */ new Error(`${HELPER_MOCK_IMPORT}() should have exactly 2 arguments`), node.start);
79
+ const { name, importItem } = parseMockImportTarget(node.arguments[0], HELPER_MOCK_IMPORT);
80
+ if (!importItem) return this.error(`Cannot find import "${name}" to mock`);
81
+ if (isExpressionStatement(parent)) removeCallExpression(node.arguments[0], node.arguments[1]);
82
+ else s.overwrite(node.start, node.end, `globalThis.${HELPER_MOCK_HOIST}[${JSON.stringify(importItem.from)}][${JSON.stringify(importItem.name)}]`);
83
+ mocksImport.push({
84
+ name,
85
+ import: importItem,
86
+ factory: code.slice(node.arguments[1].start, node.arguments[1].end)
87
+ });
88
+ }
89
+ if (isIdentifier(node.callee) && node.callee.name === HELPER_UNMOCK_IMPORT) {
90
+ if (node.arguments.length !== 1) return this.error(/* @__PURE__ */ new Error(`${HELPER_UNMOCK_IMPORT}() should have exactly 1 argument`), node.start);
91
+ const { name, importItem } = parseMockImportTarget(node.arguments[0], HELPER_UNMOCK_IMPORT);
92
+ if (!importItem) return this.error(`Cannot find import "${name}" to unmock`);
93
+ removeCallExpression(node.arguments[0]);
94
+ unmocksFrom.add(importItem.from);
95
+ mocksImport.push({
96
+ name,
97
+ import: importItem,
98
+ factory: void 0
99
+ });
100
+ }
101
+ if (isIdentifier(node.callee) && node.callee.name === HELPER_MOCK_COMPONENT) {
102
+ if (node.arguments.length !== 2) return this.error(/* @__PURE__ */ new Error(`${HELPER_MOCK_COMPONENT}() should have exactly 2 arguments`), node.start);
103
+ const componentName = node.arguments[0];
104
+ if (!isLiteral(componentName) || typeof componentName.value !== "string") return this.error(/* @__PURE__ */ new Error(`The first argument of ${HELPER_MOCK_COMPONENT}() must be a string literal`), componentName.start);
105
+ const pathOrName = componentName.value;
106
+ const path = ctx.components.find((_) => _.pascalName === pathOrName || _.kebabName === pathOrName)?.filePath || pathOrName;
107
+ removeCallExpression(node.arguments[1]);
108
+ mocksComponent.push({
109
+ path,
110
+ factory: code.slice(node.arguments[1].start, node.arguments[1].end)
111
+ });
112
+ }
113
+ } });
114
+ if (mocksImport.length === 0 && mocksComponent.length === 0) return;
115
+ const mockLines = [];
116
+ for (const from of unmocksFrom) mockLines.push(`vi.unmock(${JSON.stringify(from)});`);
117
+ for (const [from, mocks] of mapGroupBy(mocksImport, (mock) => mock.import.from)) {
118
+ importPathsList.add(from);
119
+ const quotedFrom = JSON.stringify(from);
120
+ const mockModuleEntry = `globalThis.${HELPER_MOCK_HOIST}[${quotedFrom}]`;
121
+ mockLines.push(`vi.mock(${quotedFrom}, async (importOriginal) => {`, ` if (!${mockModuleEntry} || ${unmocksFrom.has(from)}) {`, ` const original = await importOriginal()`, ` const previous = (${mockModuleEntry} ?? {}).${HELPER_MOCK_HOIST_PREVIOUS} ?? {}`, ` ${mockModuleEntry} = { ...original, ...previous }`, ` ${mockModuleEntry}.${HELPER_MOCK_HOIST_ORIGINAL} = { ...original }`, ` ${mockModuleEntry}.${HELPER_MOCK_HOIST_PREVIOUS} = { ...previous }`, ` }`);
122
+ for (const mock of mocks) {
123
+ const quotedName = JSON.stringify(mock.import.name);
124
+ const original = `${mockModuleEntry}.${HELPER_MOCK_HOIST_ORIGINAL}[${quotedName}]`;
125
+ if (mock.factory === void 0) mockLines.push(` ${mockModuleEntry}[${quotedName}] = ${original}`, ` delete ${mockModuleEntry}.${HELPER_MOCK_HOIST_PREVIOUS}[${quotedName}]`);
126
+ else mockLines.push(` ${mockModuleEntry}[${quotedName}] = await (${mock.factory})(${original})`, ` ${mockModuleEntry}.${HELPER_MOCK_HOIST_PREVIOUS}[${quotedName}] = ${mockModuleEntry}[${quotedName}]`);
127
+ }
128
+ mockLines.push(` return ${mockModuleEntry}`);
129
+ mockLines.push(`});`);
130
+ }
131
+ if (mocksComponent.length) mockLines.push(...mocksComponent.flatMap((mock) => {
132
+ return [
133
+ `vi.mock(${JSON.stringify(mock.path)}, async () => {`,
134
+ ` const factory = (${mock.factory});`,
135
+ ` const result = typeof factory === 'function' ? await factory() : await factory`,
136
+ ` return 'default' in result ? result : { default: result }`,
137
+ "});"
138
+ ];
139
+ }));
140
+ if (!mockLines.length) return;
141
+ s.appendLeft(insertionPoint, [
142
+ ``,
143
+ `vi.hoisted(() => {`,
144
+ ` if(!globalThis.${HELPER_MOCK_HOIST}){`,
145
+ ` vi.stubGlobal(${JSON.stringify(HELPER_MOCK_HOIST)}, {})`,
146
+ ` }`,
147
+ `});`,
148
+ ``
149
+ ].join("\n"));
150
+ if (!hasViImport) s.prepend(`import {vi} from ${JSON.stringify(vitestSource ?? "vitest")};\n`);
151
+ s.appendLeft(insertionPoint, "\n" + mockLines.join("\n") + "\n");
152
+ importPathsList.forEach((p) => {
153
+ s.append(`\n import ${JSON.stringify(p)};`);
154
+ });
155
+ return {
156
+ code: s.toString(),
157
+ map: s.generateMap({ hires: true })
158
+ };
159
+ },
160
+ async configResolved(config) {
161
+ const plugins = config.plugins || [];
162
+ const vitestPlugins = plugins.filter((p) => (p.name === "vite:mocks" || p.name.startsWith("vitest:")) && (p.enforce || "order" in p && p.order) === "post");
163
+ const lastNuxt = findLastIndex(plugins, (i) => !!i?.name?.startsWith("nuxt:"));
164
+ if (lastNuxt === -1) return;
165
+ for (const plugin of vitestPlugins) {
166
+ const index = plugins.indexOf(plugin);
167
+ if (index < lastNuxt) {
168
+ plugins.splice(index, 1);
169
+ plugins.splice(lastNuxt, 0, plugin);
170
+ }
171
+ }
172
+ }
173
+ }
174
+ };
175
+ });
176
+ function findLastIndex(arr, predicate) {
177
+ for (let i = arr.length - 1; i >= 0; i--) if (predicate(arr[i])) return i;
178
+ return -1;
179
+ }
180
+ function isImportDeclaration(node) {
181
+ return node.type === "ImportDeclaration";
182
+ }
183
+ function isImportSpecifier(node) {
184
+ return node.type === "ImportSpecifier";
185
+ }
186
+ function isCallExpression(node) {
187
+ return node.type === "CallExpression";
188
+ }
189
+ function isIdentifier(node) {
190
+ return node.type === "Identifier";
191
+ }
192
+ function isLiteral(node) {
193
+ return node.type === "Literal";
194
+ }
195
+ function isExpressionStatement(node) {
196
+ return node?.type === "ExpressionStatement";
197
+ }
198
+ function mapGroupBy(items, keySelector) {
199
+ const map = /* @__PURE__ */ new Map();
200
+ for (const item of items) {
201
+ const key = keySelector(item);
202
+ if (!map.has(key)) map.set(key, []);
203
+ map.get(key).push(item);
204
+ }
205
+ return map;
206
+ }
207
+ // src/module/mock.ts
208
+ /**
209
+ * This module is a macro that transforms `mockNuxtImport()` to `vi.mock()`,
210
+ * which make it possible to mock Nuxt imports.
211
+ */
212
+ async function setupImportMocking(nuxt) {
213
+ const { addVitePlugin } = await loadKit(nuxt.options.rootDir);
214
+ const ctx = {
215
+ components: [],
216
+ imports: []
217
+ };
218
+ let importsCtx;
219
+ nuxt.hook("imports:context", async (ctx) => {
220
+ importsCtx = ctx;
221
+ });
222
+ nuxt.hook("ready", async () => {
223
+ ctx.imports = await importsCtx.getImports();
224
+ });
225
+ nuxt.hook("components:extend", (_) => {
226
+ ctx.components = _;
227
+ });
228
+ nuxt.hook("imports:sources", (presets) => {
229
+ const idx = presets.findIndex((p) => typeof p === "object" && "imports" in p && p.imports?.includes("setInterval"));
230
+ if (idx !== -1) presets.splice(idx, 1);
231
+ });
232
+ const ignorePatterns = [];
233
+ nuxt.hook("vite:configResolved", (_, { isClient }) => {
234
+ if (!isClient) return;
235
+ ignorePatterns.push(...resolveIgnorePatterns());
236
+ });
237
+ addVitePlugin({
238
+ name: "nuxt:vitest:un-ignore-for-testing",
239
+ configureVitest() {
240
+ for (const pattern of new Set(ignorePatterns)) {
241
+ if (pattern.startsWith("!")) continue;
242
+ nuxt._ignore?.add(`!${pattern}`);
243
+ }
244
+ }
245
+ });
246
+ addVitePlugin(createMockPlugin(ctx).vite());
247
+ }
248
+ // src/module/plugins/entry.ts
249
+ const PLUGIN_NAME = "nuxt:vitest:nuxt-root-stub";
250
+ const STUB_ID = "nuxt-vitest-app-entry";
251
+ const NuxtRootStubPlugin = (options) => {
252
+ const extension = extname(options.entry);
253
+ const escapedExt = extension.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
254
+ const entryPath = join(dirname(options.entry), STUB_ID + extension);
255
+ const idFilter = new RegExp(`${STUB_ID}(?:${escapedExt})?$`);
256
+ return {
257
+ name: PLUGIN_NAME,
258
+ enforce: "pre",
259
+ resolveId: {
260
+ filter: { id: idFilter },
261
+ handler() {
262
+ return entryPath;
263
+ }
264
+ },
265
+ load: {
266
+ filter: { id: idFilter },
267
+ handler() {
268
+ return readFileSync(options.entry, "utf-8").replace("#build/root-component.mjs", options.rootStubPath);
269
+ }
270
+ }
271
+ };
272
+ };
273
+ // src/module/plugins/remove-attrs.ts
274
+ const NodeTypes = {
275
+ ELEMENT: 1,
276
+ SIMPLE_EXPRESSION: 4,
277
+ ATTRIBUTE: 6,
278
+ DIRECTIVE: 7
279
+ };
280
+ const ElementTypes = { SLOT: 2 };
281
+ function removeAttrsNodeTransform(attrs) {
282
+ const attrNames = attrs.map((s) => s.toLowerCase());
283
+ return (node) => {
284
+ if (node.type !== NodeTypes.ELEMENT || node.tagType === ElementTypes.SLOT) return;
285
+ const { props } = node;
286
+ for (let i = props.length - 1; i >= 0; i--) {
287
+ const prop = props[i];
288
+ if (prop.type === NodeTypes.ATTRIBUTE && attrNames.includes(prop.name.toLowerCase()) || prop.type === NodeTypes.DIRECTIVE && prop.name === "bind" && prop.arg && prop.arg.type === NodeTypes.SIMPLE_EXPRESSION && prop.arg.isStatic && attrNames.includes(prop.arg.content.toLowerCase())) props.splice(i, 1);
289
+ }
290
+ };
291
+ }
292
+ // src/module/install-wizard.ts
293
+ function generateVitestConfig(answers) {
294
+ let config = `import { fileURLToPath } from 'node:url'
295
+ import { defineConfig } from 'vitest/config'
296
+ import { defineVitestProject } from '@nuxt/test-utils/config'`;
297
+ if (answers.browserMode) config += `
298
+ import { playwright } from '@vitest/browser-playwright'`;
299
+ config += `
300
+
301
+ export default defineConfig({\n`;
302
+ config += ` test: {
303
+ projects: [\n`;
304
+ if (answers.testingScope.includes("unit")) config += ` {
305
+ test: {
306
+ name: 'unit',
307
+ include: ['test/unit/*.{test,spec}.ts'],
308
+ environment: 'node',
309
+ },
310
+ },\n`;
311
+ config += ` await defineVitestProject({
312
+ test: {
313
+ name: 'nuxt',
314
+ include: ['test/nuxt/*.{test,spec}.ts'],
315
+ environment: 'nuxt',
316
+ environmentOptions: {
317
+ nuxt: {
318
+ rootDir: fileURLToPath(new URL('.', import.meta.url)),${answers.browserMode ? "" : `\n domEnvironment: '${answers.domEnvironment || "happy-dom"}',`}
319
+ },
320
+ },${answers.browserMode ? `\n browser: {\n enabled: true,\n provider: playwright(),\n instances: [\n { browser: 'chromium' },\n ],\n },` : ""}
321
+ },
322
+ }),\n`;
323
+ if (answers.testingScope.includes("e2e") && answers.e2eRunner === "vitest") config += ` {
324
+ test: {
325
+ name: 'e2e',
326
+ include: ['test/e2e/*.{test,spec}.ts'],
327
+ environment: 'node',
328
+ },
329
+ },\n`;
330
+ config += ` ],\n`;
331
+ if (answers.coverage) config += ` coverage: {
332
+ enabled: true,
333
+ provider: 'v8',
334
+ },\n`;
335
+ config += ` },\n`;
336
+ config += `})\n`;
337
+ return config;
338
+ }
339
+ function generatePlaywrightConfig() {
340
+ return `import { fileURLToPath } from 'node:url'
341
+ import { defineConfig, devices } from '@ohos-ports/playwright-test'
342
+ import type { ConfigOptions } from '@nuxt/test-utils/playwright'
343
+
344
+ export default defineConfig<ConfigOptions>({
345
+ testDir: './tests',
346
+ fullyParallel: true,
347
+ forbidOnly: !!process.env.CI,
348
+ retries: process.env.CI ? 2 : 0,
349
+ workers: process.env.CI ? 1 : undefined,
350
+ reporter: 'html',
351
+ use: {
352
+ trace: 'on-first-retry',
353
+ nuxt: {
354
+ rootDir: fileURLToPath(new URL('.', import.meta.url)),
355
+ },
356
+ },
357
+ projects: [
358
+ {
359
+ name: 'chromium',
360
+ use: { ...devices['Desktop Chrome'] },
361
+ },
362
+ ],
363
+ })
364
+ `;
365
+ }
366
+ function getDependencies(answers) {
367
+ const dependencies = [];
368
+ if (answers.testingScope.includes("unit") || answers.testingScope.includes("runtime")) {
369
+ dependencies.push("vitest", "@ohos-ports/vue-test-utils");
370
+ if (answers.domEnvironment) dependencies.push(answers.domEnvironment);
371
+ if (answers.browserMode) dependencies.push("@vitest/browser-playwright");
372
+ }
373
+ if (answers.e2eRunner === "playwright") dependencies.push("@ohos-ports/playwright-test", "@ohos-ports/playwright-core");
374
+ else if (answers.e2eRunner === "cucumber") dependencies.push("@cucumber/cucumber");
375
+ else if (answers.e2eRunner === "jest") dependencies.push("@jest/globals");
376
+ if (answers.coverage) dependencies.push("@vitest/coverage-v8");
377
+ return dependencies;
378
+ }
379
+ function getPackageScripts(answers) {
380
+ const scripts = {};
381
+ if (answers.testingScope.includes("unit") || answers.testingScope.includes("runtime")) {
382
+ scripts.test = "vitest";
383
+ scripts["test:watch"] = "vitest --watch";
384
+ if (answers.coverage) scripts["test:coverage"] = "vitest --coverage";
385
+ if (answers.testingScope.includes("unit")) scripts["test:unit"] = "vitest --project unit";
386
+ scripts["test:nuxt"] = "vitest --project nuxt";
387
+ if (answers.testingScope.includes("e2e") && answers.e2eRunner === "vitest") scripts["test:e2e"] = "vitest --project e2e";
388
+ }
389
+ if (answers.e2eRunner === "playwright") {
390
+ scripts["test:e2e"] = "playwright test";
391
+ scripts["test:e2e:ui"] = "playwright test --ui";
392
+ }
393
+ return scripts;
394
+ }
395
+ async function runInstallWizard(nuxt) {
396
+ if (isCI || !hasTTY || nuxt.options.test) return;
397
+ if (nuxt.options.workspaceDir && nuxt.options.workspaceDir !== nuxt.options.rootDir) {
398
+ logger.info("Monorepo detected. Skipping setup wizard.");
399
+ return;
400
+ }
401
+ const rootDir = nuxt.options.rootDir;
402
+ const hasVitestConfig = existsSync(join(rootDir, "vitest.config.ts")) || existsSync(join(rootDir, "vitest.config.js")) || existsSync(join(rootDir, "vitest.config.mts")) || existsSync(join(rootDir, "vitest.config.mjs"));
403
+ const hasPlaywrightConfig = existsSync(join(rootDir, "playwright.config.ts")) || existsSync(join(rootDir, "playwright.config.js"));
404
+ if (hasVitestConfig || hasPlaywrightConfig) {
405
+ logger.info("Test configuration already exists. Skipping setup wizard.");
406
+ return;
407
+ }
408
+ intro(colors.bold(colors.cyan("🧪 Nuxt Test Utils Setup")));
409
+ const answers = {};
410
+ const testingScope = await multiselect({
411
+ message: "What kind of tests will you need?",
412
+ options: [
413
+ {
414
+ value: "runtime",
415
+ label: "Runtime",
416
+ hint: "components or composables running in a Nuxt runtime environment"
417
+ },
418
+ {
419
+ value: "unit",
420
+ label: "Unit tests",
421
+ hint: "pure functions or build-time/Node tests"
422
+ },
423
+ {
424
+ value: "e2e",
425
+ label: "End-to-end",
426
+ hint: "full application flows in browser"
427
+ }
428
+ ],
429
+ required: true
430
+ });
431
+ if (isCancel(testingScope)) {
432
+ cancel("Setup cancelled.");
433
+ process$1.exit(0);
434
+ }
435
+ answers.testingScope = testingScope;
436
+ const needsVitest = answers.testingScope.includes("unit") || answers.testingScope.includes("runtime");
437
+ const needsE2E = answers.testingScope.includes("e2e");
438
+ if (answers.testingScope.includes("runtime")) {
439
+ const domEnvironment = await select({
440
+ message: "Which Vitest environment would you like to use for runtime tests?",
441
+ options: [
442
+ {
443
+ value: "happy-dom",
444
+ label: "happy-dom",
445
+ hint: "recommended - faster, lighter"
446
+ },
447
+ {
448
+ value: "jsdom",
449
+ label: "jsdom",
450
+ hint: "more complete browser simulation"
451
+ },
452
+ {
453
+ value: "browser",
454
+ label: "browser mode",
455
+ hint: "real browser with Playwright"
456
+ }
457
+ ],
458
+ initialValue: "happy-dom"
459
+ });
460
+ if (isCancel(domEnvironment)) {
461
+ cancel("Setup cancelled.");
462
+ process$1.exit(0);
463
+ }
464
+ if (domEnvironment === "browser") answers.browserMode = true;
465
+ else answers.domEnvironment = domEnvironment;
466
+ }
467
+ if (needsE2E) {
468
+ const e2eRunner = await select({
469
+ message: "Which end-to-end test runner would you like to use?",
470
+ options: [
471
+ {
472
+ value: "playwright",
473
+ label: "Playwright",
474
+ hint: "recommended - modern, multi-browser"
475
+ },
476
+ {
477
+ value: "vitest",
478
+ label: "Vitest",
479
+ hint: "same runner as unit tests"
480
+ },
481
+ {
482
+ value: "cucumber",
483
+ label: "Cucumber",
484
+ hint: "behavior-driven development"
485
+ },
486
+ {
487
+ value: "jest",
488
+ label: "Jest",
489
+ hint: "legacy test runner"
490
+ }
491
+ ],
492
+ initialValue: "playwright"
493
+ });
494
+ if (isCancel(e2eRunner)) {
495
+ cancel("Setup cancelled.");
496
+ process$1.exit(0);
497
+ }
498
+ answers.e2eRunner = e2eRunner;
499
+ }
500
+ if (needsVitest) {
501
+ const coverage = await confirm({
502
+ message: "Would you like to set up test coverage?",
503
+ initialValue: false
504
+ });
505
+ if (isCancel(coverage)) {
506
+ cancel("Setup cancelled.");
507
+ process$1.exit(0);
508
+ }
509
+ answers.coverage = coverage;
510
+ }
511
+ const exampleTests = await confirm({
512
+ message: "Create example test files?",
513
+ initialValue: true
514
+ });
515
+ if (isCancel(exampleTests)) {
516
+ cancel("Setup cancelled.");
517
+ process$1.exit(0);
518
+ }
519
+ answers.exampleTests = exampleTests;
520
+ await performSetup(nuxt, answers);
521
+ outro(colors.green("✨ Test setup complete!"));
522
+ }
523
+ async function performSetup(nuxt, answers) {
524
+ const rootDir = nuxt.options.rootDir;
525
+ logger.info("Installing dependencies...");
526
+ const dependencies = getDependencies(answers);
527
+ if (dependencies.length > 0) try {
528
+ await addDevDependencies(dependencies, rootDir);
529
+ } catch (error) {
530
+ logger.error("Failed to install dependencies:", error);
531
+ return;
532
+ }
533
+ if (answers.testingScope.includes("unit") || answers.testingScope.includes("runtime")) await createVitestConfig(nuxt, answers);
534
+ if (answers.e2eRunner === "playwright") await createPlaywrightConfig(nuxt);
535
+ await createTestDirectories(nuxt, answers);
536
+ if (answers.exampleTests) await createExampleTests(nuxt, answers);
537
+ await updatePackageScripts(nuxt, answers);
538
+ await updateGitignore(nuxt, answers);
539
+ }
540
+ async function addDevDependencies(packages, cwd) {
541
+ const agent = (await detect({ cwd }).catch(() => null))?.agent || "npm";
542
+ const args = ["-D", ...packages];
543
+ const { command, args: resolvedArgs } = resolveCommand(agent, "add", args, { ignoreWorkspaceRootCheck: true }) || {
544
+ command: "npm",
545
+ args: ["i", ...args]
546
+ };
547
+ if (command === "pnpm") resolvedArgs.push("--config.confirm-modules-purge=false", "--config.strict-dep-builds=false");
548
+ const result = await x(command, resolvedArgs, { nodeOptions: {
549
+ cwd,
550
+ stdio: [
551
+ "inherit",
552
+ "inherit",
553
+ "pipe"
554
+ ]
555
+ } });
556
+ if (result.exitCode !== 0) throw new Error(`\`${command} ${resolvedArgs.join(" ")}\` exited with code ${result.exitCode}${result.stderr ? `\n${result.stderr.trim()}` : ""}`);
557
+ }
558
+ async function createVitestConfig(nuxt, answers) {
559
+ const rootDir = nuxt.options.rootDir;
560
+ const configPath = join(rootDir, "vitest.config.ts");
561
+ const config = generateVitestConfig(answers);
562
+ await promises.writeFile(configPath, config, "utf-8");
563
+ logger.success(`Created ${colors.cyan(relative(process$1.cwd(), configPath))}`);
564
+ }
565
+ async function createPlaywrightConfig(nuxt) {
566
+ const rootDir = nuxt.options.rootDir;
567
+ const configPath = join(rootDir, "playwright.config.ts");
568
+ const config = generatePlaywrightConfig();
569
+ await promises.writeFile(configPath, config, "utf-8");
570
+ logger.success(`Created ${colors.cyan(relative(process$1.cwd(), configPath))}`);
571
+ }
572
+ async function createTestDirectories(nuxt, answers) {
573
+ const rootDir = nuxt.options.rootDir;
574
+ if (answers.testingScope.includes("unit")) {
575
+ const unitDir = join(rootDir, "test/unit");
576
+ await promises.mkdir(unitDir, { recursive: true });
577
+ logger.success(`Created ${colors.cyan(relative(process$1.cwd(), unitDir))}`);
578
+ }
579
+ if (answers.testingScope.includes("runtime")) {
580
+ const nuxtDir = join(rootDir, "test/nuxt");
581
+ await promises.mkdir(nuxtDir, { recursive: true });
582
+ logger.success(`Created ${colors.cyan(relative(process$1.cwd(), nuxtDir))}`);
583
+ }
584
+ if (answers.testingScope.includes("e2e")) {
585
+ const e2eDir = answers.e2eRunner === "playwright" ? join(rootDir, "tests") : join(rootDir, "test/e2e");
586
+ await promises.mkdir(e2eDir, { recursive: true });
587
+ logger.success(`Created ${colors.cyan(relative(process$1.cwd(), e2eDir))}`);
588
+ }
589
+ }
590
+ async function createExampleTests(nuxt, answers) {
591
+ const rootDir = nuxt.options.rootDir;
592
+ if (answers.testingScope.includes("unit")) {
593
+ const unitTestPath = join(rootDir, "test/unit/example.test.ts");
594
+ await promises.writeFile(unitTestPath, `import { describe, expect, it } from 'vitest'
595
+
596
+ describe('example unit test', () => {
597
+ it('should pass', () => {
598
+ expect(1 + 1).toBe(2)
599
+ })
600
+ })
601
+ `, "utf-8");
602
+ logger.success(`Created ${colors.cyan(relative(process$1.cwd(), unitTestPath))}`);
603
+ }
604
+ if (answers.testingScope.includes("runtime")) {
605
+ const componentTestPath = join(rootDir, "test/nuxt/component.test.ts");
606
+ await promises.writeFile(componentTestPath, `import { describe, expect, it } from 'vitest'
607
+ import { mountSuspended } from '@nuxt/test-utils/runtime'
608
+ import { defineComponent, h } from 'vue'
609
+
610
+ describe('component test example', () => {
611
+ it('can mount components', async () => {
612
+ const TestComponent = defineComponent({
613
+ setup() {
614
+ return () => h('div', 'Hello Nuxt!')
615
+ },
616
+ })
617
+
618
+ const component = await mountSuspended(TestComponent)
619
+
620
+ expect(component.text()).toBe('Hello Nuxt!')
621
+ })
622
+ })
623
+ `, "utf-8");
624
+ logger.success(`Created ${colors.cyan(relative(process$1.cwd(), componentTestPath))}`);
625
+ }
626
+ if (answers.testingScope.includes("e2e")) {
627
+ if (answers.e2eRunner === "playwright") {
628
+ const e2eTestPath = join(rootDir, "tests/example.spec.ts");
629
+ await promises.writeFile(e2eTestPath, `import { expect, test } from '@nuxt/test-utils/playwright'
630
+
631
+ test('example e2e test', async ({ page, goto }) => {
632
+ await goto('/', { waitUntil: 'hydration' })
633
+ await expect(page).toHaveTitle(/Nuxt/)
634
+ })
635
+ `, "utf-8");
636
+ logger.success(`Created ${colors.cyan(relative(process$1.cwd(), e2eTestPath))}`);
637
+ } else {
638
+ const e2eTestPath = join(rootDir, "test/e2e/example.test.ts");
639
+ await promises.writeFile(e2eTestPath, `import { describe, expect, it } from 'vitest'
640
+ import { $fetch, setup } from '@nuxt/test-utils/e2e'
641
+
642
+ describe('example e2e test', async () => {
643
+ await setup()
644
+
645
+ it('renders the index page', async () => {
646
+ const html = await $fetch('/')
647
+ expect(html).toContain('Nuxt')
648
+ })
649
+ })
650
+ `, "utf-8");
651
+ logger.success(`Created ${colors.cyan(relative(process$1.cwd(), e2eTestPath))}`);
652
+ }
653
+ }
654
+ }
655
+ async function updatePackageScripts(nuxt, answers) {
656
+ const rootDir = nuxt.options.rootDir;
657
+ const packageJsonPath = join(rootDir, "package.json");
658
+ const packageJson = JSON.parse(await promises.readFile(packageJsonPath, "utf-8"));
659
+ packageJson.scripts = packageJson.scripts || {};
660
+ const newScripts = getPackageScripts(answers);
661
+ Object.assign(packageJson.scripts, newScripts);
662
+ await promises.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2) + "\n", "utf-8");
663
+ logger.success("Updated package.json scripts");
664
+ }
665
+ async function updateGitignore(nuxt, answers) {
666
+ const rootDir = nuxt.options.rootDir;
667
+ const gitignorePath = join(rootDir, ".gitignore");
668
+ let gitignore = "";
669
+ if (existsSync(gitignorePath)) gitignore = await promises.readFile(gitignorePath, "utf-8");
670
+ const lines = [];
671
+ if (answers.coverage && !gitignore.includes("coverage")) lines.push("# Test coverage", "coverage/", "");
672
+ if (answers.e2eRunner === "playwright") {
673
+ if (!gitignore.includes("playwright-report")) lines.push("# Playwright", "playwright-report/", "test-results/", "");
674
+ }
675
+ if (lines.length > 0) {
676
+ gitignore += "\n" + lines.join("\n");
677
+ await promises.writeFile(gitignorePath, gitignore, "utf-8");
678
+ logger.success("Updated .gitignore");
679
+ }
680
+ }
681
+ // src/devtools.ts
682
+ async function setupDevTools(vitestWrapper, nuxt = useNuxt()) {
683
+ const iframeSrc = "/__test_utils_vitest__/";
684
+ const updateTabs = debounce(() => {
685
+ refreshCustomTabs(nuxt);
686
+ }, 100);
687
+ addCustomTab(() => createVitestCustomTab(vitestWrapper, { iframeSrc }), nuxt);
688
+ addDevServerHandler({
689
+ route: iframeSrc,
690
+ handler: Object.assign(() => iframeContentHtml(vitestWrapper.uiUrl), { __is_handler__: true })
691
+ });
692
+ vitestWrapper.ons({
693
+ started() {
694
+ updateTabs();
695
+ },
696
+ updated() {
697
+ updateTabs();
698
+ },
699
+ finished() {
700
+ updateTabs();
701
+ },
702
+ exited() {
703
+ updateTabs();
704
+ }
705
+ });
706
+ }
707
+ function createVitestCustomTab(vitest, { iframeSrc }) {
708
+ const launchView = {
709
+ type: "launch",
710
+ description: "Start tests along with Nuxt",
711
+ actions: [{
712
+ get label() {
713
+ switch (vitest.status) {
714
+ case "starting": return "Starting...";
715
+ case "running": return "Running Vitest";
716
+ case "stopped": return "Start Vitest";
717
+ case "finished": return "Start Vitest";
718
+ }
719
+ },
720
+ get pending() {
721
+ return vitest.status === "starting" || vitest.status === "running";
722
+ },
723
+ handle: () => {
724
+ vitest.start();
725
+ }
726
+ }]
727
+ };
728
+ const uiView = {
729
+ type: "iframe",
730
+ persistent: false,
731
+ src: iframeSrc
732
+ };
733
+ return {
734
+ title: "Vitest",
735
+ name: "vitest",
736
+ icon: "logos-vitest",
737
+ get view() {
738
+ if (vitest.status === "stopped" || vitest.status === "starting" || !vitest.uiUrl) return launchView;
739
+ else return uiView;
740
+ },
741
+ extraTabVNode: vitest.testSummary.totalCount ? h("div", { style: { color: vitest.testSummary.failedCount ? "orange" : "green" } }, [
742
+ h("span", {}, vitest.testSummary.passedCount),
743
+ h("span", { style: {
744
+ opacity: "0.5",
745
+ fontSize: "0.9em"
746
+ } }, "/"),
747
+ h("span", { style: {
748
+ opacity: "0.8",
749
+ fontSize: "0.9em"
750
+ } }, vitest.testSummary.totalCount)
751
+ ]) : void 0
752
+ };
753
+ }
754
+ function iframeContentHtml(uiUrl) {
755
+ return [
756
+ "<html><head><script>",
757
+ `(${function redirect(uiUrl, provider) {
758
+ if (typeof window === "undefined") return;
759
+ if (!uiUrl) return;
760
+ if (provider === "stackblitz") {
761
+ const url = new URL(window.location.href);
762
+ const newUrl = new URL(uiUrl);
763
+ newUrl.host = url.host.replace(/--\d+--/, `--${newUrl.port}--`);
764
+ newUrl.protocol = url.protocol;
765
+ newUrl.port = url.port;
766
+ uiUrl = newUrl.toString();
767
+ }
768
+ window.location.replace(uiUrl);
769
+ }})(${JSON.stringify(uiUrl)}, ${JSON.stringify(provider)})`,
770
+ "<\/script></head></html>"
771
+ ].join("\n");
772
+ }
773
+ // src/vitest-wrapper/host.ts
774
+ function vitestWrapper(options) {
775
+ const { cwd, ...startOptions } = options;
776
+ let _status = "stopped";
777
+ let _uiUrl;
778
+ let _process;
779
+ let _testSummary = createVitestTestSummary();
780
+ const _handlers = {
781
+ started: [({ uiUrl }) => {
782
+ _uiUrl = uiUrl;
783
+ _status = "running";
784
+ _testSummary = createVitestTestSummary();
785
+ }],
786
+ updated: [(summary) => {
787
+ _testSummary = summary;
788
+ }],
789
+ finished: [(summary) => {
790
+ _status = "finished";
791
+ _testSummary = summary;
792
+ }],
793
+ exited: [clear]
794
+ };
795
+ function clear() {
796
+ _status = "stopped";
797
+ _uiUrl = void 0;
798
+ _process = void 0;
799
+ _testSummary = createVitestTestSummary();
800
+ }
801
+ function on(name, handler) {
802
+ _handlers[name] ??= [];
803
+ _handlers[name]?.push(handler);
804
+ }
805
+ function ons(handlers) {
806
+ for (const [name, handler] of Object.entries(handlers)) if (typeof handler === "function") on(name, handler);
807
+ }
808
+ async function stop() {
809
+ const vitest = _process;
810
+ if (!vitest || vitest.exitCode !== null) return;
811
+ return new Promise((resolve) => {
812
+ vitest.once("exit", () => resolve());
813
+ sendMessageToCli(vitest, "stop", { force: true });
814
+ });
815
+ }
816
+ async function start() {
817
+ if (_process) return false;
818
+ const vitest = fork(resolve(distDir, "./vitest-wrapper/cli.mjs"), {
819
+ cwd,
820
+ env: {
821
+ ...process.env,
822
+ NODE_ENV: "test",
823
+ MODE: "test"
824
+ },
825
+ stdio: startOptions.logToConsole ? void 0 : [
826
+ "ignore",
827
+ "ignore",
828
+ "inherit",
829
+ "ipc"
830
+ ]
831
+ });
832
+ _status = "starting";
833
+ _process = vitest;
834
+ vitest.once("exit", () => {
835
+ _handlers.exited.forEach((fn) => fn({ exitCode: vitest.exitCode ?? 0 }));
836
+ });
837
+ listenCliMessages(vitest, ({ type, payload }) => {
838
+ _handlers[type].forEach((fn) => fn(payload));
839
+ });
840
+ sendMessageToCli(vitest, "start", startOptions);
841
+ return true;
842
+ }
843
+ return {
844
+ on,
845
+ ons,
846
+ stop,
847
+ start,
848
+ get uiUrl() {
849
+ return _uiUrl;
850
+ },
851
+ get options() {
852
+ return options;
853
+ },
854
+ get status() {
855
+ return _status;
856
+ },
857
+ get testSummary() {
858
+ return { ..._testSummary };
859
+ }
860
+ };
861
+ }
862
+ // src/module.ts
863
+ var module_default = defineNuxtModule({
864
+ meta: {
865
+ name: "@nuxt/test-utils",
866
+ configKey: "testUtils",
867
+ version: "4.4.0"
868
+ },
869
+ defaults: {
870
+ startOnBoot: false,
871
+ logToConsole: false,
872
+ removeTestIdAttribute: false
873
+ },
874
+ async onInstall(nuxt) {
875
+ await runInstallWizard(nuxt);
876
+ },
877
+ async setup(options, nuxt) {
878
+ const { addTypeTemplate, addVitePlugin } = await loadKit(nuxt.options.rootDir);
879
+ const resolver = createResolver(import.meta.url);
880
+ if (options._fromVitestConfig) {
881
+ await setupImportMocking(nuxt);
882
+ nuxt.hook("app:templates", (app) => {
883
+ const template = app.templates.find((t) => t.filename === "paths.mjs");
884
+ if (!template?.getContents) return;
885
+ const original = template.getContents;
886
+ const inlineAppConfig = JSON.stringify(nuxt.options.app);
887
+ template.getContents = async (data) => {
888
+ return (await original(data)).replace(/^import \{ useRuntimeConfig \} from ['"]nitropack\/runtime['"]\n?/m, "").replace(/const getAppConfig = \(\) => useRuntimeConfig\(\)\.app/, () => `const getAppConfig = () => (${inlineAppConfig})`);
889
+ };
890
+ });
891
+ addVitePlugin(NuxtRootStubPlugin({
892
+ entry: await resolvePath("#app/entry", { alias: nuxt.options.alias }),
893
+ rootStubPath: await resolvePath(resolver.resolve("./runtime/nuxt-root"))
894
+ }));
895
+ }
896
+ if (!nuxt.options.test && !nuxt.options.dev) {
897
+ nuxt.options.vite.define ||= {};
898
+ nuxt.options.vite.define["import.meta.vitest"] = "undefined";
899
+ }
900
+ const h3 = resolveH3Package(nuxt.options.rootDir, nuxt.options.appDir, nuxt.options.modulesDir);
901
+ if (h3) addTypeTemplate({
902
+ filename: "types/test-utils-h3.d.ts",
903
+ getContents: ({ nuxt }) => {
904
+ const h3Path = relative(join(nuxt.options.buildDir, "types"), h3.rootPath);
905
+ return [
906
+ `import type { EventHandler, HTTPMethod } from ${JSON.stringify(h3Path.startsWith(".") ? h3Path : `./${h3Path}`)}`,
907
+ `declare module '@nuxt/test-utils/runtime' {`,
908
+ ` interface RegisterEndpointH3Types {`,
909
+ ` EventHandler: EventHandler`,
910
+ ` HTTPMethod: HTTPMethod`,
911
+ ` }`,
912
+ `}`,
913
+ `export {}`
914
+ ].join("\n");
915
+ }
916
+ }, {
917
+ nuxt: true,
918
+ node: true,
919
+ shared: true
920
+ });
921
+ nuxt.hook("prepare:types", (ctx) => {
922
+ ctx.references.push({ types: "vitest/import-meta" });
923
+ for (const tsConfig of [
924
+ ctx.tsConfig,
925
+ ctx.nodeTsConfig,
926
+ ctx.sharedTsConfig
927
+ ]) {
928
+ if (!tsConfig) continue;
929
+ tsConfig.compilerOptions ||= {};
930
+ tsConfig.compilerOptions.allowImportingTsExtensions = true;
931
+ }
932
+ if (ctx.nodeTsConfig) {
933
+ ctx.nodeTsConfig.include ||= [];
934
+ ctx.nodeTsConfig.include.push(relative(nuxt.options.buildDir, join(nuxt.options.rootDir, "vitest.config.*")));
935
+ if (nuxt.options.workspaceDir !== nuxt.options.rootDir) ctx.nodeTsConfig.include.push(relative(nuxt.options.buildDir, join(nuxt.options.workspaceDir, "vitest.config.*")));
936
+ }
937
+ });
938
+ if (options.removeTestIdAttribute) {
939
+ const testIdAttr = options.removeTestIdAttribute === true ? "data-testid" : options.removeTestIdAttribute;
940
+ const transform = removeAttrsNodeTransform([testIdAttr]);
941
+ logger.info(`Remove testIdAttribute '${testIdAttr}' enabled.`);
942
+ nuxt.hook("build:before", () => {
943
+ const template = (nuxt.options.vite.vue ||= {}).template ||= {};
944
+ template.compilerOptions = {
945
+ ...template.compilerOptions,
946
+ nodeTransforms: [...template.compilerOptions?.nodeTransforms || [], transform]
947
+ };
948
+ const loader = nuxt.options.webpack.loaders.vue;
949
+ loader.compilerOptions = {
950
+ ...loader.compilerOptions,
951
+ nodeTransforms: [...loader.compilerOptions?.nodeTransforms || [], transform]
952
+ };
953
+ });
954
+ }
955
+ if (!nuxt.options.dev) return;
956
+ if (process.env.TEST || process.env.VITE_TEST) return;
957
+ const vitestWrapper = createVitestWrapper(options, nuxt);
958
+ onDevToolsInitialized(async () => {
959
+ await setupDevTools(vitestWrapper, nuxt);
960
+ }, nuxt);
961
+ if (options.startOnBoot) vitestWrapper.start();
962
+ }
963
+ });
964
+ function createVitestWrapper(options, nuxt = useNuxt()) {
965
+ const watchMode = !isCI;
966
+ const wrapper = vitestWrapper({
967
+ cwd: nuxt.options.rootDir,
968
+ apiPorts: [15555],
969
+ logToConsole: options.logToConsole ?? false,
970
+ watchMode
971
+ });
972
+ wrapper.ons({
973
+ started({ uiUrl }) {
974
+ if (watchMode) logger.info(`Vitest UI starting on ${uiUrl}`);
975
+ },
976
+ exited({ exitCode }) {
977
+ if (watchMode) logger.info(`Vitest exited with code ${exitCode}`);
978
+ else nuxt.close().finally(() => process.exit(exitCode));
979
+ }
980
+ });
981
+ nuxt.hooks.addHooks({
982
+ close: () => wrapper.stop(),
983
+ restart: () => wrapper.stop()
984
+ });
985
+ return wrapper;
986
+ }
987
+ export { module_default as default };