@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.
- package/LICENSE +21 -0
- package/README.md +20 -2
- package/dirs.js +4 -0
- package/dist/browser/index.d.mts +7 -0
- package/dist/browser/index.mjs +12 -0
- package/dist/browser/pure.d.mts +2 -0
- package/dist/browser/pure.mjs +1 -0
- package/dist/config.d.mts +82 -0
- package/dist/config.mjs +336 -0
- package/dist/e2e/dev-server.d.mts +1 -0
- package/dist/e2e/dev-server.mjs +10 -0
- package/dist/e2e-BO5mj9tk.d.mts +244 -0
- package/dist/e2e-DzsWJ8cS.mjs +373 -0
- package/dist/e2e.d.mts +2 -0
- package/dist/e2e.mjs +3 -0
- package/dist/experimental.d.mts +5 -0
- package/dist/experimental.mjs +20 -0
- package/dist/interface-Dhh_nx8F.mjs +34 -0
- package/dist/module.d.mts +32 -0
- package/dist/module.mjs +987 -0
- package/dist/playwright.d.mts +33 -0
- package/dist/playwright.mjs +68 -0
- package/dist/pure-Ba9-jZYN.d.mts +56 -0
- package/dist/pure-C_CSGRkt.mjs +114 -0
- package/dist/runtime/browser-entry.mjs +15 -0
- package/dist/runtime/entry.mjs +19 -0
- package/dist/runtime/global-setup.mjs +15 -0
- package/dist/runtime/mocks/vue-devtools.mjs +11 -0
- package/dist/runtime/nuxt-root.mjs +17 -0
- package/dist/runtime/shared/environment.mjs +67 -0
- package/dist/runtime/shared/h3-v1.mjs +32 -0
- package/dist/runtime/shared/h3-v2.mjs +34 -0
- package/dist/runtime/shared/h3.mjs +5 -0
- package/dist/runtime/shared/nuxt.mjs +17 -0
- package/dist/runtime/shared/vue-wrapper-plugin.mjs +42 -0
- package/dist/runtime-utils/index.d.mts +208 -0
- package/dist/runtime-utils/index.mjs +276 -0
- package/dist/server-Vl1UKNYB.mjs +301 -0
- package/dist/suspended-BbyJTvUP.d.mts +45 -0
- package/dist/suspended-Bjq6Zao6.mjs +1 -0
- package/dist/suspended-UrdAzOmb.mjs +255 -0
- package/dist/utils-CCklE0VI.mjs +196 -0
- package/dist/vitest-environment.d.mts +42 -0
- package/dist/vitest-environment.mjs +318 -0
- package/dist/vitest-wrapper/cli.d.mts +1 -0
- package/dist/vitest-wrapper/cli.mjs +81 -0
- package/package.json +145 -4
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { o as resolveNuxtCli, s as toSerializable } from "./utils-CCklE0VI.mjs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { defu as defu$1 } from "defu";
|
|
4
|
+
import { joinURL, withTrailingSlash } from "ufo";
|
|
5
|
+
import { isBun, isWindows } from "std-env";
|
|
6
|
+
import { distDir } from "#dirs";
|
|
7
|
+
import { x, xSync } from "tinyexec";
|
|
8
|
+
import { getRandomPort, waitForPort } from "get-port-please";
|
|
9
|
+
import { createFetch, fetch } from "ofetch";
|
|
10
|
+
import { resolve as resolve$1 } from "pathe";
|
|
11
|
+
// src/e2e/context.ts
|
|
12
|
+
let currentContext;
|
|
13
|
+
function createTestContext(options) {
|
|
14
|
+
const _options = defu$1(options, {
|
|
15
|
+
testDir: resolve(process.cwd(), "test"),
|
|
16
|
+
fixture: "fixture",
|
|
17
|
+
configFile: "nuxt.config",
|
|
18
|
+
setupTimeout: isWindows ? 24e4 : 12e4,
|
|
19
|
+
teardownTimeout: isWindows ? 6e4 : 3e4,
|
|
20
|
+
serverStartTimeout: isWindows ? 12e4 : 6e4,
|
|
21
|
+
dev: !!JSON.parse(process.env.NUXT_TEST_DEV || "false"),
|
|
22
|
+
logLevel: 1,
|
|
23
|
+
server: true,
|
|
24
|
+
build: options.browser !== false || options.server !== false,
|
|
25
|
+
env: {},
|
|
26
|
+
nuxtConfig: { compatibilityDate: "2024-04-03" },
|
|
27
|
+
browserOptions: { type: "chromium" },
|
|
28
|
+
captureServerLogs: true
|
|
29
|
+
});
|
|
30
|
+
if (process.env.NUXT_TEST_LOG_LEVEL) _options.logLevel = Number(process.env.NUXT_TEST_LOG_LEVEL);
|
|
31
|
+
if (!_options.dev) _options.env.NODE_ENV ||= "production";
|
|
32
|
+
if (_options.host) {
|
|
33
|
+
_options.build = false;
|
|
34
|
+
_options.server = false;
|
|
35
|
+
}
|
|
36
|
+
if (process.env.VITEST === "true") _options.runner ||= "vitest";
|
|
37
|
+
else if (process.env.JEST_WORKER_ID) _options.runner ||= "jest";
|
|
38
|
+
else if (isBun) _options.runner ||= "bun";
|
|
39
|
+
return setTestContext({
|
|
40
|
+
options: _options,
|
|
41
|
+
url: withTrailingSlash(_options.host),
|
|
42
|
+
serverLogs: []
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
function useTestContext() {
|
|
46
|
+
recoverContextFromEnv();
|
|
47
|
+
if (!currentContext) throw new Error("No context is available. (Forgot calling setup or createContext?)");
|
|
48
|
+
return currentContext;
|
|
49
|
+
}
|
|
50
|
+
function setTestContext(context) {
|
|
51
|
+
currentContext = context;
|
|
52
|
+
return currentContext;
|
|
53
|
+
}
|
|
54
|
+
function isDev() {
|
|
55
|
+
return useTestContext().options.dev;
|
|
56
|
+
}
|
|
57
|
+
function recoverContextFromEnv() {
|
|
58
|
+
if (!currentContext && process.env.NUXT_TEST_CONTEXT) setTestContext(JSON.parse(process.env.NUXT_TEST_CONTEXT || "{}"));
|
|
59
|
+
}
|
|
60
|
+
function exposeContextToEnv() {
|
|
61
|
+
const { options, browser, url } = currentContext;
|
|
62
|
+
process.env.NUXT_TEST_CONTEXT = JSON.stringify({
|
|
63
|
+
options,
|
|
64
|
+
browser,
|
|
65
|
+
url
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
// src/e2e/server.ts
|
|
69
|
+
const globalFetch = globalThis.fetch || fetch;
|
|
70
|
+
/**
|
|
71
|
+
* Per-context promise that resolves once the server subprocess's output has
|
|
72
|
+
* been fully collected into `ctx.serverLogs`. Absent when log capture is off.
|
|
73
|
+
*/
|
|
74
|
+
const serverLogsCollected = /* @__PURE__ */ new WeakMap();
|
|
75
|
+
const MAX_START_ATTEMPTS = 5;
|
|
76
|
+
async function startServer(options = {}) {
|
|
77
|
+
const ctx = useTestContext();
|
|
78
|
+
await stopServer();
|
|
79
|
+
if (ctx.disposed) throw new Error("Test context has been torn down; refusing to start a server.");
|
|
80
|
+
const host = "127.0.0.1";
|
|
81
|
+
const capture = ctx.options.captureServerLogs !== false;
|
|
82
|
+
const stdio = capture ? "pipe" : "inherit";
|
|
83
|
+
const logLevel = String(options.logLevel ?? ctx.options.logLevel);
|
|
84
|
+
let lastError;
|
|
85
|
+
for (let attempt = 0; attempt < MAX_START_ATTEMPTS; attempt++) {
|
|
86
|
+
const port = ctx.options.port || await getRandomPort(host);
|
|
87
|
+
ctx.serverLogs = [];
|
|
88
|
+
ctx.url = `http://${host}:${port}/`;
|
|
89
|
+
serverLogsCollected.delete(ctx);
|
|
90
|
+
const startedAt = Date.now();
|
|
91
|
+
if (ctx.options.dev) {
|
|
92
|
+
const rootDir = ctx.nuxt.options.rootDir;
|
|
93
|
+
ctx.serverProcess = x("node", [resolve$1(distDir, "e2e/dev-server.mjs"), resolveNuxtCli(rootDir)], {
|
|
94
|
+
throwOnError: true,
|
|
95
|
+
nodeOptions: {
|
|
96
|
+
cwd: rootDir,
|
|
97
|
+
stdio,
|
|
98
|
+
env: {
|
|
99
|
+
...process.env,
|
|
100
|
+
_PORT: String(port),
|
|
101
|
+
PORT: String(port),
|
|
102
|
+
HOST: host,
|
|
103
|
+
NODE_ENV: "development",
|
|
104
|
+
CONSOLA_LEVEL: logLevel,
|
|
105
|
+
...ctx.options.env,
|
|
106
|
+
...options.env,
|
|
107
|
+
__NUXT_TEST_DEV_OVERRIDES__: serializeDevOverrides(ctx.options.nuxtConfig)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
} else {
|
|
112
|
+
const outputDir = ctx.nuxt ? ctx.nuxt.options.nitro.output.dir : ctx.options.nuxtConfig.nitro.output.dir;
|
|
113
|
+
ctx.serverProcess = x("node", [resolve$1(outputDir, "server/index.mjs")], {
|
|
114
|
+
throwOnError: true,
|
|
115
|
+
nodeOptions: {
|
|
116
|
+
stdio,
|
|
117
|
+
env: {
|
|
118
|
+
...process.env,
|
|
119
|
+
PORT: String(port),
|
|
120
|
+
HOST: host,
|
|
121
|
+
NODE_ENV: "test",
|
|
122
|
+
CONSOLA_LEVEL: logLevel,
|
|
123
|
+
...ctx.options.env,
|
|
124
|
+
...options.env
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
if (capture) serverLogsCollected.set(ctx, (async () => {
|
|
130
|
+
for await (const line of ctx.serverProcess) ctx.serverLogs.push(line);
|
|
131
|
+
})().catch(() => {}));
|
|
132
|
+
if (ctx.disposed) {
|
|
133
|
+
await stopServer();
|
|
134
|
+
throw new Error("Test context has been torn down; server was stopped again.");
|
|
135
|
+
}
|
|
136
|
+
try {
|
|
137
|
+
await waitForServer({
|
|
138
|
+
host,
|
|
139
|
+
port,
|
|
140
|
+
startedAt
|
|
141
|
+
});
|
|
142
|
+
return;
|
|
143
|
+
} catch (error) {
|
|
144
|
+
lastError = error;
|
|
145
|
+
if (ctx.options.port || !isPortInUseError(error, ctx)) throw error;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
throw lastError;
|
|
149
|
+
}
|
|
150
|
+
function serializeDevOverrides(nuxtConfig) {
|
|
151
|
+
const { value, omitted } = toSerializable(nuxtConfig);
|
|
152
|
+
if (omitted.length) console.warn(`[@nuxt/test-utils] These \`nuxtConfig\` values cannot be passed to the dev server and will be ignored: ${omitted.map((path) => `\`${path}\``).join(", ")}`);
|
|
153
|
+
return JSON.stringify(value ?? {});
|
|
154
|
+
}
|
|
155
|
+
function signalCode(proc) {
|
|
156
|
+
return proc.process?.signalCode ?? null;
|
|
157
|
+
}
|
|
158
|
+
function hasExited(proc) {
|
|
159
|
+
return !!proc && (proc.killed || proc.exitCode != null || signalCode(proc) !== null);
|
|
160
|
+
}
|
|
161
|
+
async function flushServerLogs(ctx) {
|
|
162
|
+
const collected = serverLogsCollected.get(ctx);
|
|
163
|
+
if (!collected) return;
|
|
164
|
+
let timer;
|
|
165
|
+
const timeout = new Promise((resolve) => {
|
|
166
|
+
timer = setTimeout(resolve, 1e3);
|
|
167
|
+
});
|
|
168
|
+
try {
|
|
169
|
+
await Promise.race([collected, timeout]);
|
|
170
|
+
} finally {
|
|
171
|
+
clearTimeout(timer);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function earlyExitError(ctx, elapsed) {
|
|
175
|
+
const proc = ctx.serverProcess;
|
|
176
|
+
const signal = signalCode(proc);
|
|
177
|
+
const message = `Server process exited before becoming ready (${[
|
|
178
|
+
signal ? `signal: ${signal}` : `exit code: ${proc.exitCode ?? "unknown"}`,
|
|
179
|
+
`killed: ${proc.killed}`,
|
|
180
|
+
`after ${elapsed}ms`,
|
|
181
|
+
`mode: ${ctx.options.dev ? "dev" : "built"}`
|
|
182
|
+
].join(", ")})`;
|
|
183
|
+
const output = ctx.serverLogs.slice(-30).join("\n");
|
|
184
|
+
if (output) return /* @__PURE__ */ new Error(`${message}\n--- last output from the server process ---\n${output}`);
|
|
185
|
+
if (!serverLogsCollected.has(ctx)) return /* @__PURE__ */ new Error(`${message}\n(no output captured: \`captureServerLogs\` is disabled)`);
|
|
186
|
+
return /* @__PURE__ */ new Error(`${message}\n(the server process produced no output)`);
|
|
187
|
+
}
|
|
188
|
+
function isPortInUseError(error, ctx) {
|
|
189
|
+
if (!(error instanceof Error)) return false;
|
|
190
|
+
return /EADDRINUSE|address already in use|is already in use/i.test(`${error.message}\n${ctx.serverLogs.join("\n")}`);
|
|
191
|
+
}
|
|
192
|
+
async function waitForServer({ host, port, startedAt }) {
|
|
193
|
+
const ctx = useTestContext();
|
|
194
|
+
const dev = ctx.options.dev;
|
|
195
|
+
const baseURL = ctx.nuxt?.options.app.baseURL ?? "/";
|
|
196
|
+
const deadline = Date.now() + ctx.options.serverStartTimeout;
|
|
197
|
+
await waitForPort(port, {
|
|
198
|
+
retries: 8,
|
|
199
|
+
host
|
|
200
|
+
}).catch(() => {});
|
|
201
|
+
let lastError;
|
|
202
|
+
let scannedLogs = 0;
|
|
203
|
+
while (Date.now() < deadline) {
|
|
204
|
+
while (scannedLogs < ctx.serverLogs.length) {
|
|
205
|
+
const match = /Port \d+ is in use, using port (\d+) instead/.exec(ctx.serverLogs[scannedLogs++]);
|
|
206
|
+
if (match) ctx.url = `http://${host}:${match[1]}/`;
|
|
207
|
+
}
|
|
208
|
+
if (hasExited(ctx.serverProcess)) {
|
|
209
|
+
await flushServerLogs(ctx);
|
|
210
|
+
const error = earlyExitError(ctx, Date.now() - startedAt);
|
|
211
|
+
await stopServer();
|
|
212
|
+
throw error;
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
const res = await globalFetch(joinURL(ctx.url, baseURL), { signal: AbortSignal.timeout(1e4) });
|
|
216
|
+
if (dev && res.status === 503) lastError = /* @__PURE__ */ new Error(`Server responded with ${res.status} ${res.statusText}`);
|
|
217
|
+
else if (dev && (await res.text()).includes("__NUXT_LOADING__")) lastError = /* @__PURE__ */ new Error("Dev server is still starting up");
|
|
218
|
+
else return;
|
|
219
|
+
} catch (e) {
|
|
220
|
+
lastError = e;
|
|
221
|
+
}
|
|
222
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
223
|
+
}
|
|
224
|
+
let error;
|
|
225
|
+
if (hasExited(ctx.serverProcess)) {
|
|
226
|
+
await flushServerLogs(ctx);
|
|
227
|
+
error = earlyExitError(ctx, Date.now() - startedAt);
|
|
228
|
+
} else {
|
|
229
|
+
await flushServerLogs(ctx);
|
|
230
|
+
const output = ctx.serverLogs.slice(-30).join("\n");
|
|
231
|
+
error = new Error(`Timeout (${ctx.options.serverStartTimeout}ms) waiting for ${dev ? "dev" : "built"} server to become ready at ${ctx.url}` + (output ? `\n--- last output from the server process ---\n${output}` : ""), { cause: lastError });
|
|
232
|
+
}
|
|
233
|
+
await stopServer();
|
|
234
|
+
throw error;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* On Windows there are no process groups, so `taskkill /T /F` is used to
|
|
238
|
+
* terminate the server process together with its descendants.
|
|
239
|
+
*/
|
|
240
|
+
function killProcessTree(pid) {
|
|
241
|
+
try {
|
|
242
|
+
xSync("taskkill", [
|
|
243
|
+
"/pid",
|
|
244
|
+
String(pid),
|
|
245
|
+
"/T",
|
|
246
|
+
"/F"
|
|
247
|
+
], {
|
|
248
|
+
throwOnError: false,
|
|
249
|
+
nodeOptions: { stdio: "ignore" }
|
|
250
|
+
});
|
|
251
|
+
} catch {}
|
|
252
|
+
}
|
|
253
|
+
async function stopServer() {
|
|
254
|
+
const ctx = useTestContext();
|
|
255
|
+
const proc = ctx.serverProcess;
|
|
256
|
+
if (!proc) return;
|
|
257
|
+
ctx.serverProcess = void 0;
|
|
258
|
+
const exited = Promise.resolve(proc).then(() => {}, () => {});
|
|
259
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
260
|
+
const pid = proc.pid;
|
|
261
|
+
if (isWindows && pid !== void 0) {
|
|
262
|
+
killProcessTree(pid);
|
|
263
|
+
await Promise.race([exited, sleep(5e3)]);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
proc.kill();
|
|
267
|
+
await Promise.race([exited, sleep(5e3)]);
|
|
268
|
+
if (proc.exitCode == null) {
|
|
269
|
+
proc.kill("SIGKILL");
|
|
270
|
+
await Promise.race([exited, sleep(5e3)]);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Returns the lines captured from the server subprocess's stdout/stderr since
|
|
275
|
+
* the last `startServer()` call (or `clearServerLogs()`).
|
|
276
|
+
* Only populated when `captureServerLogs` is `true` (the default).
|
|
277
|
+
*/
|
|
278
|
+
function getServerLogs() {
|
|
279
|
+
return useTestContext().serverLogs;
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Clears the captured server log lines. Useful between requests when you want
|
|
283
|
+
* to assert only on the logs produced by a specific operation.
|
|
284
|
+
*/
|
|
285
|
+
function clearServerLogs() {
|
|
286
|
+
useTestContext().serverLogs = [];
|
|
287
|
+
}
|
|
288
|
+
function fetch$1(path, options) {
|
|
289
|
+
return globalFetch(url(path), options);
|
|
290
|
+
}
|
|
291
|
+
const _$fetch = createFetch({ fetch: globalFetch });
|
|
292
|
+
const $fetch = function $fetch(path, options) {
|
|
293
|
+
return _$fetch(url(path), options);
|
|
294
|
+
};
|
|
295
|
+
function url(path) {
|
|
296
|
+
const ctx = useTestContext();
|
|
297
|
+
if (!ctx.url) throw new Error("url is not available (is server option enabled?)");
|
|
298
|
+
if (path.startsWith(ctx.url)) return path;
|
|
299
|
+
return joinURL(ctx.url, path);
|
|
300
|
+
}
|
|
301
|
+
export { startServer as a, createTestContext as c, recoverContextFromEnv as d, setTestContext as f, getServerLogs as i, exposeContextToEnv as l, clearServerLogs as n, stopServer as o, useTestContext as p, fetch$1 as r, url as s, $fetch as t, isDev as u };
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { RenderFunction } from "vue";
|
|
2
|
+
import "@vue/test-utils";
|
|
3
|
+
import { RouteLocationRaw } from "vue-router";
|
|
4
|
+
type AnySetupState = Record<string, any>;
|
|
5
|
+
type GetDefinedSetupState<Component, SetupReturn = Component extends {
|
|
6
|
+
setup?: (...args: infer _) => infer R;
|
|
7
|
+
} ? Awaited<R> : never, IsOptionalReturn = [Extract<SetupReturn, undefined>] extends [never] ? false : true, DefinedSetupState = Exclude<SetupReturn, void | RenderFunction>> = IsOptionalReturn extends true ? Partial<DefinedSetupState> : DefinedSetupState;
|
|
8
|
+
type GetSetupState<Component, DefinedSetupState = GetDefinedSetupState<Component>> = [DefinedSetupState] extends [never] ? AnySetupState : DefinedSetupState;
|
|
9
|
+
type SetupState<C = unknown> = GetSetupState<C> & AnySetupState;
|
|
10
|
+
type WrapperFnComponent<Fn> = Fn extends ((c: infer C, o: infer _) => infer _) ? C : never;
|
|
11
|
+
type WrapperFnOption<Fn> = Fn extends ((c: WrapperFnComponent<Fn>, o: infer O) => infer _) ? O : never;
|
|
12
|
+
type WrapperFnResult<Fn> = Fn extends ((c: WrapperFnComponent<Fn>, o: WrapperFnOption<Fn>) => infer R) ? R : never;
|
|
13
|
+
type WrapperSuspendedAdditionalOptions = {
|
|
14
|
+
/**
|
|
15
|
+
* The initial route, or false to skip the initial route change.
|
|
16
|
+
* @default '/'
|
|
17
|
+
*/
|
|
18
|
+
route?: RouteLocationRaw | false;
|
|
19
|
+
/**
|
|
20
|
+
* Enable spy component setup state.
|
|
21
|
+
* @default false
|
|
22
|
+
* @example
|
|
23
|
+
* ```ts
|
|
24
|
+
* const wrapper = await mountSuspended(CustomRandom, { spy: true })
|
|
25
|
+
* vi.mocked(wrapper.setupState.getRandom).mockImplementation(() => 200)
|
|
26
|
+
* await wrapper.find('#random').trigger('click')
|
|
27
|
+
* expect(wrapper.setupState.getRandom).toHaveBeenCalled()
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
spy?: boolean;
|
|
31
|
+
scoped?: boolean;
|
|
32
|
+
};
|
|
33
|
+
type WrapperSuspendedOptions<Fn> = WrapperFnOption<Fn> & WrapperSuspendedAdditionalOptions;
|
|
34
|
+
type WrapperSuspendedResult<Fn, C> = WrapperFnResult<Fn> & {
|
|
35
|
+
/**
|
|
36
|
+
* The return value of the component setup.
|
|
37
|
+
*/
|
|
38
|
+
setupState: SetupState<C>;
|
|
39
|
+
};
|
|
40
|
+
declare global {
|
|
41
|
+
interface Window {
|
|
42
|
+
__cleanup?: Array<() => void>;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export { WrapperSuspendedResult as i, WrapperSuspendedAdditionalOptions as n, WrapperSuspendedOptions as r, SetupState as t };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as cleanupAll, n as patchWrapperSetProps, r as wrapperSuspended } from "./suspended-UrdAzOmb.mjs";
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import { Suspense, effectScope, getCurrentInstance, h, nextTick, onErrorCaptured, reactive } from "vue";
|
|
2
|
+
import { vi } from "vitest";
|
|
3
|
+
import { defineComponent, h as h$1, tryUseNuxtApp, useNuxtApp, useRouter } from "#imports";
|
|
4
|
+
import NuxtRoot from "#build/root-component.mjs";
|
|
5
|
+
// src/runtime-utils/components/RouterLink.ts
|
|
6
|
+
function getUseLink(nuxtApp) {
|
|
7
|
+
const linkComponent = nuxtApp.vueApp._context.components.RouterLink;
|
|
8
|
+
if (!linkComponent || typeof linkComponent !== "object") return void 0;
|
|
9
|
+
if (typeof linkComponent.useLink !== "function") return void 0;
|
|
10
|
+
return linkComponent.useLink.bind(linkComponent);
|
|
11
|
+
}
|
|
12
|
+
const RouterLink = defineComponent({
|
|
13
|
+
functional: true,
|
|
14
|
+
props: {
|
|
15
|
+
to: {
|
|
16
|
+
type: [String, Object],
|
|
17
|
+
required: true
|
|
18
|
+
},
|
|
19
|
+
custom: Boolean,
|
|
20
|
+
replace: Boolean,
|
|
21
|
+
activeClass: String,
|
|
22
|
+
exactActiveClass: String,
|
|
23
|
+
ariaCurrentValue: String
|
|
24
|
+
},
|
|
25
|
+
setup: (props, { slots }) => {
|
|
26
|
+
const useLink = getUseLink(useNuxtApp());
|
|
27
|
+
if (!useLink) {
|
|
28
|
+
const navigate = () => {};
|
|
29
|
+
const router = useRouter();
|
|
30
|
+
return () => {
|
|
31
|
+
const route = router.resolve(props.to);
|
|
32
|
+
return props.custom ? slots.default?.({
|
|
33
|
+
href: route.href,
|
|
34
|
+
navigate,
|
|
35
|
+
route
|
|
36
|
+
}) : h$1("a", {
|
|
37
|
+
href: route.href,
|
|
38
|
+
onClick: (e) => {
|
|
39
|
+
e.preventDefault();
|
|
40
|
+
}
|
|
41
|
+
}, slots);
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
const link = useLink(props);
|
|
45
|
+
return () => {
|
|
46
|
+
const route = link.route.value;
|
|
47
|
+
const href = link.href.value;
|
|
48
|
+
const isActive = link.isActive.value;
|
|
49
|
+
const isExactActive = link.isExactActive.value;
|
|
50
|
+
return props.custom ? slots.default?.({
|
|
51
|
+
href,
|
|
52
|
+
navigate: link.navigate,
|
|
53
|
+
route,
|
|
54
|
+
isActive,
|
|
55
|
+
isExactActive
|
|
56
|
+
}) : h$1("a", {
|
|
57
|
+
href,
|
|
58
|
+
onClick: (e) => {
|
|
59
|
+
e.preventDefault();
|
|
60
|
+
return link.navigate(e);
|
|
61
|
+
}
|
|
62
|
+
}, slots);
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
// src/runtime-utils/utils/suspended.ts
|
|
67
|
+
function resolveVueApp() {
|
|
68
|
+
return tryUseNuxtApp()?.vueApp || globalThis.__unctx__.get("nuxt-app").tryUse().vueApp;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* `wrapper.setProps` delegates to this `@ohos-ports/vue-test-utils` internal when the wrapper is the mount
|
|
72
|
+
* root, which is the case for the component we mount around the suspended component.
|
|
73
|
+
*/
|
|
74
|
+
function patchWrapperSetProps(wrapper, setProps) {
|
|
75
|
+
Object.assign(wrapper, { __setProps: setProps });
|
|
76
|
+
}
|
|
77
|
+
function cleanupAll() {
|
|
78
|
+
for (const fn of (window.__cleanup || []).splice(0)) fn();
|
|
79
|
+
}
|
|
80
|
+
function addCleanup(fn) {
|
|
81
|
+
window.__cleanup ||= [];
|
|
82
|
+
window.__cleanup.push(fn);
|
|
83
|
+
}
|
|
84
|
+
function removeCleanup(fn) {
|
|
85
|
+
const index = window.__cleanup?.indexOf(fn) ?? -1;
|
|
86
|
+
if (index !== -1) window.__cleanup.splice(index, 1);
|
|
87
|
+
}
|
|
88
|
+
function runEffectScope(fn, register) {
|
|
89
|
+
const scope = effectScope();
|
|
90
|
+
register(() => scope.stop());
|
|
91
|
+
return scope.run(fn);
|
|
92
|
+
}
|
|
93
|
+
function wrapperSuspended(component, options, { wrapperFn, wrappedRender = (fn) => fn, suspendedHelperName, clonedComponentName, stubRouterLink = true }) {
|
|
94
|
+
const vueApp = resolveVueApp();
|
|
95
|
+
const ownCleanups = [];
|
|
96
|
+
function registerCleanup(fn) {
|
|
97
|
+
ownCleanups.push(fn);
|
|
98
|
+
addCleanup(fn);
|
|
99
|
+
}
|
|
100
|
+
function cleanup() {
|
|
101
|
+
for (const fn of ownCleanups.splice(0)) {
|
|
102
|
+
removeCleanup(fn);
|
|
103
|
+
fn();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const { props = {}, attrs = {} } = options;
|
|
107
|
+
const { route = "/", scoped = false, spy = false, ...wrapperFnOptions } = options;
|
|
108
|
+
const { render: componentRender, setup: componentSetup, ...componentRest } = component;
|
|
109
|
+
let wrappedInstance = null;
|
|
110
|
+
let setupContext;
|
|
111
|
+
let setupState = {};
|
|
112
|
+
const setProps = reactive({});
|
|
113
|
+
function patchInstanceAppContext() {
|
|
114
|
+
const app = getCurrentInstance()?.appContext.app;
|
|
115
|
+
if (!app) return;
|
|
116
|
+
for (const [key, value] of Object.entries(vueApp)) {
|
|
117
|
+
if (key in app) continue;
|
|
118
|
+
app[key] = value;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const ClonedComponent = {
|
|
122
|
+
components: {},
|
|
123
|
+
...component,
|
|
124
|
+
name: clonedComponentName,
|
|
125
|
+
async setup(props, instanceContext) {
|
|
126
|
+
const currentInstance = getCurrentInstance();
|
|
127
|
+
if (currentInstance) currentInstance.emit = (event, ...args) => {
|
|
128
|
+
setupContext.emit(event, ...args);
|
|
129
|
+
};
|
|
130
|
+
if (!componentSetup) return;
|
|
131
|
+
let result = scoped ? await runEffectScope(() => componentSetup(props, setupContext), registerCleanup) : await componentSetup(props, setupContext);
|
|
132
|
+
if (wrappedInstance?.exposed) instanceContext.expose(wrappedInstance.exposed);
|
|
133
|
+
if (result && typeof result === "object") {
|
|
134
|
+
if (spy) result = vi.mockObject(result, { spy: true });
|
|
135
|
+
setupState = result;
|
|
136
|
+
} else setupState = {};
|
|
137
|
+
return result;
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
const SuspendedHelper = {
|
|
141
|
+
name: suspendedHelperName,
|
|
142
|
+
render: () => "",
|
|
143
|
+
async setup() {
|
|
144
|
+
if (route) await useRouter().replace(route);
|
|
145
|
+
return () => h(ClonedComponent, {
|
|
146
|
+
...props,
|
|
147
|
+
...setProps,
|
|
148
|
+
...attrs
|
|
149
|
+
}, setupContext.slots);
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
return new Promise((resolve, reject) => {
|
|
153
|
+
let isMountSettled = false;
|
|
154
|
+
const wrapper = wrapperFn({
|
|
155
|
+
inheritAttrs: false,
|
|
156
|
+
__cssModules: componentRest.__cssModules,
|
|
157
|
+
setup: (props, ctx) => {
|
|
158
|
+
patchInstanceAppContext();
|
|
159
|
+
wrappedInstance = getCurrentInstance();
|
|
160
|
+
setupContext = ctx;
|
|
161
|
+
const nuxtRootSetupResult = runEffectScope(() => NuxtRoot.setup(props, {
|
|
162
|
+
...ctx,
|
|
163
|
+
expose: () => {}
|
|
164
|
+
}), registerCleanup);
|
|
165
|
+
onErrorCaptured((error, ...args) => {
|
|
166
|
+
if (isMountSettled) return;
|
|
167
|
+
isMountSettled = true;
|
|
168
|
+
try {
|
|
169
|
+
wrappedInstance?.appContext.config.errorHandler?.(error, ...args);
|
|
170
|
+
reject(error);
|
|
171
|
+
} catch (error) {
|
|
172
|
+
reject(error);
|
|
173
|
+
}
|
|
174
|
+
return false;
|
|
175
|
+
});
|
|
176
|
+
return nuxtRootSetupResult;
|
|
177
|
+
},
|
|
178
|
+
render: wrappedRender(() => h(Suspense, { onResolve: () => nextTick().then(() => {
|
|
179
|
+
if (isMountSettled) return;
|
|
180
|
+
isMountSettled = true;
|
|
181
|
+
wrapper.setupState = setupState;
|
|
182
|
+
resolve({
|
|
183
|
+
wrapper,
|
|
184
|
+
setProps: (props) => {
|
|
185
|
+
Object.assign(setProps, props);
|
|
186
|
+
},
|
|
187
|
+
cleanup
|
|
188
|
+
});
|
|
189
|
+
}) }, { default: () => h(SuspendedHelper) }))
|
|
190
|
+
}, {
|
|
191
|
+
...wrapperFnOptions,
|
|
192
|
+
global: mergeComponentMountingGlobalOptions(wrapperFnOptions.global, {
|
|
193
|
+
config: { globalProperties: makeAllPropertiesEnumerable(vueApp.config.globalProperties) },
|
|
194
|
+
directives: vueApp._context.directives,
|
|
195
|
+
provide: vueApp._context.provides,
|
|
196
|
+
stubs: {
|
|
197
|
+
Suspense: false,
|
|
198
|
+
[SuspendedHelper.name]: false,
|
|
199
|
+
[ClonedComponent.name]: false
|
|
200
|
+
},
|
|
201
|
+
components: {
|
|
202
|
+
...vueApp._context.components,
|
|
203
|
+
...stubRouterLink ? { RouterLink } : {}
|
|
204
|
+
}
|
|
205
|
+
})
|
|
206
|
+
});
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
function mergeComponentMountingGlobalOptions(options = {}, defaults = {}) {
|
|
210
|
+
const compilerOptions = {
|
|
211
|
+
...defaults.config?.compilerOptions,
|
|
212
|
+
...options.config?.compilerOptions
|
|
213
|
+
};
|
|
214
|
+
return {
|
|
215
|
+
...options,
|
|
216
|
+
mixins: [...defaults.mixins || [], ...options.mixins || []],
|
|
217
|
+
stubs: {
|
|
218
|
+
...defaults.stubs,
|
|
219
|
+
...Array.isArray(options.stubs) ? Object.fromEntries(options.stubs.map((n) => [n, true])) : options.stubs
|
|
220
|
+
},
|
|
221
|
+
plugins: [...defaults.plugins || [], ...options.plugins || []],
|
|
222
|
+
components: {
|
|
223
|
+
...defaults.components,
|
|
224
|
+
...options.components
|
|
225
|
+
},
|
|
226
|
+
provide: {
|
|
227
|
+
...defaults.provide,
|
|
228
|
+
...options.provide
|
|
229
|
+
},
|
|
230
|
+
mocks: {
|
|
231
|
+
...defaults.mocks,
|
|
232
|
+
...options.mocks
|
|
233
|
+
},
|
|
234
|
+
config: {
|
|
235
|
+
...defaults.config,
|
|
236
|
+
...options.config,
|
|
237
|
+
...Object.keys(compilerOptions).length ? { compilerOptions } : void 0,
|
|
238
|
+
globalProperties: {
|
|
239
|
+
...defaults.config?.globalProperties,
|
|
240
|
+
...options.config?.globalProperties
|
|
241
|
+
}
|
|
242
|
+
},
|
|
243
|
+
directives: {
|
|
244
|
+
...defaults.directives,
|
|
245
|
+
...options.directives
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
function makeAllPropertiesEnumerable(target) {
|
|
250
|
+
return {
|
|
251
|
+
...target,
|
|
252
|
+
...Object.fromEntries(Object.getOwnPropertyNames(target).map((key) => [key, target[key]]))
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
export { patchWrapperSetProps as n, wrapperSuspended as r, cleanupAll as t };
|