@vitest/browser-playwright 4.1.12 → 5.1.0

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.d.ts CHANGED
@@ -2,7 +2,7 @@ import { CustomComparatorsRegistry } from '@vitest/browser';
2
2
  export { defineBrowserCommand } from '@vitest/browser';
3
3
  import { Page, Frame, FrameLocator, BrowserContext, CDPSession, Browser, LaunchOptions, ConnectOptions, BrowserContextOptions } from 'playwright';
4
4
  import { ScreenshotMatcherOptions, ScreenshotComparatorRegistry, Locator } from 'vitest/browser';
5
- import { BrowserProvider, BrowserModuleMocker, TestProject, CDPSession as CDPSession$1, BrowserProviderOption } from 'vitest/node';
5
+ import { BrowserProvider, BrowserModuleMocker, TestProject, CDPSession as CDPSession$1, BrowserProviderCloseOptions, BrowserProviderOption } from 'vitest/node';
6
6
 
7
7
  declare const playwrightBrowsers: readonly ["firefox", "webkit", "chromium"];
8
8
  type PlaywrightBrowser = (typeof playwrightBrowsers)[number];
@@ -57,13 +57,17 @@ declare class PlaywrightBrowserProvider implements BrowserProvider {
57
57
  mocker: BrowserModuleMocker;
58
58
  browserName: PlaywrightBrowser;
59
59
  private browserPromise;
60
+ private launchOptionsJson;
60
61
  private closing;
62
+ private armedContexts;
61
63
  tracingContexts: Set<string>;
62
64
  pendingTraces: Map<string, string>;
63
65
  initScripts: string[];
64
66
  constructor(project: TestProject, options: PlaywrightProviderOptions);
65
67
  private onSIGTERM;
66
68
  private openBrowser;
69
+ private armInterception;
70
+ private probeInterception;
67
71
  private createMocker;
68
72
  private createContext;
69
73
  private getContextOptions;
@@ -80,7 +84,8 @@ declare class PlaywrightBrowserProvider implements BrowserProvider {
80
84
  }): Promise<void>;
81
85
  private _throwIfClosing;
82
86
  getCDPSession(sessionid: string): Promise<CDPSession$1>;
83
- close(): Promise<void>;
87
+ close(options?: BrowserProviderCloseOptions): Promise<void>;
88
+ private closeContexts;
84
89
  }
85
90
  declare module "vitest/node" {
86
91
  interface BrowserCommandContext {
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { asLocator, parseKeyDef, resolveScreenshotPath, assertBrowserApiWrite, assertBrowserFileAccess, defineBrowserProvider } from '@vitest/browser';
1
+ import { parseKeyDef, resolveScreenshotPath, assertBrowserApiWrite, assertBrowserFileAccess, defineBrowserProvider } from '@vitest/browser';
2
2
  export { defineBrowserCommand } from '@vitest/browser';
3
3
  import { createManualModuleSource } from '@vitest/mocker/node';
4
4
  import c from 'tinyrainbow';
5
- import { createDebugger, isCSSRequest } from 'vitest/node';
5
+ import { createDebugger, BrowserConnectionError, isCSSRequest } from 'vitest/node';
6
6
  import { mkdir, unlink } from 'node:fs/promises';
7
7
  import { fileURLToPath } from 'node:url';
8
8
 
@@ -169,13 +169,21 @@ const basename = function(p, extension) {
169
169
  return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
170
170
  };
171
171
 
172
+ async function focusIframe(context) {
173
+ const frame = await context.frame();
174
+ await frame.evaluate(() => {
175
+ if (!document.activeElement || document.activeElement.ownerDocument !== document || document.activeElement === document.body) {
176
+ window.focus();
177
+ }
178
+ });
179
+ }
172
180
  // strip iframe locator part from the trace description e.g.
173
181
  // - locator('[data-vitest="true"]').contentFrame().getByRole('button')
174
182
  // ⇓
175
183
  // - getByRole('button')
176
- function getDescribedLocator(context, selector) {
177
- const locator = context.iframe.locator(selector);
178
- return typeof locator.describe === "function" ? locator.describe(asLocator("javascript", selector)) : locator;
184
+ function getDescribedLocator(context, { locator, selector }) {
185
+ const iframeLocator = context.iframe.locator(selector);
186
+ return typeof iframeLocator.describe === "function" ? iframeLocator.describe(locator) : iframeLocator;
179
187
  }
180
188
 
181
189
  const clear = async (context, selector) => {
@@ -184,12 +192,15 @@ const clear = async (context, selector) => {
184
192
  };
185
193
 
186
194
  const click = async (context, selector, options = {}) => {
195
+ await focusIframe(context);
187
196
  await getDescribedLocator(context, selector).click(options);
188
197
  };
189
198
  const dblClick = async (context, selector, options = {}) => {
199
+ await focusIframe(context);
190
200
  await getDescribedLocator(context, selector).dblclick(options);
191
201
  };
192
202
  const tripleClick = async (context, selector, options = {}) => {
203
+ await focusIframe(context);
193
204
  await getDescribedLocator(context, selector).click({
194
205
  ...options,
195
206
  clickCount: 3
@@ -198,7 +209,7 @@ const tripleClick = async (context, selector, options = {}) => {
198
209
 
199
210
  const dragAndDrop = async (context, source, target, options_) => {
200
211
  const frame = await context.frame();
201
- await frame.dragAndDrop(source, target, options_);
212
+ await frame.dragAndDrop(source.selector, target.selector, options_);
202
213
  };
203
214
 
204
215
  const fill = async (context, selector, text, options = {}) => {
@@ -211,8 +222,7 @@ const hover = async (context, selector, options = {}) => {
211
222
  };
212
223
 
213
224
  const keyboard = async (context, text, state) => {
214
- const frame = await context.frame();
215
- await frame.evaluate(focusIframe);
225
+ await focusIframe(context);
216
226
  const pressed = new Set(state.unreleased);
217
227
  await keyboardImplementation(pressed, context.provider, context.sessionId, text, async () => {
218
228
  const frame = await context.frame();
@@ -485,11 +495,6 @@ async function keyboardImplementation(pressed, provider, sessionId, text, select
485
495
  }
486
496
  return { pressed };
487
497
  }
488
- function focusIframe() {
489
- if (!document.activeElement || document.activeElement.ownerDocument !== document || document.activeElement === document.body) {
490
- window.focus();
491
- }
492
- }
493
498
  function selectAll() {
494
499
  const element = document.activeElement;
495
500
  if (element && typeof element.select === "function") {
@@ -497,6 +502,122 @@ function selectAll() {
497
502
  }
498
503
  }
499
504
 
505
+ const pointer = async (context, input, state = {}) => {
506
+ const pressedKeys = new Set(state.unreleased);
507
+ let lastTarget = state.target;
508
+ let lastCoords = state.coords;
509
+ for (const option of input) {
510
+ let target = option.target;
511
+ let coords = option.coords;
512
+ if (target || coords) {
513
+ lastTarget = target;
514
+ lastCoords = coords;
515
+ } else {
516
+ target = lastTarget;
517
+ coords = lastCoords;
518
+ }
519
+ const pointerAction = {
520
+ ...option,
521
+ target,
522
+ coords
523
+ };
524
+ const keys = "keys" in option ? option.keys : null;
525
+ const parsedKeys = keys === null ? null : groupKeyDefs(parseKeyDef(keys));
526
+ const hasOnlyClickActions = parsedKeys?.every(({ keyDef: { keyDef: { code }, releasePrevious, releaseSelf } }) => code === "MouseLeft" && !releasePrevious && releaseSelf);
527
+ // click has its own moving logic, no need to move twice
528
+ if (!hasOnlyClickActions) {
529
+ if (target) {
530
+ await hover(context, target, { position: coords });
531
+ } else if (coords) {
532
+ await context.page.mouse.move(coords.x, coords.y);
533
+ }
534
+ }
535
+ if (parsedKeys) {
536
+ for (const key of parsedKeys) {
537
+ await keyDefHandler(key, pointerAction, pressedKeys, context);
538
+ }
539
+ }
540
+ }
541
+ return {
542
+ unreleased: Array.from(pressedKeys),
543
+ target: lastTarget,
544
+ coords: lastCoords
545
+ };
546
+ };
547
+ function groupKeyDefs(keyDefs) {
548
+ const output = [];
549
+ let last;
550
+ for (const keyDef of keyDefs) {
551
+ if (last !== undefined && last.keyDef.releasePrevious === keyDef.releasePrevious && last.keyDef.releaseSelf === keyDef.releaseSelf && last.keyDef.keyDef.key === keyDef.keyDef.key && last.keyDef.keyDef.code === keyDef.keyDef.code && last.keyDef.keyDef.location === keyDef.keyDef.location) {
552
+ last.times += keyDef.repeat;
553
+ } else {
554
+ last = {
555
+ times: keyDef.repeat,
556
+ keyDef
557
+ };
558
+ output.push(last);
559
+ }
560
+ }
561
+ return output;
562
+ }
563
+ const MOUSE_KEYS = [
564
+ "MouseLeft",
565
+ "MouseRight",
566
+ "MouseMiddle"
567
+ ];
568
+ async function keyDefHandler({ keyDef: { keyDef, releasePrevious, releaseSelf }, times }, pointerAction, pressedKeys, context) {
569
+ const key = keyDef.key;
570
+ const code = keyDef.code;
571
+ if (MOUSE_KEYS.includes(code)) {
572
+ const button = code.replace("Mouse", "").toLowerCase();
573
+ const mouseOptions = {
574
+ button,
575
+ clickCount: times
576
+ };
577
+ if (releasePrevious) {
578
+ await context.page.mouse.up(mouseOptions);
579
+ } else if (releaseSelf) {
580
+ if (pointerAction.target) {
581
+ await click(context, pointerAction.target, {
582
+ ...mouseOptions,
583
+ position: pointerAction.coords
584
+ });
585
+ } else {
586
+ const x = pointerAction.coords?.x ?? 0;
587
+ const y = pointerAction.coords?.y ?? 0;
588
+ await context.page.mouse.click(x, y, mouseOptions);
589
+ }
590
+ } else {
591
+ await context.page.mouse.down(mouseOptions);
592
+ }
593
+ return;
594
+ }
595
+ if (key === "Unknown") {
596
+ return;
597
+ }
598
+ if (!releasePrevious) {
599
+ if (releaseSelf) {
600
+ for (let count = 0; count < times; count += 1) {
601
+ await context.page.keyboard.press(key);
602
+ }
603
+ } else {
604
+ await context.page.keyboard.down(key);
605
+ pressedKeys.add(key);
606
+ }
607
+ } else if (pressedKeys.has(key)) {
608
+ await context.page.keyboard.up(key);
609
+ pressedKeys.delete(key);
610
+ }
611
+ }
612
+
613
+ const SCREENSHOT_STYLES = `
614
+ iframe[data-vitest="true"] {
615
+ position: absolute !important;
616
+ inset: 0 !important;
617
+ z-index: ${Number.MAX_SAFE_INTEGER} !important;
618
+ transform: none !important;
619
+ }
620
+ `;
500
621
  /**
501
622
  * Takes a screenshot using the provided browser context and returns a buffer and the expected screenshot path.
502
623
  *
@@ -519,23 +640,35 @@ async function takeScreenshot(context, name, options) {
519
640
  await mkdir(dirname(savePath), { recursive: true });
520
641
  }
521
642
  const mask = options.mask?.map((selector) => getDescribedLocator(context, selector));
643
+ const style = context.project.config.browser.ui ? options.style === undefined ? SCREENSHOT_STYLES : SCREENSHOT_STYLES + options.style : options.style;
522
644
  if (options.element) {
523
- const { element: selector, ...config } = options;
645
+ const { element: selector, target: _target, ...config } = options;
524
646
  const element = getDescribedLocator(context, selector);
525
647
  const buffer = await element.screenshot({
526
648
  ...config,
527
649
  mask,
528
- path: savePath
650
+ path: savePath,
651
+ style
529
652
  });
530
653
  return {
531
654
  buffer,
532
655
  path
533
656
  };
534
657
  }
535
- const buffer = await getDescribedLocator(context, "body").screenshot({
536
- ...options,
658
+ const { target, ...config } = options;
659
+ const buffer = target === "page" ? await context.page.screenshot({
660
+ ...config,
661
+ mask,
662
+ path: savePath,
663
+ style
664
+ }) : await getDescribedLocator(context, {
665
+ selector: "body",
666
+ locator: "locator('body')"
667
+ }).screenshot({
668
+ ...config,
537
669
  mask,
538
- path: savePath
670
+ path: savePath,
671
+ style
539
672
  });
540
673
  return {
541
674
  buffer,
@@ -620,14 +753,14 @@ const markTrace = async (context, payload) => {
620
753
  if (!context.provider.tracingContexts.has(context.sessionId)) {
621
754
  return;
622
755
  }
623
- const { name, selector, stack } = payload;
756
+ const { name, element, stack } = payload;
624
757
  const location = parseLocation(context, stack);
625
758
  // mark trace via group/groupEnd with dummy calls to force snapshot.
626
759
  // https://github.com/microsoft/playwright/issues/39308
627
760
  await context.context.tracing.group(name, { location });
628
761
  try {
629
- if (selector) {
630
- const locator = getDescribedLocator(context, selector);
762
+ if (element) {
763
+ const locator = getDescribedLocator(context, element);
631
764
  if (typeof locator._expect === "function") {
632
765
  await locator._expect("to.be.attached", {
633
766
  isNot: false,
@@ -671,7 +804,7 @@ function parseLocation(context, stack) {
671
804
  if (!stack) {
672
805
  return;
673
806
  }
674
- const parsedStacks = context.project.browser.parseStacktrace(stack);
807
+ const parsedStacks = context.project.browser.parseStacktrace(stack, { firstOnly: true });
675
808
  return parsedStacks[0];
676
809
  }
677
810
  function resolveTracesPath({ testPath, project }, name) {
@@ -769,6 +902,10 @@ const upload = async (context, selector, files, options) => {
769
902
  await getDescribedLocator(context, selector).setInputFiles(playwrightFiles, options);
770
903
  };
771
904
 
905
+ const viewport = async (context, options) => {
906
+ await context.page.setViewportSize(options);
907
+ };
908
+
772
909
  const wheel = async (context, selector, options) => {
773
910
  await hover(context, selector);
774
911
  const times = options.times ?? 1;
@@ -785,6 +922,7 @@ var commands = {
785
922
  __vitest_dblClick: dblClick,
786
923
  __vitest_tripleClick: tripleClick,
787
924
  __vitest_wheel: wheel,
925
+ __vitest_pointer: pointer,
788
926
  __vitest_takeScreenshot: takeScreenshot,
789
927
  __vitest_type: type,
790
928
  __vitest_clear: clear,
@@ -802,7 +940,8 @@ var commands = {
802
940
  __vitest_annotateTraces: annotateTraces,
803
941
  __vitest_markTrace: markTrace,
804
942
  __vitest_groupTraceStart: groupTraceStart,
805
- __vitest_groupTraceEnd: groupTraceEnd
943
+ __vitest_groupTraceEnd: groupTraceEnd,
944
+ __vitest_viewport: viewport
806
945
  };
807
946
 
808
947
  const pkgRoot = resolve(fileURLToPath(import.meta.url), "../..");
@@ -822,12 +961,149 @@ function playwright(options = {}) {
822
961
  name: "playwright",
823
962
  supportedBrowser: playwrightBrowsers,
824
963
  options,
964
+ prewarm(ctx) {
965
+ prewarmBrowser(ctx, options);
966
+ },
825
967
  providerFactory(project) {
826
968
  return new PlaywrightBrowserProvider(project, options);
827
969
  }
828
970
  });
829
971
  }
972
+ // The resolved config object is passed unchanged to the eventual TestProject,
973
+ // so it identifies the browser this project can adopt.
974
+ const warmBrowsers = new WeakMap();
975
+ const pendingWarmBrowsers = new WeakMap();
976
+ // starts importing playwright and launching the browser while the node side
977
+ // is still creating the vite server, so the launch latency overlaps it. The
978
+ // launch options are resolved by the same code as the real launch — if they
979
+ // still differ by the time the provider opens the browser, the warm instance
980
+ // is discarded, so this is always safe
981
+ function prewarmBrowser(project, options) {
982
+ const browserName = project.config.browser.name;
983
+ if (options.connectOptions || options.persistentContext || project.vitest.config.inspector.enabled) {
984
+ return;
985
+ }
986
+ if (!browserName || !playwrightBrowsers.includes(browserName)) {
987
+ return;
988
+ }
989
+ if (warmBrowsers.has(project.config)) {
990
+ return;
991
+ }
992
+ const pending = getPendingWarmBrowsers(project.vitest);
993
+ const launchOptions = resolveLaunchOptions(project.config.browser, project.vitest.config.inspector, options, browserName);
994
+ const entry = {
995
+ config: project.config,
996
+ launchOptionsJson: getWarmBrowserKey(browserName, launchOptions),
997
+ pending,
998
+ promise: (async () => {
999
+ debug?.("[%s] prewarming the browser", browserName);
1000
+ const playwright = await import('playwright');
1001
+ return playwright[browserName].launch(launchOptions);
1002
+ })()
1003
+ };
1004
+ // if the warm launch fails, drop it so the real launch retries
1005
+ // and surfaces the error through the normal path
1006
+ entry.promise.catch(() => {
1007
+ if (warmBrowsers.get(project.config) === entry) {
1008
+ warmBrowsers.delete(project.config);
1009
+ entry.pending.delete(entry);
1010
+ }
1011
+ });
1012
+ pending.add(entry);
1013
+ warmBrowsers.set(project.config, entry);
1014
+ }
1015
+ function getWarmBrowserKey(browserName, launchOptions) {
1016
+ return JSON.stringify([browserName, launchOptions]);
1017
+ }
1018
+ function getPendingWarmBrowsers(vitest) {
1019
+ let pending = pendingWarmBrowsers.get(vitest);
1020
+ if (!pending) {
1021
+ const pendingBrowsers = new Set();
1022
+ pending = pendingBrowsers;
1023
+ pendingWarmBrowsers.set(vitest, pendingBrowsers);
1024
+ // Browsers whose projects never initialize a provider (they have no test
1025
+ // files to run) are cleaned up when Vitest closes.
1026
+ vitest.onClose(() => closeWarmBrowsers(pendingBrowsers));
1027
+ }
1028
+ return pending;
1029
+ }
1030
+ // the pool closes an idle instance to start another project; the browser
1031
+ // process stays warm so the next project adopts it instead of launching one
1032
+ function keepWarmBrowser(project, browser, launchOptionsJson) {
1033
+ const pending = getPendingWarmBrowsers(project.vitest);
1034
+ const entry = {
1035
+ config: project.config,
1036
+ launchOptionsJson,
1037
+ pending,
1038
+ promise: browser
1039
+ };
1040
+ pending.add(entry);
1041
+ warmBrowsers.set(project.config, entry);
1042
+ }
1043
+ function takeWarmBrowser(config) {
1044
+ const warm = warmBrowsers.get(config);
1045
+ if (warm) {
1046
+ warmBrowsers.delete(config);
1047
+ warm.pending.delete(warm);
1048
+ }
1049
+ return warm;
1050
+ }
1051
+ // fewer browsers are prewarmed than there are projects and the pool starts
1052
+ // projects in test order, so a browser prepared for another project is
1053
+ // adopted when it is the same browser launched with the same options
1054
+ function takeAnyWarmBrowser(vitest, launchOptionsJson) {
1055
+ const pending = pendingWarmBrowsers.get(vitest);
1056
+ if (!pending) {
1057
+ return;
1058
+ }
1059
+ for (const warm of pending) {
1060
+ if (warm.launchOptionsJson === launchOptionsJson) {
1061
+ pending.delete(warm);
1062
+ warmBrowsers.delete(warm.config);
1063
+ return warm;
1064
+ }
1065
+ }
1066
+ }
1067
+ async function closeWarmBrowsers(pending) {
1068
+ const closing = Array.from(pending, (warm) => warm.promise.then((browser) => browser.close()).catch(() => {}));
1069
+ pending.clear();
1070
+ await Promise.all(closing);
1071
+ }
1072
+ function resolveLaunchOptions(browser, inspector, providerOptions, browserName) {
1073
+ const launchOptions = {
1074
+ ...providerOptions.launchOptions,
1075
+ headless: browser.headless
1076
+ };
1077
+ if (browserName === "firefox") {
1078
+ // multiple import maps per document are behind a pref in Firefox 150+
1079
+ launchOptions.firefoxUserPrefs = {
1080
+ "dom.multiple_import_maps.enabled": true,
1081
+ ...launchOptions.firefoxUserPrefs
1082
+ };
1083
+ }
1084
+ if (typeof browser.trace === "object" && browser.trace.tracesDir) {
1085
+ launchOptions.tracesDir = browser.trace.tracesDir;
1086
+ }
1087
+ if (inspector.enabled) {
1088
+ // NodeJS equivalent defaults: https://nodejs.org/en/learn/getting-started/debugging#enable-inspector
1089
+ const port = inspector.port || 9229;
1090
+ launchOptions.args ||= [];
1091
+ launchOptions.args.push(`--remote-debugging-port=${port}`);
1092
+ }
1093
+ // start Vitest UI maximized only on supported browsers
1094
+ if (browser.ui && browserName === "chromium") {
1095
+ if (!launchOptions.args) {
1096
+ launchOptions.args = [];
1097
+ }
1098
+ if (!launchOptions.args.includes("--start-maximized") && !launchOptions.args.includes("--start-fullscreen")) {
1099
+ launchOptions.args.push("--start-maximized");
1100
+ }
1101
+ }
1102
+ return launchOptions;
1103
+ }
830
1104
  class PlaywrightBrowserProvider {
1105
+ project;
1106
+ options;
831
1107
  name = "playwright";
832
1108
  supportsParallelism = true;
833
1109
  browser = null;
@@ -837,7 +1113,10 @@ class PlaywrightBrowserProvider {
837
1113
  mocker;
838
1114
  browserName;
839
1115
  browserPromise = null;
1116
+ // set for a locally launched browser, which can be kept warm for another project
1117
+ launchOptionsJson = null;
840
1118
  closing = false;
1119
+ armedContexts = new WeakMap();
841
1120
  tracingContexts = new Set();
842
1121
  pendingTraces = new Map();
843
1122
  initScripts = [resolve(distRoot, "locators.js")];
@@ -876,36 +1155,17 @@ class PlaywrightBrowserProvider {
876
1155
  return this.browser;
877
1156
  }
878
1157
  this.browserPromise = (async () => {
879
- const options = this.project.config.browser;
880
1158
  const playwright = await import('playwright');
881
- const launchOptions = {
882
- ...this.options.launchOptions,
883
- headless: options.headless
884
- };
885
- if (typeof options.trace === "object" && options.trace.tracesDir) {
886
- launchOptions.tracesDir = options.trace?.tracesDir;
887
- }
1159
+ const launchOptions = resolveLaunchOptions(this.project.config.browser, this.project.vitest.config.inspector, this.options, this.browserName);
888
1160
  const inspector = this.project.vitest.config.inspector;
889
1161
  if (inspector.enabled) {
890
- // NodeJS equivalent defaults: https://nodejs.org/en/learn/getting-started/debugging#enable-inspector
891
1162
  const port = inspector.port || 9229;
892
1163
  const host = inspector.host || "127.0.0.1";
893
- launchOptions.args ||= [];
894
- launchOptions.args.push(`--remote-debugging-port=${port}`);
895
1164
  if (host !== "localhost" && host !== "127.0.0.1" && host !== "::1") {
896
1165
  this.project.vitest.logger.warn(`Custom inspector host "${host}" will be ignored. Chromium only allows remote debugging on localhost.`);
897
1166
  }
898
1167
  this.project.vitest.logger.log(`Debugger listening on ws://127.0.0.1:${port}`);
899
1168
  }
900
- // start Vitest UI maximized only on supported browsers
901
- if (this.project.config.browser.ui && this.browserName === "chromium") {
902
- if (!launchOptions.args) {
903
- launchOptions.args = [];
904
- }
905
- if (!launchOptions.args.includes("--start-maximized") && !launchOptions.args.includes("--start-fullscreen")) {
906
- launchOptions.args.push("--start-maximized");
907
- }
908
- }
909
1169
  debug?.("[%s] initializing the browser with launch options: %O", this.browserName, launchOptions);
910
1170
  if (this.options.connectOptions) {
911
1171
  let { wsEndpoint, headers = {}, ...connectOptions } = this.options.connectOptions;
@@ -938,13 +1198,66 @@ class PlaywrightBrowserProvider {
938
1198
  });
939
1199
  this.browser = this.persistentContext.browser();
940
1200
  } else {
1201
+ const launchOptionsJson = getWarmBrowserKey(this.browserName, launchOptions);
1202
+ let warm = takeWarmBrowser(this.project.config);
1203
+ if (warm && warm.launchOptionsJson !== launchOptionsJson) {
1204
+ debug?.("[%s] discarding the prewarmed browser, launch options changed", this.browserName);
1205
+ void warm.promise.then((browser) => browser.close()).catch(() => {});
1206
+ warm = undefined;
1207
+ }
1208
+ warm ??= takeAnyWarmBrowser(this.project.vitest, launchOptionsJson);
1209
+ if (warm) {
1210
+ const browser = await warm.promise.catch(() => null);
1211
+ if (browser?.isConnected()) {
1212
+ debug?.("[%s] adopting the prewarmed browser", this.browserName);
1213
+ this.browser = browser;
1214
+ this.browserPromise = null;
1215
+ this.launchOptionsJson = launchOptionsJson;
1216
+ return this.browser;
1217
+ }
1218
+ }
941
1219
  this.browser = await playwright[this.browserName].launch(launchOptions);
1220
+ this.launchOptionsJson = launchOptionsJson;
942
1221
  }
943
1222
  this.browserPromise = null;
944
1223
  return this.browser;
945
1224
  })();
946
1225
  return this.browserPromise;
947
1226
  }
1227
+ armInterception(page) {
1228
+ if (this.browserName !== "chromium") {
1229
+ return Promise.resolve();
1230
+ }
1231
+ const context = page.context();
1232
+ const armed = this.armedContexts.get(context) ?? this.probeInterception(page).catch((error) => {
1233
+ this.armedContexts.delete(context);
1234
+ throw error;
1235
+ });
1236
+ this.armedContexts.set(context, armed);
1237
+ return armed;
1238
+ }
1239
+ async probeInterception(page) {
1240
+ const probeUrl = "/__vitest_interception_probe__";
1241
+ const probePattern = `**${probeUrl}`;
1242
+ const context = page.context();
1243
+ await context.route(probePattern, (route) => route.fulfill({
1244
+ status: 204,
1245
+ headers: { "x-vitest-probe": "1" }
1246
+ }));
1247
+ const deadline = Date.now() + 5e3;
1248
+ while (Date.now() < deadline) {
1249
+ const intercepted = await page.evaluate((url) => fetch(url, {
1250
+ cache: "no-store",
1251
+ signal: AbortSignal.timeout(1e3)
1252
+ }).then((r) => r.headers.has("x-vitest-probe"), () => false), probeUrl).catch(() => false);
1253
+ if (intercepted) {
1254
+ return;
1255
+ }
1256
+ await new Promise((resolve) => setTimeout(resolve, 10));
1257
+ }
1258
+ await context.unroute(probePattern);
1259
+ throw new Error(`Cannot verify that ${this.browserName} request interception is active after 5s; module mocks would not apply reliably (#8339)`);
1260
+ }
948
1261
  createMocker() {
949
1262
  const idPredicates = new Map();
950
1263
  const sessionIds = new Map();
@@ -978,12 +1291,14 @@ class PlaywrightBrowserProvider {
978
1291
  predicate
979
1292
  };
980
1293
  }
1294
+ // the tester unmocks by path, but the route is registered by the full url
981
1295
  function predicateKey(sessionId, url) {
982
- return `${sessionId}:${url}`;
1296
+ return `${sessionId}:${new URL(url, "http://localhost").href}`;
983
1297
  }
984
1298
  return {
985
1299
  register: async (sessionId, module) => {
986
1300
  const page = this.getPage(sessionId);
1301
+ await this.armInterception(page);
987
1302
  const { url: moduleUrl, predicate } = createPredicate(module.url);
988
1303
  const key = predicateKey(sessionId, moduleUrl);
989
1304
  const existingPredicate = idPredicates.get(key);
@@ -996,8 +1311,8 @@ class PlaywrightBrowserProvider {
996
1311
  idPredicates.set(key, predicate);
997
1312
  await page.context().route(predicate, async (route) => {
998
1313
  if (module.type === "manual") {
999
- const exports$1 = Object.keys(await module.resolve());
1000
- const body = createManualModuleSource(module.url, exports$1);
1314
+ const exports = Object.keys(await module.resolve());
1315
+ const body = createManualModuleSource(module.url, exports);
1001
1316
  return route.fulfill({
1002
1317
  body,
1003
1318
  headers: getHeaders(this.project.browser.vite.config)
@@ -1016,7 +1331,7 @@ class PlaywrightBrowserProvider {
1016
1331
  request.searchParams.set("mock", module.type);
1017
1332
  url = request.href.slice(request.origin.length);
1018
1333
  }
1019
- const result = await this.project.browser.vite.transformRequest(url).catch(() => null);
1334
+ const result = await this.project.browser.vite.transformRequest(decodeURI(url)).catch(() => null);
1020
1335
  if (!result) {
1021
1336
  return route.continue();
1022
1337
  }
@@ -1056,7 +1371,7 @@ class PlaywrightBrowserProvider {
1056
1371
  clear: async (sessionId) => {
1057
1372
  const page = this.getPage(sessionId);
1058
1373
  const ids = sessionIds.get(sessionId) ?? new Set();
1059
- const promises = [...ids].map((id) => {
1374
+ const promises = Array.from(ids, (id) => {
1060
1375
  const key = predicateKey(sessionId, id);
1061
1376
  const predicate = idPredicates.get(key);
1062
1377
  if (predicate) {
@@ -1098,7 +1413,11 @@ class PlaywrightBrowserProvider {
1098
1413
  ...contextOptions,
1099
1414
  ignoreHTTPSErrors: true
1100
1415
  };
1101
- if (this.project.config.browser.ui) {
1416
+ // A `null` viewport lets the page adopt the real window size, which is only
1417
+ // meaningful for a headed UI. In headless mode there is no real window, so it
1418
+ // would inherit the host's device scale factor and produce screenshots that
1419
+ // differ from non-UI runs on the same machine.
1420
+ if (this.project.config.browser.ui && !this.project.config.browser.headless) {
1102
1421
  options.viewport = null;
1103
1422
  }
1104
1423
  return options;
@@ -1149,6 +1468,13 @@ class PlaywrightBrowserProvider {
1149
1468
  debug?.("[%s][%s] the page is ready", sessionId, this.browserName);
1150
1469
  await this._throwIfClosing(page);
1151
1470
  this.pages.set(sessionId, page);
1471
+ // fail the run immediately with an attributed error; otherwise the crash
1472
+ // is only visible as a websocket disconnect, if the browser closes it at all
1473
+ page.on("crash", () => {
1474
+ debug?.("[%s][%s] the page crashed", sessionId, this.browserName);
1475
+ const session = this.project.vitest._browserSessions.getSession(sessionId);
1476
+ session?.fail(new BrowserConnectionError(`The ${this.browserName} page crashed while running tests. This can happen if the browser ran out of memory.`));
1477
+ });
1152
1478
  if (process.env.VITEST_PW_DEBUG) {
1153
1479
  page.on("requestfailed", (request) => {
1154
1480
  console.error("[PW Error]", request.resourceType(), "request failed for", request.url(), "url:", request.failure()?.errorText);
@@ -1167,10 +1493,6 @@ class PlaywrightBrowserProvider {
1167
1493
  if (this.closing) {
1168
1494
  debug?.("[%s] provider was closed, cannot perform the action on %s", this.browserName, String(disposable));
1169
1495
  await disposable?.close();
1170
- this.pages.clear();
1171
- this.contexts.clear();
1172
- this.browser = null;
1173
- this.browserPromise = null;
1174
1496
  throw new Error(`[vitest] The provider was closed.`);
1175
1497
  }
1176
1498
  }
@@ -1182,29 +1504,51 @@ class PlaywrightBrowserProvider {
1182
1504
  on: cdp.on.bind(cdp),
1183
1505
  off: cdp.off.bind(cdp),
1184
1506
  once: cdp.once.bind(cdp),
1507
+ // For now this isn't typed as CDPSession but exposed only for `maybeCollectChromiumGarbage`
1185
1508
  detach: cdp.detach.bind(cdp)
1186
1509
  };
1187
1510
  }
1188
- async close() {
1511
+ async close(options) {
1189
1512
  process.off("SIGTERM", this.onSIGTERM);
1190
1513
  debug?.("[%s] closing provider", this.browserName);
1191
1514
  this.closing = true;
1515
+ // a prewarmed browser that was never adopted must not outlive the provider
1516
+ const warm = takeWarmBrowser(this.project.config);
1517
+ if (warm) {
1518
+ void warm.promise.then((browser) => browser.close()).catch(() => {});
1519
+ }
1192
1520
  if (this.browserPromise) {
1193
1521
  await this.browserPromise;
1194
1522
  this.browserPromise = null;
1195
1523
  }
1196
1524
  const browser = this.browser;
1197
1525
  this.browser = null;
1198
- await Promise.all([...this.pages.values()].map((p) => p.close()));
1526
+ const closed = this.closeContexts();
1527
+ if (options?.keepWarm && browser && this.launchOptionsJson && browser.isConnected()) {
1528
+ // registered before the contexts are closed, so the project that takes
1529
+ // over the pool slot finds the browser right away and waits for it
1530
+ const kept = closed.then(() => browser, async (error) => {
1531
+ await browser.close().catch(() => {});
1532
+ throw error;
1533
+ });
1534
+ keepWarmBrowser(this.project, kept, this.launchOptionsJson);
1535
+ await kept;
1536
+ debug?.("[%s] provider is closed, the browser is kept warm", this.browserName);
1537
+ return;
1538
+ }
1539
+ await closed;
1540
+ await browser?.close();
1541
+ debug?.("[%s] provider is closed", this.browserName);
1542
+ }
1543
+ async closeContexts() {
1544
+ await Promise.all(Array.from(this.pages.values(), (p) => p.close()));
1199
1545
  this.pages.clear();
1200
1546
  if (this.persistentContext) {
1201
1547
  await this.persistentContext.close();
1202
1548
  } else {
1203
- await Promise.all([...this.contexts.values()].map((c) => c.close()));
1549
+ await Promise.all(Array.from(this.contexts.values(), (c) => c.close()));
1204
1550
  }
1205
1551
  this.contexts.clear();
1206
- await browser?.close();
1207
- debug?.("[%s] provider is closed", this.browserName);
1208
1552
  }
1209
1553
  }
1210
1554
  function getHeaders(config) {
package/dist/locators.js CHANGED
@@ -1,39 +1,29 @@
1
- import { selectorEngine, getByTitleSelector, getByTextSelector, getByPlaceholderSelector, getByAltTextSelector, getByTestIdSelector, getByRoleSelector, getByLabelSelector, Locator, processTimeoutOptions, getIframeScale } from '@vitest/browser/locators';
1
+ import { selectorEngine, getByTitleSelector, getByTextSelector, getByPlaceholderSelector, getByAltTextSelector, getByTestIdSelector, getByRoleSelector, getByLabelSelector, Locator, getIframeScale } from '@vitest/browser/locators';
2
2
  import { page, server } from 'vitest/browser';
3
3
  import { __INTERNAL } from 'vitest/internal/browser';
4
4
 
5
5
  class PlaywrightLocator extends Locator {
6
+ selector;
7
+ _container;
6
8
  constructor(selector, _container) {
7
9
  super();
8
10
  this.selector = selector;
9
11
  this._container = _container;
10
12
  }
11
13
  click(options) {
12
- return super.click(processTimeoutOptions(processClickOptions(options)));
14
+ return super.click(processClickOptions(options));
13
15
  }
14
16
  dblClick(options) {
15
- return super.dblClick(processTimeoutOptions(processClickOptions(options)));
17
+ return super.dblClick(processClickOptions(options));
16
18
  }
17
19
  tripleClick(options) {
18
- return super.tripleClick(processTimeoutOptions(processClickOptions(options)));
19
- }
20
- selectOptions(value, options) {
21
- return super.selectOptions(value, processTimeoutOptions(options));
22
- }
23
- clear(options) {
24
- return super.clear(processTimeoutOptions(options));
20
+ return super.tripleClick(processClickOptions(options));
25
21
  }
26
22
  hover(options) {
27
- return super.hover(processTimeoutOptions(processHoverOptions(options)));
28
- }
29
- upload(files, options) {
30
- return super.upload(files, processTimeoutOptions(options));
31
- }
32
- fill(text, options) {
33
- return super.fill(text, processTimeoutOptions(options));
23
+ return super.hover(processHoverOptions(options));
34
24
  }
35
25
  dropTo(target, options) {
36
- return super.dropTo(target, processTimeoutOptions(processDragAndDropOptions(options)));
26
+ return super.dropTo(target, processDragAndDropOptions(options));
37
27
  }
38
28
  locator(selector) {
39
29
  return new PlaywrightLocator(`${this.selector} >> ${selector}`, this._container);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vitest/browser-playwright",
3
3
  "type": "module",
4
- "version": "4.1.12",
4
+ "version": "5.1.0",
5
5
  "description": "Browser running for Vitest using playwright",
6
6
  "license": "MIT",
7
7
  "funding": "https://opencollective.com/vitest",
@@ -25,6 +25,7 @@
25
25
  "sideEffects": false,
26
26
  "exports": {
27
27
  ".": {
28
+ "__vitest_source__": "./src/index.ts",
28
29
  "types": "./dist/index.d.ts",
29
30
  "default": "./dist/index.js"
30
31
  },
@@ -42,7 +43,7 @@
42
43
  ],
43
44
  "peerDependencies": {
44
45
  "playwright": "*",
45
- "vitest": "4.1.12"
46
+ "vitest": "5.1.0"
46
47
  },
47
48
  "peerDependenciesMeta": {
48
49
  "playwright": {
@@ -50,13 +51,15 @@
50
51
  }
51
52
  },
52
53
  "dependencies": {
53
- "tinyrainbow": "^3.1.0",
54
- "@vitest/mocker": "4.1.12",
55
- "@vitest/browser": "4.1.12"
54
+ "@vitest/browser": "5.1.0",
55
+ "@vitest/mocker": "5.1.0",
56
+ "tinyrainbow": "^3.2.0"
56
57
  },
57
58
  "devDependencies": {
58
- "playwright": "^1.61.0",
59
- "vitest": "4.1.12"
59
+ "pathe": "^2.0.3",
60
+ "playwright": "^1.64.1",
61
+ "vite": "8.3.5",
62
+ "vitest": "5.1.0"
60
63
  },
61
64
  "scripts": {
62
65
  "build": "premove dist && pnpm rollup -c",