@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,244 @@
1
+ import { exec } from "tinyexec";
2
+ import { $Fetch } from "ofetch";
3
+ import { ConsolaInstance, LogType } from "consola";
4
+ import { Nuxt, NuxtConfig } from "@nuxt/schema";
5
+ import { Browser, BrowserContextOptions, LaunchOptions, Page, Response as Response$1 } from "@ohos-ports/playwright-core";
6
+ declare function createBrowser(): Promise<void>;
7
+ declare function getBrowser(): Promise<Browser>;
8
+ type _GotoOptions = NonNullable<Parameters<Page['goto']>[1]>;
9
+ interface GotoOptions extends Omit<_GotoOptions, 'waitUntil'> {
10
+ waitUntil?: 'hydration' | 'route' | _GotoOptions['waitUntil'];
11
+ }
12
+ interface NuxtPage extends Omit<Page, 'goto'> {
13
+ goto: (url: string, options?: GotoOptions) => Promise<Response$1 | null>;
14
+ }
15
+ declare function createPage(path?: string, options?: BrowserContextOptions): Promise<NuxtPage>;
16
+ declare function waitForHydration(page: Page, url: string, waitUntil?: GotoOptions['waitUntil']): Promise<void>;
17
+ interface StartServerOptions {
18
+ env?: Record<string, unknown>;
19
+ /**
20
+ * Overrides the consola log level for the server subprocess.
21
+ * Defaults to `TestOptions.logLevel` (which itself defaults to `1`).
22
+ */
23
+ logLevel?: number;
24
+ }
25
+ declare function startServer(options?: StartServerOptions): Promise<void>;
26
+ declare function stopServer(): Promise<void>;
27
+ /**
28
+ * Returns the lines captured from the server subprocess's stdout/stderr since
29
+ * the last `startServer()` call (or `clearServerLogs()`).
30
+ * Only populated when `captureServerLogs` is `true` (the default).
31
+ */
32
+ declare function getServerLogs(): string[];
33
+ /**
34
+ * Clears the captured server log lines. Useful between requests when you want
35
+ * to assert only on the logs produced by a specific operation.
36
+ */
37
+ declare function clearServerLogs(): void;
38
+ declare function fetch$1(path: string, options?: RequestInit): Promise<Response>;
39
+ declare const $fetch: "$fetch" extends keyof typeof globalThis ? typeof globalThis.$fetch : $Fetch;
40
+ declare function url(path: string): string;
41
+ type TestRunner = 'vitest' | 'jest' | 'cucumber' | 'bun';
42
+ interface TestOptions {
43
+ testDir: string;
44
+ fixture: string;
45
+ /**
46
+ * Name of the configuration file.
47
+ * @default 'nuxt.config'
48
+ */
49
+ configFile: string;
50
+ /**
51
+ * Path to a directory with a Nuxt app to be put under test.
52
+ * @default '.'
53
+ */
54
+ rootDir: string;
55
+ buildDir: string;
56
+ nuxtConfig: NuxtConfig;
57
+ /**
58
+ * Whether to run a separate build step.
59
+ * @default true // (`false` if `browser` or `server` is disabled, or if a `host` is provided)
60
+ */
61
+ build: boolean;
62
+ dev: boolean;
63
+ /**
64
+ * The amount of time (in milliseconds) to allow for `setupTest` to complete its work (which could include building or generating files for a Nuxt application, depending on the options that are passed).
65
+ *
66
+ * This is also the effective deadline for the `@nuxt/test-utils/playwright` worker fixture.
67
+ * @default 120000 // or `240000` on windows
68
+ */
69
+ setupTimeout: number;
70
+ /**
71
+ * The amount of time (in milliseconds) to allow tearing down the test environment, such as closing the browser.
72
+ * @default 30000
73
+ */
74
+ teardownTimeout: number;
75
+ /**
76
+ * The amount of time (in milliseconds) to wait for the dev or built server to become ready (i.e. respond successfully on the configured base URL) before failing.
77
+ *
78
+ * This is bounded by `setupTimeout` (including in Playwright mode), so increasing this is only useful in combination with a sufficiently large `setupTimeout`.
79
+ * @default 120000 // on windows; otherwise 60000
80
+ */
81
+ serverStartTimeout: number;
82
+ waitFor: number;
83
+ /**
84
+ * Under the hood, Nuxt test utils uses [`playwright`](https://playwright.dev) to carry out browser testing. If this option is set, a browser will be launched and can be controlled in the subsequent test suite.
85
+ * @default false
86
+ */
87
+ browser: boolean;
88
+ /**
89
+ * Specify the runner for the test suite. One of `'vitest' | 'jest' | 'cucumber' | 'bun'`.
90
+ * @default 'vitest'
91
+ */
92
+ runner: TestRunner;
93
+ logLevel: number;
94
+ browserOptions: {
95
+ /** The type of browser to launch - either `chromium`, `firefox` or `webkit` */
96
+ type: 'chromium' | 'firefox' | 'webkit';
97
+ /** `object` of options that will be passed to playwright when launching the browser. See [full API reference](https://playwright.dev/docs/api/class-browsertype#browser-type-launch). */
98
+ launch?: LaunchOptions;
99
+ };
100
+ /**
101
+ * Whether to launch a server to respond to requests in the test suite.
102
+ * @default true // (`false` if a `host` is provided)
103
+ */
104
+ server: boolean;
105
+ /**
106
+ * If provided, a URL to use as the test target instead of building and running a new server. Useful for running "real" end-to-end tests against a deployed version of your application, or against an already running local server.
107
+ * @default undefined
108
+ */
109
+ host?: string;
110
+ /**
111
+ * If provided, set the launched test server port to the value.
112
+ * @default undefined
113
+ */
114
+ port?: number;
115
+ env?: StartServerOptions['env'];
116
+ /**
117
+ * Whether to capture server process output instead of inheriting stdio.
118
+ * When `true` (default), server stdout/stderr is suppressed from the console
119
+ * and accessible via `getServerLogs()`. Set to `false` to restore the old
120
+ * inherit-stdio behaviour (useful when debugging a test locally).
121
+ * @default true
122
+ */
123
+ captureServerLogs?: boolean;
124
+ }
125
+ interface TestContext {
126
+ options: TestOptions;
127
+ nuxt?: Nuxt;
128
+ browser?: Browser;
129
+ url?: string;
130
+ serverProcess?: ReturnType<typeof exec>;
131
+ /**
132
+ * Set when `afterAll` begins tearing down. A late-resolving `beforeAll` (for example one
133
+ * abandoned after a setup timeout) checks this so it does not orphan a
134
+ * server process after teardown.
135
+ */
136
+ disposed?: boolean;
137
+ mockFn?: <P extends unknown[], R>(fn?: (...args: P) => R) => (...args: P) => R;
138
+ /**
139
+ * Lines emitted to the server subprocess's stdout/stderr, in order.
140
+ * Only populated when `options.captureServerLogs` is `true`.
141
+ */
142
+ serverLogs: string[];
143
+ /**
144
+ * Functions to run on the vitest `afterAll` hook.
145
+ * Useful for removing anything created during the test.
146
+ */
147
+ teardown?: (() => void)[];
148
+ }
149
+ interface TestHooks {
150
+ beforeEach: () => void;
151
+ afterEach: () => void;
152
+ afterAll: () => Promise<void>;
153
+ beforeAll: () => Promise<void>;
154
+ /**
155
+ * @deprecated use `beforeAll` instead
156
+ */
157
+ setup: () => Promise<void>;
158
+ ctx: TestContext;
159
+ }
160
+ declare function createTestContext(options: Partial<TestOptions>): TestContext;
161
+ declare function useTestContext(): TestContext;
162
+ declare function setTestContext(context: TestContext): TestContext;
163
+ declare function setTestContext(context?: TestContext): TestContext | undefined;
164
+ declare function isDev(): boolean;
165
+ declare function recoverContextFromEnv(): void;
166
+ declare function exposeContextToEnv(): void;
167
+ declare function mockFn(): (<P extends unknown[], R>(fn?: (...args: P) => R) => (...args: P) => R) | undefined;
168
+ type MockLogs = Record<LogType, ConsolaInstance[LogType]>;
169
+ interface MockLoggerOptions {
170
+ /**
171
+ * Calls the original logger methods in addition to recording mock calls.
172
+ * @default false
173
+ */
174
+ spy?: boolean;
175
+ }
176
+ interface MockLogger extends MockLogs {
177
+ /**
178
+ * Returns a snapshot of the logger's full call history.
179
+ * Useful after `clearMocks`. These mocks are for assertions only (no-op).
180
+ * Overriding the mockLogger's mock or its implementation stops tracking new calls.
181
+ */
182
+ getSnapshot: () => MockLogs;
183
+ /**
184
+ * Returns a mock logger scoped to the specified tag (or untagged logs if omitted).
185
+ *
186
+ * @example
187
+ * ```ts
188
+ * const mock = mockLogger()
189
+ * useLogger('t1').info('mock info log by t1')
190
+ * expect(mock.getWithTag('t1').info).toHaveBeenCalledWith('mock info log by t1')
191
+ * ```
192
+ */
193
+ getWithTag: (tag?: string) => Omit<MockLogger, 'getWithTag' | 'restoreOriginal'>;
194
+ /**
195
+ * Restores the original logger methods and stops mocking newly created loggers.
196
+ */
197
+ restoreOriginal: () => void;
198
+ }
199
+ /**
200
+ * Mocks the Nuxt logger for e2e testing in the fixture or build phase.
201
+ * Automatically restores the original logger during the test teardown phase.
202
+ *
203
+ * @example
204
+ * ```ts
205
+ * import { mockLogger, setup } from '@nuxt/test-utils/e2e'
206
+ *
207
+ * await setup({})
208
+ * const logger = mockLogger()
209
+ *
210
+ * it('logging', () => {
211
+ * expect(logger.info).toHaveBeenCalledWith('info log')
212
+ * expect(logger.info).not.toHaveBeenCalledWith('info log raw')
213
+ * expect(logger.info.raw).toHaveBeenCalledWith('info log raw')
214
+ * // Useful if global clearMocks is enabled (e.g., Vitest default)
215
+ * const snapshot = logger.getSnapshot()
216
+ * expect(snapshot.info).toHaveBeenCalledWith('info log')
217
+ * expect(snapshot.info.raw).toHaveBeenCalledWith('info log raw')
218
+ * })
219
+ * ```
220
+ */
221
+ declare function mockLogger(options?: MockLoggerOptions): MockLogger;
222
+ declare function loadFixture(): Promise<void>;
223
+ declare function buildFixture(): Promise<void>;
224
+ declare function setupBun(hooks: TestHooks): Promise<void>;
225
+ declare function setupCucumber(hooks: TestHooks): Promise<void>;
226
+ declare function setupJest(hooks: TestHooks): Promise<void>;
227
+ declare function setupVitest(hooks: TestHooks): Promise<void>;
228
+ declare const setupMaps: {
229
+ bun: typeof setupBun;
230
+ cucumber: typeof setupCucumber;
231
+ jest: typeof setupJest;
232
+ vitest: typeof setupVitest;
233
+ };
234
+ declare function createTest(options: Partial<TestOptions>): TestHooks;
235
+ declare function setup(options?: Partial<TestOptions>): Promise<void>;
236
+ interface RunTestOptions {
237
+ rootDir: string;
238
+ dev?: boolean;
239
+ watch?: boolean;
240
+ runner?: 'vitest';
241
+ globalSetup?: boolean;
242
+ }
243
+ declare function runTests(opts: RunTestOptions): Promise<void>;
244
+ export { createBrowser as A, fetch$1 as C, url as D, stopServer as E, getBrowser as M, waitForHydration as N, GotoOptions as O, clearServerLogs as S, startServer as T, TestHooks as _, setupMaps as a, $fetch as b, mockFn as c, exposeContextToEnv as d, isDev as f, TestContext as g, useTestContext as h, setup as i, createPage as j, NuxtPage as k, mockLogger as l, setTestContext as m, runTests as n, buildFixture as o, recoverContextFromEnv as p, createTest as r, loadFixture as s, RunTestOptions as t, createTestContext as u, TestOptions as v, getServerLogs as w, StartServerOptions as x, TestRunner as y };
@@ -0,0 +1,373 @@
1
+ import { a as startServer, c as createTestContext, f as setTestContext, o as stopServer, p as useTestContext, s as url } from "./server-Vl1UKNYB.mjs";
2
+ import { i as loadKit } from "./utils-CCklE0VI.mjs";
3
+ import { resolve } from "node:path";
4
+ import { defu as defu$1 } from "defu";
5
+ import { distDir } from "#dirs";
6
+ import { resolve as resolve$1 } from "pathe";
7
+ import { existsSync, promises } from "node:fs";
8
+ import { Consola, LogTypes, consola } from "consola";
9
+ // src/e2e/browser.ts
10
+ async function createBrowser() {
11
+ const ctx = useTestContext();
12
+ let playwright;
13
+ try {
14
+ playwright = await import("@ohos-ports/playwright-core");
15
+ } catch {
16
+ /* istanbul ignore next */
17
+ throw new Error(`
18
+ The dependency '@ohos-ports/playwright-core' not found.
19
+ Please run 'yarn add --dev @ohos-ports/playwright-core' or 'npm install --save-dev @ohos-ports/playwright-core'
20
+ `);
21
+ }
22
+ const { type, launch } = ctx.options.browserOptions;
23
+ if (!playwright[type]) throw new Error(`Invalid browser '${type}'`);
24
+ ctx.browser = await playwright[type].launch(launch);
25
+ }
26
+ async function getBrowser() {
27
+ const ctx = useTestContext();
28
+ if (!ctx.browser) await createBrowser();
29
+ return ctx.browser;
30
+ }
31
+ async function createPage(path, options) {
32
+ const page = await (await getBrowser()).newPage(options);
33
+ const _goto = page.goto.bind(page);
34
+ page.goto = async (url, options) => {
35
+ const waitUntil = options?.waitUntil;
36
+ if (waitUntil && ["hydration", "route"].includes(waitUntil)) delete options.waitUntil;
37
+ const res = await _goto(url, options);
38
+ await waitForHydration(page, url, waitUntil);
39
+ return res;
40
+ };
41
+ if (path) await page.goto(url(path), options?.javaScriptEnabled === false ? {} : { waitUntil: "hydration" });
42
+ return page;
43
+ }
44
+ async function waitForHydration(page, url, waitUntil) {
45
+ if (waitUntil === "hydration") await page.waitForFunction(() => window.useNuxtApp?.().isHydrating === false);
46
+ else if (waitUntil === "route") await page.waitForFunction((route) => window.useNuxtApp?.()._route.fullPath === route, url);
47
+ }
48
+ // src/e2e/mock.ts
49
+ function mockFn() {
50
+ return useTestContext().mockFn;
51
+ }
52
+ /**
53
+ * Mocks the Nuxt logger for e2e testing in the fixture or build phase.
54
+ * Automatically restores the original logger during the test teardown phase.
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * import { mockLogger, setup } from '@nuxt/test-utils/e2e'
59
+ *
60
+ * await setup({})
61
+ * const logger = mockLogger()
62
+ *
63
+ * it('logging', () => {
64
+ * expect(logger.info).toHaveBeenCalledWith('info log')
65
+ * expect(logger.info).not.toHaveBeenCalledWith('info log raw')
66
+ * expect(logger.info.raw).toHaveBeenCalledWith('info log raw')
67
+ * // Useful if global clearMocks is enabled (e.g., Vitest default)
68
+ * const snapshot = logger.getSnapshot()
69
+ * expect(snapshot.info).toHaveBeenCalledWith('info log')
70
+ * expect(snapshot.info.raw).toHaveBeenCalledWith('info log raw')
71
+ * })
72
+ * ```
73
+ */
74
+ function mockLogger(options = {}) {
75
+ const fn = mockFn();
76
+ const ctx = useTestContext();
77
+ if (!fn) throw new Error(`mockLogger is not supported in ${ctx.options.runner}.`);
78
+ const mockLogger = createMockLogger(fn, options);
79
+ ctx.teardown ??= [];
80
+ ctx.teardown.unshift(mockLogger.restoreOriginal);
81
+ return mockLogger;
82
+ }
83
+ function createMockLogger(fn, options) {
84
+ const createInstance = Consola.prototype.create;
85
+ const cleanupFns = [() => {
86
+ Consola.prototype.create = createInstance;
87
+ }];
88
+ const cleanup = () => cleanupFns.forEach((fn) => fn());
89
+ const registry = createMockLoggerRegistry(fn);
90
+ const applyMockFn = (instance) => {
91
+ const original = { ...instance };
92
+ const types = Object.keys(instance.options.types);
93
+ const { log, raw } = registry.withTag(instance.options.defaults.tag ?? "");
94
+ for (const type of types) instance[type] = mockConsolaLog(fn((...args) => {
95
+ log(type, args);
96
+ if (options.spy) original[type](...args);
97
+ }), fn((...args) => {
98
+ raw(type, args);
99
+ if (options.spy) original[type].raw(...args);
100
+ }));
101
+ cleanupFns.unshift(() => types.forEach((type) => {
102
+ instance[type] = original[type];
103
+ }));
104
+ return instance;
105
+ };
106
+ Consola.prototype.create = function(...args) {
107
+ return applyMockFn(createInstance.call(this, ...args));
108
+ };
109
+ applyMockFn(consola);
110
+ const toMockLogger = (registry) => {
111
+ const methods = {
112
+ getSnapshot: registry.snapshot,
113
+ getWithTag: (tag) => toMockLogger(registry.withTag(tag)),
114
+ restoreOriginal: cleanup
115
+ };
116
+ return new Proxy(registry.mocks, {
117
+ get(target, p, receiver) {
118
+ return Reflect.get(methods, p, receiver) ?? Reflect.get(target, p, receiver);
119
+ },
120
+ has(target, p) {
121
+ return Reflect.has(methods, p) || Reflect.has(target, p);
122
+ },
123
+ ownKeys(target) {
124
+ return [.../* @__PURE__ */ new Set([...Reflect.ownKeys(target), ...Reflect.ownKeys(methods)])];
125
+ },
126
+ getOwnPropertyDescriptor(target, p) {
127
+ return Reflect.getOwnPropertyDescriptor(methods, p) ?? Reflect.getOwnPropertyDescriptor(target, p);
128
+ }
129
+ });
130
+ };
131
+ return toMockLogger(registry);
132
+ }
133
+ function createMockLoggerRegistry(fn, parent) {
134
+ const mocks = {};
135
+ const calls = {};
136
+ const tags = /* @__PURE__ */ new Map();
137
+ const init = (type) => {
138
+ calls[type] ??= {
139
+ log: [],
140
+ raw: []
141
+ };
142
+ mocks[type] ??= mockConsolaLog(fn(), fn());
143
+ };
144
+ Object.keys(LogTypes).forEach((type) => init(type));
145
+ const registry = {
146
+ mocks,
147
+ log: (type, args) => {
148
+ init(type);
149
+ mocks[type](...args);
150
+ calls[type].log.push(args);
151
+ parent?.log(type, args);
152
+ },
153
+ raw: (type, args) => {
154
+ init(type);
155
+ mocks[type].raw(...args);
156
+ calls[type].raw.push(args);
157
+ parent?.raw(type, args);
158
+ },
159
+ snapshot: () => {
160
+ const snapshot = {};
161
+ for (const type of Object.keys(calls)) {
162
+ const mock = mockConsolaLog(fn(), fn());
163
+ calls[type].log.forEach((args) => mock(...args));
164
+ calls[type].raw.forEach((args) => mock.raw(...args));
165
+ snapshot[type] = mock;
166
+ }
167
+ return snapshot;
168
+ },
169
+ withTag: (tag) => {
170
+ const withTag = tags.get(tag ?? "") ?? createMockLoggerRegistry(fn, registry);
171
+ tags.set(tag ?? "", withTag);
172
+ return withTag;
173
+ }
174
+ };
175
+ return registry;
176
+ }
177
+ function mockConsolaLog(_fn, raw) {
178
+ const fn = _fn;
179
+ fn.raw = raw;
180
+ return fn;
181
+ }
182
+ // src/e2e/nuxt.ts
183
+ const isNuxtApp = (dir) => {
184
+ return existsSync(dir) && (existsSync(resolve(dir, "pages")) || existsSync(resolve(dir, "nuxt.config.js")) || existsSync(resolve(dir, "nuxt.config.mjs")) || existsSync(resolve(dir, "nuxt.config.cjs")) || existsSync(resolve(dir, "nuxt.config.ts")) || existsSync(resolve(dir, ".config", "nuxt.js")) || existsSync(resolve(dir, ".config", "nuxt.mjs")) || existsSync(resolve(dir, ".config", "nuxt.cjs")) || existsSync(resolve(dir, ".config", "nuxt.ts")));
185
+ };
186
+ const resolveRootDir = () => {
187
+ const { options } = useTestContext();
188
+ const dirs = [
189
+ options.rootDir,
190
+ resolve(options.testDir, options.fixture),
191
+ process.cwd()
192
+ ];
193
+ for (const dir of dirs) if (dir && isNuxtApp(dir)) return dir;
194
+ throw new Error("Invalid nuxt app. (Please explicitly set `options.rootDir` pointing to a valid nuxt app)");
195
+ };
196
+ async function loadFixture() {
197
+ const ctx = useTestContext();
198
+ ctx.options.rootDir = resolveRootDir();
199
+ const randomId = Math.random().toString(36).slice(2, 8);
200
+ const buildDir = ctx.options.buildDir || resolve(ctx.options.rootDir, ".nuxt", "test", randomId);
201
+ ctx.options.nuxtConfig = defu$1(ctx.options.nuxtConfig, { buildDir });
202
+ if (!ctx.options.dev) ctx.options.nuxtConfig = defu$1(ctx.options.nuxtConfig, { nitro: { output: { dir: resolve(buildDir, "output") } } });
203
+ if (ctx.options.build) {
204
+ const buildDirExists = existsSync(resolve(ctx.options.rootDir, ctx.options.nuxtConfig.buildDir));
205
+ const { loadNuxt, logger } = await loadKit(ctx.options.rootDir);
206
+ ctx.nuxt = await loadNuxt({
207
+ cwd: ctx.options.rootDir,
208
+ dev: ctx.options.dev,
209
+ overrides: ctx.options.nuxtConfig,
210
+ configFile: ctx.options.configFile
211
+ }).finally(() => {
212
+ logger.restoreAll();
213
+ });
214
+ const buildDir = ctx.nuxt.options.buildDir;
215
+ if (!buildDirExists) {
216
+ await promises.mkdir(buildDir, { recursive: true });
217
+ ctx.teardown = ctx.teardown || [];
218
+ ctx.teardown.push(() => promises.rm(buildDir, {
219
+ recursive: true,
220
+ force: true
221
+ }));
222
+ }
223
+ }
224
+ }
225
+ async function buildFixture() {
226
+ const ctx = useTestContext();
227
+ const { buildNuxt, logger } = await loadKit(ctx.options.rootDir);
228
+ const prevLevel = logger.level;
229
+ logger.level = ctx.options.logLevel;
230
+ await buildNuxt(ctx.nuxt).finally(() => {
231
+ logger.level = prevLevel;
232
+ logger.restoreAll();
233
+ });
234
+ }
235
+ // src/e2e/setup/bun.ts
236
+ async function setupBun(hooks) {
237
+ const bunTest = await import("bun:test");
238
+ hooks.ctx.mockFn = bunTest.mock;
239
+ bunTest.beforeAll(hooks.beforeAll, hooks.ctx.options.setupTimeout);
240
+ bunTest.beforeEach(hooks.beforeEach);
241
+ bunTest.afterEach(hooks.afterEach);
242
+ bunTest.afterAll(hooks.afterAll, hooks.ctx.options.teardownTimeout);
243
+ }
244
+ // src/e2e/setup/cucumber.ts
245
+ async function setupCucumber(hooks) {
246
+ const { After, AfterAll, Before, BeforeAll } = await import("@cucumber/cucumber");
247
+ BeforeAll({ timeout: hooks.ctx.options.setupTimeout }, hooks.beforeAll);
248
+ Before(hooks.beforeEach);
249
+ After(hooks.afterEach);
250
+ AfterAll({ timeout: hooks.ctx.options.teardownTimeout }, hooks.afterAll);
251
+ }
252
+ // src/e2e/setup/jest.ts
253
+ async function setupJest(hooks) {
254
+ const { jest, test, beforeEach, afterAll, afterEach } = await import("@jest/globals");
255
+ hooks.ctx.mockFn = jest.fn;
256
+ test("setup", hooks.beforeAll, hooks.ctx.options.setupTimeout);
257
+ beforeEach(hooks.beforeEach);
258
+ afterEach(hooks.afterEach);
259
+ afterAll(hooks.afterAll, hooks.ctx.options.teardownTimeout);
260
+ }
261
+ // src/e2e/setup/vitest.ts
262
+ async function setupVitest(hooks) {
263
+ const vitest = await import("vitest");
264
+ hooks.ctx.mockFn = vitest.vi.fn;
265
+ vitest.beforeAll(hooks.beforeAll, hooks.ctx.options.setupTimeout);
266
+ vitest.beforeEach(hooks.beforeEach);
267
+ vitest.afterEach(hooks.afterEach);
268
+ vitest.afterAll(hooks.afterAll, hooks.ctx.options.teardownTimeout);
269
+ }
270
+ // src/e2e/setup/index.ts
271
+ const setupMaps = {
272
+ bun: setupBun,
273
+ cucumber: setupCucumber,
274
+ jest: setupJest,
275
+ vitest: setupVitest
276
+ };
277
+ function withTimeout(label, ms, promise) {
278
+ let timedOut = false;
279
+ let timer;
280
+ const timeout = new Promise((resolve) => {
281
+ timer = setTimeout(() => {
282
+ timedOut = true;
283
+ console.warn(`[@nuxt/test-utils] Timed out after ${ms}ms ${label} during teardown. Continuing; some processes or file handles may still be held.`);
284
+ resolve(void 0);
285
+ }, ms);
286
+ });
287
+ const guarded = promise.catch((error) => {
288
+ if (timedOut) {
289
+ console.warn(`[@nuxt/test-utils] Error ${label} during teardown:`, error);
290
+ return;
291
+ }
292
+ throw error;
293
+ }).finally(() => clearTimeout(timer));
294
+ return Promise.race([guarded, timeout]);
295
+ }
296
+ function createTest(options) {
297
+ const ctx = createTestContext(options);
298
+ const beforeEach = () => {
299
+ setTestContext(ctx);
300
+ };
301
+ const afterEach = () => {
302
+ setTestContext(void 0);
303
+ };
304
+ const afterAll = async () => {
305
+ ctx.disposed = true;
306
+ const deadline = Date.now() + ctx.options.teardownTimeout;
307
+ const remaining = () => Math.max(1e3, deadline - Date.now());
308
+ if (ctx.serverProcess) {
309
+ setTestContext(ctx);
310
+ await stopServer();
311
+ setTestContext(void 0);
312
+ }
313
+ if (ctx.nuxt && ctx.nuxt.options.dev) await withTimeout("closing the Nuxt instance", remaining(), ctx.nuxt.close());
314
+ if (ctx.browser) await withTimeout("closing the browser", remaining(), ctx.browser.close());
315
+ await withTimeout("running teardown hooks", remaining(), Promise.all(!ctx.teardown ? [] : ctx.teardown.map((fn) => fn())));
316
+ };
317
+ const beforeAll = async () => {
318
+ setTestContext(ctx);
319
+ if (ctx.options.fixture) await loadFixture();
320
+ if (ctx.options.build) await buildFixture();
321
+ if (ctx.options.server) await startServer(ctx.options.env);
322
+ if (ctx.options.waitFor) await new Promise((resolve) => setTimeout(resolve, ctx.options.waitFor));
323
+ if (ctx.options.browser) await createBrowser();
324
+ };
325
+ return {
326
+ beforeEach,
327
+ afterEach,
328
+ afterAll,
329
+ beforeAll,
330
+ setup: beforeAll,
331
+ ctx
332
+ };
333
+ }
334
+ async function setup(options = {}) {
335
+ if (typeof __NUXT_VITEST_RESOLVED__ === "boolean" && __NUXT_VITEST_RESOLVED__) console.warn("Do not use defineVitestConfig or defineVitestProject for end-to-end tests, as they only work with nuxt client-environment tests.\nPlease refer to the setup section: https://nuxt.com/docs/4.x/getting-started/testing#setup");
336
+ const hooks = createTest(options);
337
+ const setupFn = setupMaps[hooks.ctx.options.runner];
338
+ await setupFn(hooks);
339
+ }
340
+ // src/e2e/run.ts
341
+ const RunTestDefaults = {
342
+ runner: "vitest",
343
+ globalSetup: true
344
+ };
345
+ async function runTests(opts) {
346
+ opts = {
347
+ ...RunTestDefaults,
348
+ ...opts
349
+ };
350
+ if (opts.runner !== "vitest") throw new Error(`Unsupported runner: ${opts.runner}. Currently only vitest runner is supported.`);
351
+ if (opts.dev) process.env.NUXT_TEST_DEV = "true";
352
+ process.env.NUXT_TEST_OPTIONS = JSON.stringify(opts);
353
+ const { startVitest } = await import("vitest/node");
354
+ if (!await startVitest("test", [], {
355
+ root: opts.rootDir,
356
+ run: !opts.watch,
357
+ server: { deps: { inline: [/@nuxt\/test-utils/] } }
358
+ }, {
359
+ esbuild: { tsconfigRaw: "{}" },
360
+ test: {
361
+ dir: opts.rootDir,
362
+ server: { deps: { inline: [
363
+ distDir,
364
+ "@nuxt/test-utils",
365
+ "@nuxt/test-utils-nightly",
366
+ "@nuxt/test-utils-edge"
367
+ ] } },
368
+ globals: true,
369
+ globalSetup: [...opts.globalSetup ? [resolve$1(distDir, "./runtime/global-setup")] : []]
370
+ }
371
+ })) process.exit(1);
372
+ }
373
+ export { buildFixture as a, mockLogger as c, getBrowser as d, waitForHydration as f, setupMaps as i, createBrowser as l, createTest as n, loadFixture as o, setup as r, mockFn as s, runTests as t, createPage as u };
package/dist/e2e.d.mts ADDED
@@ -0,0 +1,2 @@
1
+ import { A as createBrowser, C as fetch, D as url, E as stopServer, M as getBrowser, N as waitForHydration, O as GotoOptions, S as clearServerLogs, T as startServer, _ as TestHooks, a as setupMaps, b as $fetch, c as mockFn, d as exposeContextToEnv, f as isDev, g as TestContext, h as useTestContext, i as setup, j as createPage, k as NuxtPage, l as mockLogger, m as setTestContext, n as runTests, o as buildFixture, p as recoverContextFromEnv, r as createTest, s as loadFixture, t as RunTestOptions, u as createTestContext, v as TestOptions, w as getServerLogs, x as StartServerOptions, y as TestRunner } from "./e2e-BO5mj9tk.mjs";
2
+ export { $fetch, GotoOptions, NuxtPage, RunTestOptions, StartServerOptions, TestContext, TestHooks, TestOptions, TestRunner, buildFixture, clearServerLogs, createBrowser, createPage, createTest, createTestContext, exposeContextToEnv, fetch, getBrowser, getServerLogs, isDev, loadFixture, mockFn, mockLogger, recoverContextFromEnv, runTests, setTestContext, setup, setupMaps, startServer, stopServer, url, useTestContext, waitForHydration };
package/dist/e2e.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import { a as startServer, c as createTestContext, d as recoverContextFromEnv, f as setTestContext, i as getServerLogs, l as exposeContextToEnv, n as clearServerLogs, o as stopServer, p as useTestContext, r as fetch, s as url, t as $fetch, u as isDev } from "./server-Vl1UKNYB.mjs";
2
+ import { a as buildFixture, c as mockLogger, d as getBrowser, f as waitForHydration, i as setupMaps, l as createBrowser, n as createTest, o as loadFixture, r as setup, s as mockFn, t as runTests, u as createPage } from "./e2e-DzsWJ8cS.mjs";
3
+ export { $fetch, buildFixture, clearServerLogs, createBrowser, createPage, createTest, createTestContext, exposeContextToEnv, fetch, getBrowser, getServerLogs, isDev, loadFixture, mockFn, mockLogger, recoverContextFromEnv, runTests, setTestContext, setup, setupMaps, startServer, stopServer, url, useTestContext, waitForHydration };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * This is a function to render a component directly with the Nuxt server.
3
+ */
4
+ export declare function $fetchComponent(filepath: string, props?: Record<string, unknown>): Promise<unknown>;
5
+ export declare function componentTestUrl(filepath: string, props?: Record<string, unknown>): string;
@@ -0,0 +1,20 @@
1
+ import { p as useTestContext, t as $fetch } from "./server-Vl1UKNYB.mjs";
2
+ import { stringifyQuery } from "ufo";
3
+ import "ofetch";
4
+ import { resolve } from "pathe";
5
+ // src/experimental.ts
6
+ /**
7
+ * This is a function to render a component directly with the Nuxt server.
8
+ */
9
+ function $fetchComponent(filepath, props) {
10
+ return $fetch(componentTestUrl(filepath, props));
11
+ }
12
+ function componentTestUrl(filepath, props) {
13
+ const ctx = useTestContext();
14
+ filepath = resolve(ctx.options.rootDir, filepath);
15
+ return `/__nuxt_component_test__/?${stringifyQuery({
16
+ path: filepath,
17
+ props: JSON.stringify(props)
18
+ })}`;
19
+ }
20
+ export { $fetchComponent, componentTestUrl };
@@ -0,0 +1,34 @@
1
+ // src/vitest-wrapper/interface.ts
2
+ function isMessage(message) {
3
+ return message !== null && typeof message === "object" && "type" in message && message.type !== null && typeof message.type === "string" && "payload" in message && message.payload !== null && typeof message.payload === "object";
4
+ }
5
+ function createVitestTestSummary() {
6
+ return {
7
+ failedCount: 0,
8
+ passedCount: 0,
9
+ totalCount: 0
10
+ };
11
+ }
12
+ function sendMessageToHost(type, payload) {
13
+ process.send?.({
14
+ type,
15
+ payload
16
+ });
17
+ }
18
+ function listenHostMessages(listener) {
19
+ process.on("message", (message) => {
20
+ if (isMessage(message)) listener(message);
21
+ });
22
+ }
23
+ function sendMessageToCli(cli, type, payload) {
24
+ cli.send({
25
+ type,
26
+ payload
27
+ });
28
+ }
29
+ function listenCliMessages(cli, listener) {
30
+ cli.on("message", (message) => {
31
+ if (isMessage(message)) listener(message);
32
+ });
33
+ }
34
+ export { sendMessageToHost as a, sendMessageToCli as i, listenCliMessages as n, listenHostMessages as r, createVitestTestSummary as t };