@vitest/browser 2.0.0-beta.9 → 2.0.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.
@@ -1,696 +0,0 @@
1
- function __vite__mapDeps(indexes) {
2
- if (!__vite__mapDeps.viteFileDeps) {
3
- __vite__mapDeps.viteFileDeps = []
4
- }
5
- return indexes.map((i) => __vite__mapDeps.viteFileDeps[i])
6
- }
7
- var __defProp = Object.defineProperty;
8
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
- var __publicField = (obj, key, value) => {
10
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
11
- return value;
12
- };
13
- import { i as importId, b as getConfig, e as rpc$1, _ as __vitePreload, f as extname, g as getBrowserState, a as channel, c as client, l as loadSafeRpc, o as onCancel } from "./rpc-DBukiZYG.js";
14
- function getType(value) {
15
- return Object.prototype.toString.apply(value).slice(8, -1);
16
- }
17
- function showPopupWarning(name, value, defaultValue) {
18
- return (...params) => {
19
- const formatedParams = params.map((p) => JSON.stringify(p)).join(", ");
20
- console.warn(`Vitest encountered a \`${name}(${formatedParams})\` call that it cannot handle by default, so it returned \`${value}\`. Read more in https://vitest.dev/guide/browser#thread-blocking-dialogs.
21
- If needed, mock the \`${name}\` call manually like:
22
-
23
- \`\`\`
24
- import { expect, vi } from "vitest"
25
-
26
- vi.spyOn(window, "${name}")${defaultValue ? `.mockReturnValue(${JSON.stringify(defaultValue)})` : ""}
27
- ${name}(${formatedParams})
28
- expect(${name}).toHaveBeenCalledWith(${formatedParams})
29
- \`\`\``);
30
- return value;
31
- };
32
- }
33
- function setupDialogsSpy() {
34
- globalThis.alert = showPopupWarning("alert", void 0);
35
- globalThis.confirm = showPopupWarning("confirm", false, true);
36
- globalThis.prompt = showPopupWarning("prompt", null, "your value");
37
- }
38
- const { Date: Date$1, console: console$1 } = globalThis;
39
- async function setupConsoleLogSpy() {
40
- const { stringify, format, inspect } = await importId("vitest/utils");
41
- const { log, info, error, dir, dirxml, trace, time, timeEnd, timeLog, warn, debug: debug2, count, countReset } = console$1;
42
- const formatInput = (input) => {
43
- if (input instanceof Node)
44
- return stringify(input);
45
- return format(input);
46
- };
47
- const processLog = (args) => args.map(formatInput).join(" ");
48
- const sendLog = (type, content, disableStack) => {
49
- var _a, _b, _c;
50
- if (content.startsWith("[vite]"))
51
- return;
52
- const unknownTestId = "__vitest__unknown_test__";
53
- const taskId = ((_b = (_a = globalThis.__vitest_worker__) == null ? void 0 : _a.current) == null ? void 0 : _b.id) ?? unknownTestId;
54
- const origin = getConfig().printConsoleTrace && !disableStack ? (_c = new Error("STACK_TRACE").stack) == null ? void 0 : _c.split("\n").slice(1).join("\n") : void 0;
55
- rpc$1().sendLog({
56
- origin,
57
- content,
58
- browser: true,
59
- time: Date$1.now(),
60
- taskId,
61
- type,
62
- size: content.length
63
- });
64
- };
65
- const stdout = (base) => (...args) => {
66
- sendLog("stdout", processLog(args));
67
- return base(...args);
68
- };
69
- const stderr = (base) => (...args) => {
70
- sendLog("stderr", processLog(args));
71
- return base(...args);
72
- };
73
- console$1.log = stdout(log);
74
- console$1.debug = stdout(debug2);
75
- console$1.info = stdout(info);
76
- console$1.error = stderr(error);
77
- console$1.warn = stderr(warn);
78
- console$1.dir = (item, options) => {
79
- sendLog("stdout", inspect(item, options));
80
- return dir(item, options);
81
- };
82
- console$1.dirxml = (...args) => {
83
- sendLog("stdout", processLog(args));
84
- return dirxml(...args);
85
- };
86
- console$1.trace = (...args) => {
87
- var _a;
88
- const content = processLog(args);
89
- const error2 = new Error("$$Trace");
90
- const stack = (error2.stack || "").split("\n").slice(((_a = error2.stack) == null ? void 0 : _a.includes("$$Trace")) ? 2 : 1).join("\n");
91
- sendLog("stderr", `${content}
92
- ${stack}`, true);
93
- return trace(...args);
94
- };
95
- const timeLabels = {};
96
- console$1.time = (label = "default") => {
97
- const now2 = performance.now();
98
- time(label);
99
- timeLabels[label] = now2;
100
- };
101
- console$1.timeLog = (label = "default") => {
102
- timeLog(label);
103
- if (!(label in timeLabels))
104
- sendLog("stderr", `Timer "${label}" does not exist`);
105
- else
106
- sendLog("stdout", `${label}: ${timeLabels[label]} ms`);
107
- };
108
- console$1.timeEnd = (label = "default") => {
109
- const end = performance.now();
110
- timeEnd(label);
111
- const start = timeLabels[label];
112
- if (!(label in timeLabels)) {
113
- sendLog("stderr", `Timer "${label}" does not exist`);
114
- } else if (start) {
115
- const duration = end - start;
116
- sendLog("stdout", `${label}: ${duration} ms`);
117
- }
118
- };
119
- const countLabels = {};
120
- console$1.count = (label = "default") => {
121
- const counter = (countLabels[label] ?? 0) + 1;
122
- countLabels[label] = counter;
123
- sendLog("stdout", `${label}: ${counter}`);
124
- return count(label);
125
- };
126
- console$1.countReset = (label = "default") => {
127
- countLabels[label] = 0;
128
- return countReset(label);
129
- };
130
- }
131
- class VitestBrowserSnapshotEnvironment {
132
- getVersion() {
133
- return "1";
134
- }
135
- getHeader() {
136
- return `// Vitest Snapshot v${this.getVersion()}, https://vitest.dev/guide/snapshot.html`;
137
- }
138
- readSnapshotFile(filepath) {
139
- return rpc().readSnapshotFile(filepath);
140
- }
141
- saveSnapshotFile(filepath, snapshot) {
142
- return rpc().saveSnapshotFile(filepath, snapshot);
143
- }
144
- resolvePath(filepath) {
145
- return rpc().resolveSnapshotPath(filepath);
146
- }
147
- resolveRawPath(testPath, rawPath) {
148
- return rpc().resolveSnapshotRawPath(testPath, rawPath);
149
- }
150
- removeSnapshotFile(filepath) {
151
- return rpc().removeSnapshotFile(filepath);
152
- }
153
- }
154
- function rpc() {
155
- return globalThis.__vitest_worker__.rpc;
156
- }
157
- const browserHashMap = /* @__PURE__ */ new Map();
158
- function createBrowserRunner(runnerClass, coverageModule) {
159
- return class BrowserTestRunner extends runnerClass {
160
- constructor(options) {
161
- super(options.config);
162
- __publicField(this, "config");
163
- __publicField(this, "hashMap", browserHashMap);
164
- __publicField(this, "onAfterRunTask", async (task) => {
165
- var _a, _b, _c;
166
- await ((_a = super.onAfterRunTask) == null ? void 0 : _a.call(this, task));
167
- if (this.config.bail && ((_b = task.result) == null ? void 0 : _b.state) === "fail") {
168
- const previousFailures = await rpc$1().getCountOfFailedTests();
169
- const currentFailures = 1 + previousFailures;
170
- if (currentFailures >= this.config.bail) {
171
- rpc$1().onCancel("test-failure");
172
- (_c = this.onCancel) == null ? void 0 : _c.call(this, "test-failure");
173
- }
174
- }
175
- });
176
- __publicField(this, "onAfterRunFiles", async (files) => {
177
- var _a, _b;
178
- await rpc$1().invalidateMocks();
179
- await ((_a = super.onAfterRunFiles) == null ? void 0 : _a.call(this, files));
180
- const coverage = await ((_b = coverageModule == null ? void 0 : coverageModule.takeCoverage) == null ? void 0 : _b.call(coverageModule));
181
- if (coverage) {
182
- await rpc$1().onAfterSuiteRun({
183
- coverage,
184
- transformMode: "web",
185
- projectName: this.config.name
186
- });
187
- }
188
- });
189
- __publicField(this, "onCollected", async (files) => {
190
- if (this.config.includeTaskLocation) {
191
- try {
192
- await updateFilesLocations(files);
193
- } catch (_) {
194
- }
195
- }
196
- return rpc$1().onCollected(files);
197
- });
198
- __publicField(this, "onTaskUpdate", (task) => {
199
- return rpc$1().onTaskUpdate(task);
200
- });
201
- __publicField(this, "importFile", async (filepath) => {
202
- let [test, hash] = this.hashMap.get(filepath) ?? [false, ""];
203
- if (hash === "") {
204
- hash = Date.now().toString();
205
- this.hashMap.set(filepath, [false, hash]);
206
- }
207
- const base = this.config.base || "/";
208
- const prefix = `${base}${/^\w:/.test(filepath) ? "@fs/" : ""}`;
209
- const query = `${test ? "browserv" : "v"}=${hash}`;
210
- const importpath = `${prefix}${filepath}?${query}`.replace(/\/+/g, "/");
211
- await __vitePreload(() => import(importpath), true ? __vite__mapDeps([]) : void 0);
212
- });
213
- this.config = options.config;
214
- }
215
- };
216
- }
217
- let cachedRunner = null;
218
- async function initiateRunner(config) {
219
- if (cachedRunner)
220
- return cachedRunner;
221
- const [
222
- { VitestTestRunner, NodeBenchmarkRunner },
223
- { takeCoverageInsideWorker, loadDiffConfig, loadSnapshotSerializers }
224
- ] = await Promise.all([
225
- importId("vitest/runners"),
226
- importId("vitest/browser")
227
- ]);
228
- const runnerClass = config.mode === "test" ? VitestTestRunner : NodeBenchmarkRunner;
229
- const BrowserRunner = createBrowserRunner(runnerClass, {
230
- takeCoverage: () => takeCoverageInsideWorker(config.coverage, { executeId: importId })
231
- });
232
- if (!config.snapshotOptions.snapshotEnvironment)
233
- config.snapshotOptions.snapshotEnvironment = new VitestBrowserSnapshotEnvironment();
234
- const runner = new BrowserRunner({
235
- config
236
- });
237
- const executor = { executeId: importId };
238
- const [diffOptions] = await Promise.all([
239
- loadDiffConfig(config, executor),
240
- loadSnapshotSerializers(config, executor)
241
- ]);
242
- runner.config.diffOptions = diffOptions;
243
- cachedRunner = runner;
244
- return runner;
245
- }
246
- async function updateFilesLocations(files) {
247
- const { loadSourceMapUtils } = await importId("vitest/utils");
248
- const { TraceMap, originalPositionFor } = await loadSourceMapUtils();
249
- const promises = files.map(async (file) => {
250
- const result = await rpc$1().getBrowserFileSourceMap(file.filepath);
251
- if (!result)
252
- return null;
253
- const traceMap = new TraceMap(result);
254
- function updateLocation(task) {
255
- if (task.location) {
256
- const { line, column } = originalPositionFor(traceMap, task.location);
257
- if (line != null && column != null)
258
- task.location = { line, column: task.each ? column : column + 1 };
259
- }
260
- if ("tasks" in task)
261
- task.tasks.forEach(updateLocation);
262
- }
263
- file.tasks.forEach(updateLocation);
264
- return null;
265
- });
266
- await Promise.all(promises);
267
- }
268
- const now = Date.now;
269
- class VitestBrowserClientMocker {
270
- constructor() {
271
- __publicField(this, "queue", /* @__PURE__ */ new Set());
272
- __publicField(this, "mocks", {});
273
- __publicField(this, "factories", {});
274
- __publicField(this, "spyModule");
275
- }
276
- setSpyModule(mod) {
277
- this.spyModule = mod;
278
- }
279
- async importActual(id, importer) {
280
- const resolved = await rpc$1().resolveId(id, importer);
281
- if (resolved == null)
282
- throw new Error(`[vitest] Cannot resolve ${id} imported from ${importer}`);
283
- const ext = extname(resolved.id);
284
- const base = getBrowserState().config.base || "/";
285
- const url2 = new URL(`/@id${base}${resolved.id}`, location.href);
286
- const query = `_vitest_original&ext.${ext}`;
287
- const actualUrl = `${url2.pathname}${url2.search ? `${url2.search}&${query}` : `?${query}`}${url2.hash}`;
288
- return getBrowserState().wrapModule(() => __vitePreload(() => import(actualUrl), true ? __vite__mapDeps([]) : void 0));
289
- }
290
- async importMock(rawId, importer) {
291
- await this.prepare();
292
- const { resolvedId, type, mockPath } = await rpc$1().resolveMock(rawId, importer);
293
- const factoryReturn = this.get(resolvedId);
294
- if (factoryReturn)
295
- return factoryReturn;
296
- if (this.factories[resolvedId])
297
- return await this.resolve(resolvedId);
298
- const base = getBrowserState().config.base || "/";
299
- if (type === "redirect") {
300
- const url22 = new URL(`/@id${base}${mockPath}`, location.href);
301
- return __vitePreload(() => import(url22.toString()), true ? __vite__mapDeps([]) : void 0);
302
- }
303
- const url2 = new URL(`/@id${base}${resolvedId}`, location.href);
304
- const query = url2.search ? `${url2.search}&t=${now()}` : `?t=${now()}`;
305
- const moduleObject = await __vitePreload(() => import(`${url2.pathname}${query}${url2.hash}`), true ? __vite__mapDeps([]) : void 0);
306
- return this.mockObject(moduleObject);
307
- }
308
- getMockContext() {
309
- return { callstack: null };
310
- }
311
- get(id) {
312
- return this.mocks[id];
313
- }
314
- async resolve(id) {
315
- const factory = this.factories[id];
316
- if (!factory)
317
- throw new Error(`Cannot resolve ${id} mock: no factory provided`);
318
- try {
319
- this.mocks[id] = await factory();
320
- return this.mocks[id];
321
- } catch (err) {
322
- const vitestError = new Error(
323
- '[vitest] There was an error when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. Read more: https://vitest.dev/api/vi.html#vi-mock'
324
- );
325
- vitestError.cause = err;
326
- throw vitestError;
327
- }
328
- }
329
- queueMock(id, importer, factory) {
330
- const promise = rpc$1().queueMock(id, importer, !!factory).then((id2) => {
331
- this.factories[id2] = factory;
332
- }).finally(() => {
333
- this.queue.delete(promise);
334
- });
335
- this.queue.add(promise);
336
- }
337
- queueUnmock(id, importer) {
338
- const promise = rpc$1().queueUnmock(id, importer).then((id2) => {
339
- delete this.factories[id2];
340
- }).finally(() => {
341
- this.queue.delete(promise);
342
- });
343
- this.queue.add(promise);
344
- }
345
- async prepare() {
346
- if (!this.queue.size)
347
- return;
348
- await Promise.all([...this.queue.values()]);
349
- }
350
- // TODO: move this logic into a util(?)
351
- mockObject(object, mockExports = {}) {
352
- const finalizers = new Array();
353
- const refs = new RefTracker();
354
- const define = (container, key, value) => {
355
- try {
356
- container[key] = value;
357
- return true;
358
- } catch {
359
- return false;
360
- }
361
- };
362
- const mockPropertiesOf = (container, newContainer) => {
363
- const containerType = /* @__PURE__ */ getType(container);
364
- const isModule = containerType === "Module" || !!container.__esModule;
365
- for (const { key: property, descriptor } of getAllMockableProperties(container, isModule)) {
366
- if (!isModule && descriptor.get) {
367
- try {
368
- Object.defineProperty(newContainer, property, descriptor);
369
- } catch (error) {
370
- }
371
- continue;
372
- }
373
- if (isSpecialProp(property, containerType))
374
- continue;
375
- const value = container[property];
376
- const refId = refs.getId(value);
377
- if (refId !== void 0) {
378
- finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId)));
379
- continue;
380
- }
381
- const type = /* @__PURE__ */ getType(value);
382
- if (Array.isArray(value)) {
383
- define(newContainer, property, []);
384
- continue;
385
- }
386
- const isFunction = type.includes("Function") && typeof value === "function";
387
- if ((!isFunction || value.__isMockFunction) && type !== "Object" && type !== "Module") {
388
- define(newContainer, property, value);
389
- continue;
390
- }
391
- if (!define(newContainer, property, isFunction ? value : {}))
392
- continue;
393
- if (isFunction) {
394
- let mockFunction = function() {
395
- if (this instanceof newContainer[property]) {
396
- for (const { key, descriptor: descriptor2 } of getAllMockableProperties(this, false)) {
397
- if (descriptor2.get)
398
- continue;
399
- const value2 = this[key];
400
- const type2 = /* @__PURE__ */ getType(value2);
401
- const isFunction2 = type2.includes("Function") && typeof value2 === "function";
402
- if (isFunction2) {
403
- const original = this[key];
404
- const mock2 = spyModule.vi.spyOn(this, key).mockImplementation(original);
405
- mock2.mockRestore = () => {
406
- mock2.mockReset();
407
- mock2.mockImplementation(original);
408
- return mock2;
409
- };
410
- }
411
- }
412
- }
413
- };
414
- const spyModule = this.spyModule;
415
- if (!spyModule)
416
- throw new Error("[vitest] `spyModule` is not defined. This is Vitest error. Please open a new issue with reproduction.");
417
- const mock = spyModule.vi.spyOn(newContainer, property).mockImplementation(mockFunction);
418
- mock.mockRestore = () => {
419
- mock.mockReset();
420
- mock.mockImplementation(mockFunction);
421
- return mock;
422
- };
423
- Object.defineProperty(newContainer[property], "length", { value: 0 });
424
- }
425
- refs.track(value, newContainer[property]);
426
- mockPropertiesOf(value, newContainer[property]);
427
- }
428
- };
429
- const mockedObject = mockExports;
430
- mockPropertiesOf(object, mockedObject);
431
- for (const finalizer of finalizers)
432
- finalizer();
433
- return mockedObject;
434
- }
435
- }
436
- function isSpecialProp(prop, parentType) {
437
- return parentType.includes("Function") && typeof prop === "string" && ["arguments", "callee", "caller", "length", "name"].includes(prop);
438
- }
439
- class RefTracker {
440
- constructor() {
441
- __publicField(this, "idMap", /* @__PURE__ */ new Map());
442
- __publicField(this, "mockedValueMap", /* @__PURE__ */ new Map());
443
- }
444
- getId(value) {
445
- return this.idMap.get(value);
446
- }
447
- getMockedValue(id) {
448
- return this.mockedValueMap.get(id);
449
- }
450
- track(originalValue, mockedValue) {
451
- const newId = this.idMap.size;
452
- this.idMap.set(originalValue, newId);
453
- this.mockedValueMap.set(newId, mockedValue);
454
- return newId;
455
- }
456
- }
457
- function getAllMockableProperties(obj, isModule) {
458
- const allProps = /* @__PURE__ */ new Map();
459
- let curr = obj;
460
- do {
461
- if (curr === Object.prototype || curr === Function.prototype || curr === RegExp.prototype)
462
- break;
463
- collectOwnProperties(curr, (key) => {
464
- const descriptor = Object.getOwnPropertyDescriptor(curr, key);
465
- if (descriptor)
466
- allProps.set(key, { key, descriptor });
467
- });
468
- } while (curr = Object.getPrototypeOf(curr));
469
- if (isModule && !allProps.has("default") && "default" in obj) {
470
- const descriptor = Object.getOwnPropertyDescriptor(obj, "default");
471
- if (descriptor)
472
- allProps.set("default", { key: "default", descriptor });
473
- }
474
- return Array.from(allProps.values());
475
- }
476
- function collectOwnProperties(obj, collector) {
477
- const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
478
- Object.getOwnPropertyNames(obj).forEach(collect);
479
- Object.getOwnPropertySymbols(obj).forEach(collect);
480
- }
481
- function on(event, listener) {
482
- window.addEventListener(event, listener);
483
- return () => window.removeEventListener(event, listener);
484
- }
485
- function serializeError(unhandledError) {
486
- return {
487
- ...unhandledError,
488
- name: unhandledError.name,
489
- message: unhandledError.message,
490
- stack: String(unhandledError.stack)
491
- };
492
- }
493
- async function defaultErrorReport(type, unhandledError) {
494
- const error = serializeError(unhandledError);
495
- channel.postMessage({
496
- type: "error",
497
- files: getBrowserState().runningFiles,
498
- error,
499
- errorType: type,
500
- id: getBrowserState().iframeId
501
- });
502
- }
503
- function catchWindowErrors(cb) {
504
- let userErrorListenerCount = 0;
505
- function throwUnhandlerError(e) {
506
- if (userErrorListenerCount === 0 && e.error != null)
507
- cb(e);
508
- else
509
- console.error(e.error);
510
- }
511
- const addEventListener = window.addEventListener.bind(window);
512
- const removeEventListener = window.removeEventListener.bind(window);
513
- window.addEventListener("error", throwUnhandlerError);
514
- window.addEventListener = function(...args) {
515
- if (args[0] === "error")
516
- userErrorListenerCount++;
517
- return addEventListener.apply(this, args);
518
- };
519
- window.removeEventListener = function(...args) {
520
- if (args[0] === "error" && userErrorListenerCount)
521
- userErrorListenerCount--;
522
- return removeEventListener.apply(this, args);
523
- };
524
- return function clearErrorHandlers() {
525
- window.removeEventListener("error", throwUnhandlerError);
526
- };
527
- }
528
- function registerUnhandledErrors() {
529
- const stopErrorHandler2 = catchWindowErrors((e) => defaultErrorReport("Error", e.error));
530
- const stopRejectionHandler = on("unhandledrejection", (e) => defaultErrorReport("Unhandled Rejection", e.reason));
531
- return () => {
532
- stopErrorHandler2();
533
- stopRejectionHandler();
534
- };
535
- }
536
- function registerUnexpectedErrors(rpc2) {
537
- catchWindowErrors((event) => reportUnexpectedError(rpc2, "Error", event.error));
538
- on("unhandledrejection", (event) => reportUnexpectedError(rpc2, "Unhandled Rejection", event.reason));
539
- }
540
- async function reportUnexpectedError(rpc2, type, error) {
541
- const { processError } = await importId("vitest/browser");
542
- const processedError = processError(error);
543
- await rpc2.onUnhandledError(processedError, type);
544
- }
545
- const stopErrorHandler = registerUnhandledErrors();
546
- const url = new URL(location.href);
547
- const reloadStart = url.searchParams.get("__reloadStart");
548
- function debug(...args) {
549
- const debug2 = getConfig().env.VITEST_BROWSER_DEBUG;
550
- if (debug2 && debug2 !== "false")
551
- client.rpc.debug(...args.map(String));
552
- }
553
- async function tryCall(fn) {
554
- try {
555
- return await fn();
556
- } catch (err) {
557
- const now2 = Date.now();
558
- const canTry = !reloadStart || now2 - Number(reloadStart) < 3e4;
559
- const errorStack = (() => {
560
- var _a;
561
- if (!err)
562
- return null;
563
- return ((_a = err.stack) == null ? void 0 : _a.includes(err.message)) ? err.stack : `${err.message}
564
- ${err.stack}`;
565
- })();
566
- debug("failed to resolve runner", "trying again:", canTry, "time is", now2, "reloadStart is", reloadStart, ":\n", errorStack);
567
- if (!canTry) {
568
- const error = serializeError(new Error("Vitest failed to load its runner after 30 seconds."));
569
- error.cause = serializeError(err);
570
- await client.rpc.onUnhandledError(error, "Preload Error");
571
- return false;
572
- }
573
- if (!reloadStart) {
574
- const newUrl = new URL(location.href);
575
- newUrl.searchParams.set("__reloadStart", now2.toString());
576
- debug("set the new url because reload start is not set to", newUrl);
577
- location.href = newUrl.toString();
578
- } else {
579
- debug("reload the iframe because reload start is set", location.href);
580
- location.reload();
581
- }
582
- }
583
- }
584
- async function prepareTestEnvironment(files) {
585
- debug("trying to resolve runner", `${reloadStart}`);
586
- const config = getConfig();
587
- const viteClientPath = `${config.base || "/"}@vite/client`;
588
- await __vitePreload(() => import(viteClientPath), true ? __vite__mapDeps([]) : void 0);
589
- const rpc2 = await loadSafeRpc(client);
590
- stopErrorHandler();
591
- registerUnexpectedErrors(rpc2);
592
- const providedContext = await client.rpc.getProvidedContext();
593
- const state = {
594
- ctx: {
595
- pool: "browser",
596
- worker: "./browser.js",
597
- workerId: 1,
598
- config,
599
- projectName: config.name || "",
600
- files,
601
- environment: {
602
- name: "browser",
603
- options: null
604
- },
605
- providedContext,
606
- invalidates: []
607
- },
608
- onCancel,
609
- mockMap: /* @__PURE__ */ new Map(),
610
- config,
611
- environment: {
612
- name: "browser",
613
- transformMode: "web",
614
- setup() {
615
- throw new Error("Not called in the browser");
616
- }
617
- },
618
- moduleCache: getBrowserState().moduleCache,
619
- rpc: rpc2,
620
- durations: {
621
- environment: 0,
622
- prepare: performance.now()
623
- },
624
- providedContext
625
- };
626
- globalThis.__vitest_browser__ = true;
627
- globalThis.__vitest_worker__ = state;
628
- const mocker = new VitestBrowserClientMocker();
629
- globalThis.__vitest_mocker__ = mocker;
630
- await setupConsoleLogSpy();
631
- setupDialogsSpy();
632
- const version = url.searchParams.get("browserv") || "";
633
- files.forEach((filename) => {
634
- const currentVersion = browserHashMap.get(filename);
635
- if (!currentVersion || currentVersion[1] !== version)
636
- browserHashMap.set(filename, [true, version]);
637
- });
638
- const [runner, { startTests, setupCommonEnv, Vitest }] = await Promise.all([
639
- initiateRunner(config),
640
- importId("vitest/browser")
641
- ]);
642
- mocker.setSpyModule(Vitest);
643
- onCancel.then((reason) => {
644
- var _a;
645
- (_a = runner.onCancel) == null ? void 0 : _a.call(runner, reason);
646
- });
647
- return {
648
- runner,
649
- config,
650
- state,
651
- setupCommonEnv,
652
- startTests
653
- };
654
- }
655
- function done(files) {
656
- channel.postMessage({
657
- type: "done",
658
- filenames: files,
659
- id: getBrowserState().iframeId
660
- });
661
- }
662
- async function runTests(files) {
663
- await client.waitForConnection();
664
- debug("client is connected to ws server");
665
- let preparedData;
666
- try {
667
- preparedData = await tryCall(() => prepareTestEnvironment(files));
668
- } catch (error) {
669
- debug("data cannot be loaded because it threw an error");
670
- await client.rpc.onUnhandledError(serializeError(error), "Preload Error");
671
- done(files);
672
- return;
673
- }
674
- if (preparedData === false) {
675
- debug("data cannot be loaded, finishing the test");
676
- done(files);
677
- return;
678
- }
679
- if (!preparedData) {
680
- debug("page is reloading, waiting for the next run");
681
- return;
682
- }
683
- debug("runner resolved successfully");
684
- const { config, runner, state, setupCommonEnv, startTests } = preparedData;
685
- state.durations.prepare = performance.now() - state.durations.prepare;
686
- try {
687
- await setupCommonEnv(config);
688
- for (const file of files)
689
- await startTests([file], runner);
690
- } finally {
691
- state.environmentTeardownRun = true;
692
- debug("finished running tests");
693
- done(files);
694
- }
695
- }
696
- window.__vitest_browser_runner__.runTests = runTests;