@vitest/browser 4.0.16 → 4.0.18

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/dist/index.js CHANGED
@@ -18,7 +18,7 @@ import { PNG } from 'pngjs';
18
18
  import pm from 'pixelmatch';
19
19
  import { WebSocketServer } from 'ws';
20
20
 
21
- var version = "4.0.16";
21
+ var version = "4.0.18";
22
22
 
23
23
  const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
24
24
  function normalizeWindowsPath(input = "") {
@@ -695,6 +695,7 @@ async function resolveOrchestrator(globalServer, url, res) {
695
695
  __VITEST_TYPE__: "\"orchestrator\"",
696
696
  __VITEST_SESSION_ID__: JSON.stringify(sessionId),
697
697
  __VITEST_TESTER_ID__: "\"none\"",
698
+ __VITEST_OTEL_CARRIER__: url.searchParams.get("otelCarrier") ?? "null",
698
699
  __VITEST_PROVIDED_CONTEXT__: JSON.stringify(stringify(browserProject.project.getProvidedContext())),
699
700
  __VITEST_API_TOKEN__: JSON.stringify(globalServer.vitest.config.api.token)
700
701
  });
@@ -790,6 +791,7 @@ async function resolveTester(globalServer, url, res, next) {
790
791
  __VITEST_TYPE__: "\"tester\"",
791
792
  __VITEST_METHOD__: JSON.stringify("none"),
792
793
  __VITEST_SESSION_ID__: JSON.stringify(sessionId),
794
+ __VITEST_OTEL_CARRIER__: JSON.stringify(null),
793
795
  __VITEST_TESTER_ID__: JSON.stringify(crypto.randomUUID()),
794
796
  __VITEST_PROVIDED_CONTEXT__: "{}",
795
797
  __VITEST_API_TOKEN__: JSON.stringify(globalServer.vitest.config.api.token)
@@ -1139,6 +1141,11 @@ var BrowserPlugin = (parentServer, base = "/") => {
1139
1141
  if (vueTestUtils) {
1140
1142
  include.push("@vue/test-utils");
1141
1143
  }
1144
+ const otelConfig = project.config.experimental.openTelemetry;
1145
+ if (otelConfig?.enabled && otelConfig.browserSdkPath) {
1146
+ entries.push(otelConfig.browserSdkPath);
1147
+ include.push("@opentelemetry/api");
1148
+ }
1142
1149
  return {
1143
1150
  define,
1144
1151
  resolve: { dedupe: ["vitest"] },
@@ -2224,9 +2231,20 @@ function asyncTimeout(timeout) {
2224
2231
  });
2225
2232
  }
2226
2233
 
2234
+ /**
2235
+ * Browser command that compares a screenshot against a stored reference.
2236
+ *
2237
+ * The comparison workflow is organized as follows:
2238
+ *
2239
+ * 1. Load existing reference (if any)
2240
+ * 2. Capture a stable screenshot (retrying until the page stops changing)
2241
+ * 3. Determine the outcome based on capture results and update settings
2242
+ * 4. Write any necessary files (new references, diffs)
2243
+ * 5. Return result for the test runner
2244
+ */
2227
2245
  const screenshotMatcher = async (context, name, testName, options) => {
2228
2246
  if (!context.testPath) {
2229
- throw new Error(`Cannot compare screenshots without a test path`);
2247
+ throw new Error("Cannot compare screenshots without a test path");
2230
2248
  }
2231
2249
  const { element } = options;
2232
2250
  const { codec, comparator, paths, resolvedOptions: { comparatorOptions, screenshotOptions, timeout } } = resolveOptions({
@@ -2236,9 +2254,8 @@ const screenshotMatcher = async (context, name, testName, options) => {
2236
2254
  options
2237
2255
  });
2238
2256
  const referenceFile = await readFile$1(paths.reference).catch(() => null);
2239
- const reference = referenceFile && await codec.decode(await readFile$1(paths.reference), {});
2240
- const abortController = new AbortController();
2241
- const stableScreenshot = getStableScreenshots({
2257
+ const reference = referenceFile && await codec.decode(referenceFile, {});
2258
+ const screenshotResult = await waitForStableScreenshot({
2242
2259
  codec,
2243
2260
  comparator,
2244
2261
  comparatorOptions,
@@ -2246,115 +2263,189 @@ const screenshotMatcher = async (context, name, testName, options) => {
2246
2263
  element,
2247
2264
  name: `${Date.now()}-${basename(paths.reference)}`,
2248
2265
  reference,
2249
- screenshotOptions,
2250
- signal: abortController.signal
2266
+ screenshotOptions
2267
+ }, timeout);
2268
+ const outcome = await determineOutcome({
2269
+ reference,
2270
+ screenshot: screenshotResult && screenshotResult.actual,
2271
+ retries: screenshotResult?.retries ?? 0,
2272
+ updateSnapshot: context.project.serializedConfig.snapshotOptions.updateSnapshot,
2273
+ paths,
2274
+ comparator,
2275
+ comparatorOptions
2251
2276
  });
2252
- const value = await (timeout === 0 ? stableScreenshot : Promise.race([stableScreenshot, asyncTimeout(timeout).finally(() => {
2253
- abortController.abort();
2254
- })]));
2255
- // case #01
2256
- // - impossible to get a stable screenshot to compare against
2257
- // - fail
2258
- if (value === null || value.actual === null) {
2277
+ await performSideEffects(outcome, codec);
2278
+ return buildOutput(outcome, timeout);
2279
+ };
2280
+ /**
2281
+ * Core comparison logic that produces a {@linkcode MatchOutcome}.
2282
+ *
2283
+ * All branching logic lives here. This is the single source of truth for "what happened".
2284
+ *
2285
+ * The outcome carries all data needed by {@linkcode performSideEffects} and {@linkcode buildOutput}.
2286
+ */
2287
+ async function determineOutcome({ comparator, comparatorOptions, paths, reference, retries, screenshot, updateSnapshot }) {
2288
+ if (screenshot === null) {
2259
2289
  return {
2260
- pass: false,
2261
- reference: referenceFile && {
2262
- path: paths.reference,
2263
- width: reference.metadata.width,
2264
- height: reference.metadata.height
2265
- },
2266
- actual: null,
2267
- diff: null,
2268
- message: `Could not capture a stable screenshot within ${timeout}ms.`
2290
+ type: "unstable-screenshot",
2291
+ reference: reference && {
2292
+ image: reference,
2293
+ path: paths.reference
2294
+ }
2269
2295
  };
2270
2296
  }
2271
- const { updateSnapshot } = context.project.serializedConfig.snapshotOptions;
2272
- // if there's no reference or if we want to update snapshots, we have to finish the comparison early
2297
+ // no reference to compare against - create one based on update settings
2273
2298
  if (reference === null || updateSnapshot === "all") {
2274
- const shouldCreateReference = updateSnapshot !== "none";
2275
- const referencePath = shouldCreateReference ? paths.reference : paths.diffs.reference;
2276
- await writeScreenshot(referencePath, await codec.encode(value.actual, {}));
2277
- // case #02
2278
- // - got a stable screenshot, but there is no reference and we don't want to update screenshots
2279
- // - fail
2280
- if (updateSnapshot !== "all") {
2299
+ if (updateSnapshot === "all") {
2281
2300
  return {
2282
- pass: false,
2301
+ type: "update-reference",
2283
2302
  reference: {
2284
- path: referencePath,
2285
- width: value.actual.metadata.width,
2286
- height: value.actual.metadata.height
2287
- },
2288
- actual: null,
2289
- diff: null,
2290
- message: `No existing reference screenshot found${shouldCreateReference ? "; a new one was created. Review it before running tests again." : "."}`
2303
+ image: screenshot,
2304
+ path: paths.reference
2305
+ }
2291
2306
  };
2292
2307
  }
2293
- // case #03
2294
- // - got a stable screenshot, there is no reference, but we want to update screenshots
2295
- // - pass
2296
- return { pass: true };
2297
- }
2298
- // case #04
2299
- // - got a stable screenshot with no retries and there's a reference
2300
- // - pass
2301
- if (referenceFile && value.retries === 0) {
2302
- return { pass: true };
2303
- }
2304
- const finalResult = await comparator(reference, value.actual, {
2308
+ const location = updateSnapshot === "none" ? "diffs" : "reference";
2309
+ return {
2310
+ type: "missing-reference",
2311
+ location,
2312
+ reference: {
2313
+ image: screenshot,
2314
+ path: location === "reference" ? paths.reference : paths.diffs.reference
2315
+ }
2316
+ };
2317
+ }
2318
+ // first capture matched reference (used as baseline) - no further comparison needed
2319
+ if (retries === 0) {
2320
+ return { type: "matched-immediately" };
2321
+ }
2322
+ const comparisonResult = await comparator(reference, screenshot, {
2305
2323
  createDiff: true,
2306
2324
  ...comparatorOptions
2307
2325
  });
2308
- if (finalResult.pass === false && finalResult.diff !== null) {
2309
- const diff = await codec.encode({
2310
- data: finalResult.diff,
2311
- metadata: {
2312
- height: reference.metadata.height,
2313
- width: reference.metadata.width
2314
- }
2315
- }, {});
2316
- await writeScreenshot(paths.diffs.diff, diff);
2317
- }
2318
- // case #05
2319
- // - reference matches stable screenshot
2320
- // - pass
2321
- if (finalResult.pass === true) {
2322
- return { pass: true };
2323
- }
2324
- const actual = await codec.encode(value.actual, {});
2325
- await writeScreenshot(paths.diffs.actual, actual);
2326
- // case #06
2327
- // - fallback, reference does NOT match stable screenshot
2328
- // - fail
2326
+ if (comparisonResult.pass) {
2327
+ return { type: "matched-after-comparison" };
2328
+ }
2329
2329
  return {
2330
- pass: false,
2330
+ type: "mismatch",
2331
2331
  reference: {
2332
- path: paths.reference,
2333
- width: reference.metadata.width,
2334
- height: reference.metadata.height
2332
+ image: reference,
2333
+ path: paths.reference
2335
2334
  },
2336
2335
  actual: {
2337
- path: paths.diffs.actual,
2338
- width: value.actual.metadata.width,
2339
- height: value.actual.metadata.height
2336
+ image: screenshot,
2337
+ path: paths.diffs.actual
2338
+ },
2339
+ diff: comparisonResult.diff && {
2340
+ image: {
2341
+ data: comparisonResult.diff,
2342
+ metadata: reference.metadata
2343
+ },
2344
+ path: paths.diffs.diff
2340
2345
  },
2341
- diff: finalResult.diff && paths.diffs.diff,
2342
- message: `Screenshot does not match the stored reference.${finalResult.message === null ? "" : `\n${finalResult.message}`}`
2346
+ message: comparisonResult.message
2343
2347
  };
2344
- };
2345
- async function writeScreenshot(path, image) {
2346
- try {
2347
- await mkdir(dirname(path), { recursive: true });
2348
- await writeFile$1(path, image);
2349
- } catch {
2350
- throw new Error("Couldn't write file to fs");
2348
+ }
2349
+ /**
2350
+ * Writes files to disk based on the outcome.
2351
+ *
2352
+ * Only `missing-reference`, `update-reference`, and `mismatch` write files. Successful matches produce no side effects.
2353
+ */
2354
+ async function performSideEffects(outcome, codec) {
2355
+ switch (outcome.type) {
2356
+ case "missing-reference":
2357
+ case "update-reference": {
2358
+ await writeScreenshot(outcome.reference.path, await codec.encode(outcome.reference.image, {}));
2359
+ break;
2360
+ }
2361
+ case "mismatch": {
2362
+ await writeScreenshot(outcome.actual.path, await codec.encode(outcome.actual.image, {}));
2363
+ if (outcome.diff) {
2364
+ await writeScreenshot(outcome.diff.path, await codec.encode(outcome.diff.image, {}));
2365
+ }
2366
+ break;
2367
+ }
2351
2368
  }
2352
2369
  }
2353
2370
  /**
2371
+ * Transforms a {@linkcode MatchOutcome} into the output format expected by the test runner.
2372
+ *
2373
+ * Maps each outcome to a pass/fail result with metadata and error messages.
2374
+ */
2375
+ function buildOutput(outcome, timeout) {
2376
+ switch (outcome.type) {
2377
+ case "unstable-screenshot": return {
2378
+ pass: false,
2379
+ reference: outcome.reference && {
2380
+ path: outcome.reference.path,
2381
+ width: outcome.reference.image.metadata.width,
2382
+ height: outcome.reference.image.metadata.height
2383
+ },
2384
+ actual: null,
2385
+ diff: null,
2386
+ message: `Could not capture a stable screenshot within ${timeout}ms.`
2387
+ };
2388
+ case "missing-reference": {
2389
+ return {
2390
+ pass: false,
2391
+ reference: {
2392
+ path: outcome.reference.path,
2393
+ width: outcome.reference.image.metadata.width,
2394
+ height: outcome.reference.image.metadata.height
2395
+ },
2396
+ actual: null,
2397
+ diff: null,
2398
+ message: outcome.location === "reference" ? "No existing reference screenshot found; a new one was created. Review it before running tests again." : "No existing reference screenshot found."
2399
+ };
2400
+ }
2401
+ case "update-reference":
2402
+ case "matched-immediately":
2403
+ case "matched-after-comparison": return { pass: true };
2404
+ case "mismatch": return {
2405
+ pass: false,
2406
+ reference: {
2407
+ path: outcome.reference.path,
2408
+ width: outcome.reference.image.metadata.width,
2409
+ height: outcome.reference.image.metadata.height
2410
+ },
2411
+ actual: {
2412
+ path: outcome.actual.path,
2413
+ width: outcome.actual.image.metadata.width,
2414
+ height: outcome.actual.image.metadata.height
2415
+ },
2416
+ diff: outcome.diff && {
2417
+ path: outcome.diff.path,
2418
+ width: outcome.diff.image.metadata.width,
2419
+ height: outcome.diff.image.metadata.height
2420
+ },
2421
+ message: `Screenshot does not match the stored reference.${outcome.message ? `\n${outcome.message}` : ""}`
2422
+ };
2423
+ default: {
2424
+ return {
2425
+ pass: false,
2426
+ actual: null,
2427
+ reference: null,
2428
+ diff: null,
2429
+ message: `Outcome (${outcome.type}) not handled. This is a bug in Vitest. Please, open an issue with reproduction.`
2430
+ };
2431
+ }
2432
+ }
2433
+ }
2434
+ /**
2435
+ * Captures a stable screenshot with timeout handling.
2436
+ *
2437
+ * Wraps {@linkcode getStableScreenshot} with an abort controller that triggers when the timeout expires. Returns `null` if the page never stabilizes.
2438
+ */
2439
+ async function waitForStableScreenshot(options, timeout) {
2440
+ const abortController = new AbortController();
2441
+ const stableScreenshot = getStableScreenshot(options, abortController.signal);
2442
+ const result = await (timeout === 0 ? stableScreenshot : Promise.race([stableScreenshot, asyncTimeout(timeout).finally(() => abortController.abort())]));
2443
+ return result;
2444
+ }
2445
+ /**
2354
2446
  * Takes screenshots repeatedly until the page reaches a visually stable state.
2355
2447
  *
2356
- * This function compares consecutive screenshots and continues taking new ones
2357
- * until two consecutive screenshots match according to the provided comparator.
2448
+ * This function compares consecutive screenshots and continues taking new ones until two consecutive screenshots match according to the provided comparator.
2358
2449
  *
2359
2450
  * The process works as follows:
2360
2451
  *
@@ -2364,10 +2455,9 @@ async function writeScreenshot(path, image) {
2364
2455
  * 4. If they don't match, it continues with the newer screenshot as the baseline
2365
2456
  * 5. Repeats until stability is achieved or the operation is aborted
2366
2457
  *
2367
- * @returns `Promise` resolving to an object containing the retry count and
2368
- * final screenshot
2458
+ * @returns `Promise` resolving to an object containing the retry count and final screenshot
2369
2459
  */
2370
- async function getStableScreenshots({ codec, context, comparator, comparatorOptions, element, name, reference, screenshotOptions, signal }) {
2460
+ async function getStableScreenshot({ codec, context, comparator, comparatorOptions, element, name, reference, screenshotOptions }, signal) {
2371
2461
  const screenshotArgument = {
2372
2462
  codec,
2373
2463
  context,
@@ -2382,12 +2472,12 @@ async function getStableScreenshots({ codec, context, comparator, comparatorOpti
2382
2472
  decodedBaseline = takeDecodedScreenshot(screenshotArgument);
2383
2473
  }
2384
2474
  const [image1, image2] = await Promise.all([decodedBaseline, takeDecodedScreenshot(screenshotArgument)]);
2385
- const comparatorResult = (await comparator(image1, image2, {
2475
+ const isStable = (await comparator(image1, image2, {
2386
2476
  ...comparatorOptions,
2387
2477
  createDiff: false
2388
2478
  })).pass;
2389
2479
  decodedBaseline = image2;
2390
- if (comparatorResult) {
2480
+ if (isStable) {
2391
2481
  break;
2392
2482
  }
2393
2483
  retries += 1;
@@ -2397,6 +2487,15 @@ async function getStableScreenshots({ codec, context, comparator, comparatorOpti
2397
2487
  actual: await decodedBaseline
2398
2488
  };
2399
2489
  }
2490
+ /** Writes encoded images to disk, creating parent directories as needed. */
2491
+ async function writeScreenshot(path, image) {
2492
+ try {
2493
+ await mkdir(dirname(path), { recursive: true });
2494
+ await writeFile$1(path, image);
2495
+ } catch (cause) {
2496
+ throw new Error("Couldn't write file to fs", { cause });
2497
+ }
2498
+ }
2400
2499
 
2401
2500
  var builtinCommands = {
2402
2501
  readFile,
@@ -3242,6 +3341,7 @@ const createBrowserServer = async (options) => {
3242
3341
  let cacheDir;
3243
3342
  const vite = await createViteServer({
3244
3343
  ...project.options,
3344
+ define: project.config.viteDefine,
3245
3345
  base: "/",
3246
3346
  root: project.config.root,
3247
3347
  logLevel,
package/dist/locators.js CHANGED
@@ -1 +1 @@
1
- export{L as Locator,n as convertElementToCssSelector,q as getByAltTextSelector,r as getByLabelSelector,t as getByPlaceholderSelector,u as getByRoleSelector,v as getByTestIdSelector,w as getByTextSelector,x as getByTitleSelector,o as getIframeScale,p as processTimeoutOptions,s as selectorEngine}from"./index-CEutxZap.js";import"vitest/browser";import"vitest/internal/browser";
1
+ export{L as Locator,n as convertElementToCssSelector,q as getByAltTextSelector,r as getByLabelSelector,t as getByPlaceholderSelector,u as getByRoleSelector,v as getByTestIdSelector,w as getByTextSelector,x as getByTitleSelector,o as getIframeScale,p as processTimeoutOptions,s as selectorEngine}from"./index-D6m36C6U.js";import"vitest/browser";import"vitest/internal/browser";
@@ -14,7 +14,7 @@ export type ScreenshotMatcherOutput = Promise<{
14
14
  pass: false;
15
15
  reference: ScreenshotData | null;
16
16
  actual: ScreenshotData | null;
17
- diff: string | null;
17
+ diff: ScreenshotData | null;
18
18
  message: string;
19
19
  } | {
20
20
  pass: true;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vitest/browser",
3
3
  "type": "module",
4
- "version": "4.0.16",
4
+ "version": "4.0.18",
5
5
  "description": "Browser running for Vitest",
6
6
  "license": "MIT",
7
7
  "funding": "https://opencollective.com/vitest",
@@ -51,7 +51,7 @@
51
51
  "providers"
52
52
  ],
53
53
  "peerDependencies": {
54
- "vitest": "4.0.16"
54
+ "vitest": "4.0.18"
55
55
  },
56
56
  "dependencies": {
57
57
  "magic-string": "^0.30.21",
@@ -60,10 +60,11 @@
60
60
  "sirv": "^3.0.2",
61
61
  "tinyrainbow": "^3.0.3",
62
62
  "ws": "^8.18.3",
63
- "@vitest/mocker": "4.0.16",
64
- "@vitest/utils": "4.0.16"
63
+ "@vitest/mocker": "4.0.18",
64
+ "@vitest/utils": "4.0.18"
65
65
  },
66
66
  "devDependencies": {
67
+ "@opentelemetry/api": "^1.9.0",
67
68
  "@testing-library/user-event": "^14.6.1",
68
69
  "@types/pngjs": "^6.0.5",
69
70
  "@types/ws": "^8.18.1",
@@ -72,8 +73,8 @@
72
73
  "ivya": "^1.7.0",
73
74
  "mime": "^4.1.0",
74
75
  "pathe": "^2.0.3",
75
- "@vitest/runner": "4.0.16",
76
- "vitest": "4.0.16"
76
+ "@vitest/runner": "4.0.18",
77
+ "vitest": "4.0.18"
77
78
  },
78
79
  "scripts": {
79
80
  "typecheck": "tsc -p ./src/client/tsconfig.json --noEmit",
@@ -81,7 +82,7 @@
81
82
  "build": "premove dist && pnpm build:node && pnpm build:client",
82
83
  "build:client": "vite build src/client",
83
84
  "build:node": "rollup -c",
84
- "dev:client": "vite build src/client --watch",
85
+ "dev:client": "node --watch-preserve-output --watch-path src/client scripts/build-client.js",
85
86
  "dev:node": "rollup -c --watch --watch.include 'src/**'",
86
87
  "dev": "premove dist && pnpm run --stream '/^dev:/'"
87
88
  }