-
-
Notifications
You must be signed in to change notification settings - Fork 751
Expand file tree
/
Copy pathPlaywright.js
More file actions
4981 lines (4457 loc) · 159 KB
/
Playwright.js
File metadata and controls
4981 lines (4457 loc) · 159 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import path from 'path'
import fs from 'fs'
import Helper from '@codeceptjs/helper'
import { v4 as uuidv4 } from 'uuid'
import assert from 'assert'
import promiseRetry from 'promise-retry'
import Locator from '../locator.js'
import recorder from '../recorder.js'
import store from '../store.js'
import { includes as stringIncludes } from '../assert/include.js'
import { urlEquals, equals } from '../assert/equal.js'
import { empty } from '../assert/empty.js'
import { truth } from '../assert/truth.js'
import {
xpathLocator,
ucfirst,
fileExists,
chunkArray,
convertCssPropertiesToCamelCase,
screenshotOutputFolder,
getNormalizedKeyAttributeValue,
isModifierKey,
clearString,
requireWithFallback,
normalizeSpacesInString,
relativeDir,
} from '../utils.js'
import { isColorProperty, convertColorToRGBA } from '../colorUtils.js'
import ElementNotFound from './errors/ElementNotFound.js'
import RemoteBrowserConnectionRefused from './errors/RemoteBrowserConnectionRefused.js'
import Popup from './extras/Popup.js'
import Console from './extras/Console.js'
import { findReact, findVue, findByPlaywrightLocator } from './extras/PlaywrightReactVueLocator.js'
import WebElement from '../element/WebElement.js'
let playwright
let perfTiming
let defaultSelectorEnginesInitialized = false
let registeredCustomLocatorStrategies = new Set()
let globalCustomLocatorStrategies = new Map()
// Use global object to track selector registration across workers
if (typeof global.__playwrightSelectorsRegistered === 'undefined') {
global.__playwrightSelectorsRegistered = false
}
/**
* Creates a Playwright selector engine factory for a custom locator strategy.
* @param {string} name - Strategy name for error messages
* @param {Function} func - The locator function (selector, root) => Element|Element[]
* @returns {Function} Selector engine factory
*/
function createCustomSelectorEngine(name, func) {
return () => ({
create: () => null,
query(root, selector) {
if (!root) return null
try {
const result = func(selector, root)
return Array.isArray(result) ? result[0] : result
} catch (e) {
return null
}
},
queryAll(root, selector) {
if (!root) return []
try {
const result = func(selector, root)
return Array.isArray(result) ? result : result ? [result] : []
} catch (e) {
return []
}
},
})
}
const popupStore = new Popup()
const consoleLogStore = new Console()
const availableBrowsers = ['chromium', 'webkit', 'firefox', 'electron']
import { setRestartStrategy, restartsSession, restartsContext, restartsBrowser } from './extras/PlaywrightRestartOpts.js'
import { createValueEngine, createDisabledEngine } from './extras/PlaywrightPropEngine.js'
import { seeElementError, dontSeeElementError, dontSeeElementInDOMError, seeElementInDOMError } from './errors/ElementAssertion.js'
import { dontSeeTraffic, seeTraffic, grabRecordedNetworkTraffics, stopRecordingTraffic, flushNetworkTraffics } from './network/actions.js'
const pathSeparator = path.sep
/**
* ## Configuration
*
* This helper should be configured in codecept.conf.(js|ts)
*
* @typedef PlaywrightConfig
* @type {object}
* @prop {string} [url] - base url of website to be tested
* @prop {'chromium' | 'firefox'| 'webkit' | 'electron'} [browser='chromium'] - a browser to test on, either: `chromium`, `firefox`, `webkit`, `electron`. Default: chromium.
* @prop {boolean} [show=true] - show browser window.
* @prop {string|boolean} [restart=false] - restart strategy between tests. Possible values:
* * 'context' or **false** - restarts [browser context](https://playwright.dev/docs/api/class-browsercontext) but keeps running browser. Recommended by Playwright team to keep tests isolated.
* * 'session' or 'keep' - keeps browser context and session, but cleans up cookies and localStorage between tests. The fastest option when running tests in windowed mode. Works with `keepCookies` and `keepBrowserState` options. This behavior was default before CodeceptJS 3.1
* @prop {number} [timeout=1000] - - [timeout](https://playwright.dev/docs/api/class-page#page-set-default-timeout) in ms of all Playwright actions .
* @prop {boolean} [disableScreenshots=false] - don't save screenshot on failure.
* @prop {any} [emulate] - browser in device emulation mode.
* @prop {boolean} [video=false] - enables video recording for failed tests; videos are saved into `output/videos` folder
* @prop {boolean} [keepVideoForPassedTests=false] - save videos for passed tests; videos are saved into `output/videos` folder
* @prop {boolean} [trace=false] - record [tracing information](https://playwright.dev/docs/trace-viewer) with screenshots and snapshots.
* @prop {boolean} [keepTraceForPassedTests=false] - save trace for passed tests.
* @prop {boolean} [fullPageScreenshots=false] - make full page screenshots on failure.
* @prop {boolean} [uniqueScreenshotNames=false] - option to prevent screenshot override if you have scenarios with the same name in different suites.
* @prop {boolean} [keepBrowserState=false] - keep browser state between tests when `restart` is set to 'session'.
* @prop {boolean} [keepCookies=false] - keep cookies between tests when `restart` is set to 'session'.
* @prop {number} [waitForAction] - how long to wait after click, doubleClick or PressKey actions in ms. Default: 100.
* @prop {'load' | 'domcontentloaded' | 'commit'} [waitForNavigation] - When to consider navigation succeeded. Possible options: `load`, `domcontentloaded`, `commit`. Choose one of those options is possible. See [Playwright API](https://playwright.dev/docs/api/class-page#page-wait-for-url).
* @prop {number} [pressKeyDelay=10] - Delay between key presses in ms. Used when calling Playwrights page.type(...) in fillField/appendField
* @prop {number} [getPageTimeout] - config option to set maximum navigation time in milliseconds.
* @prop {number} [waitForTimeout] - default wait* timeout in ms. Default: 1000.
* @prop {object} [basicAuth] - the basic authentication to pass to base url. Example: {username: 'username', password: 'password'}
* @prop {string} [windowSize] - default window size. Set a dimension like `640x480`.
* @prop {'dark' | 'light' | 'no-preference'} [colorScheme] - default color scheme. Possible values: `dark` | `light` | `no-preference`.
* @prop {string} [userAgent] - user-agent string.
* @prop {string} [locale] - locale string. Example: 'en-GB', 'de-DE', 'fr-FR', ...
* @prop {boolean} [manualStart] - do not start browser before a test, start it manually inside a helper with `this.helpers["Playwright"]._startBrowser()`.
* @prop {object} [chromium] - pass additional chromium options
* @prop {object} [firefox] - pass additional firefox options
* @prop {object} [electron] - (pass additional electron options
* @prop {any} [channel] - (While Playwright can operate against the stock Google Chrome and Microsoft Edge browsers available on the machine. In particular, current Playwright version will support Stable and Beta channels of these browsers. See [Google Chrome & Microsoft Edge](https://playwright.dev/docs/browsers/#google-chrome--microsoft-edge).
* @prop {string[]} [ignoreLog] - An array with console message types that are not logged to debug log. Default value is `['warning', 'log']`. E.g. you can set `[]` to log all messages. See all possible [values](https://playwright.dev/docs/api/class-consolemessage#console-message-type).
* @prop {boolean} [ignoreHTTPSErrors] - Allows access to untrustworthy pages, e.g. to a page with an expired certificate. Default value is `false`
* @prop {boolean} [bypassCSP] - bypass Content Security Policy or CSP
* @prop {boolean} [highlightElement] - highlight the interacting elements. Default: false. Note: only activate under verbose mode (--verbose).
* @prop {object} [recordHar] - record HAR and will be saved to `output/har`. See more of [HAR options](https://playwright.dev/docs/api/class-browser#browser-new-context-option-record-har).
* @prop {string} [testIdAttribute=data-testid] - locate elements based on the testIdAttribute. See more of [locate by test id](https://playwright.dev/docs/locators#locate-by-test-id).
* @prop {object} [customLocatorStrategies] - custom locator strategies. An object with keys as strategy names and values as JavaScript functions. Example: `{ byRole: (selector, root) => { return root.querySelector(`[role="${selector}"]`) } }`
* @prop {string|object} [storageState] - Playwright storage state (path to JSON file or object)
* passed directly to `browser.newContext`.
* If a Scenario is declared with a `cookies` option (e.g. `Scenario('name', { cookies: [...] }, fn)`),
* those cookies are used instead and the configured `storageState` is ignored (no merge).
* May include session cookies, auth tokens, localStorage and (if captured with
* `grabStorageState({ indexedDB: true })`) IndexedDB data; treat as sensitive and do not commit.
*/
const config = {}
/**
* Uses [Playwright](https://github.com/microsoft/playwright) library to run tests inside:
*
* * Chromium
* * Firefox
* * Webkit (Safari)
*
* This helper works with a browser out of the box with no additional tools required to install.
*
* Requires `playwright` or `playwright-core` package version ^1 to be installed:
*
* ```
* npm i playwright@^1.18 --save
* ```
* or
* ```
* npm i playwright-core@^1.18 --save
* ```
*
* Breaking Changes: if you use Playwright v1.38 and later, it will no longer download browsers automatically.
*
* Run `npx playwright install` to download browsers after `npm install`.
*
* Using playwright-core package, will prevent the download of browser binaries and allow connecting to an existing browser installation or for connecting to a remote one.
*
*
* <!-- configuration -->
*
* #### Video Recording Customization
*
* By default, video is saved to `output/video` dir. You can customize this path by passing `dir` option to `recordVideo` option.
*
* `video`: enables video recording for failed tests; videos are saved into `output/videos` folder
* * `keepVideoForPassedTests`: - save videos for passed tests
* * `recordVideo`: [additional options for videos customization](https://playwright.dev/docs/next/api/class-browser#browser-new-context)
*
* #### Trace Recording Customization
*
* Trace recording provides complete information on test execution and includes DOM snapshots, screenshots, and network requests logged during run.
* Traces will be saved to `output/trace`
*
* * `trace`: enables trace recording for failed tests; trace are saved into `output/trace` folder
* * `keepTraceForPassedTests`: - save trace for passed tests
*
* #### HAR Recording Customization
*
* A HAR file is an HTTP Archive file that contains a record of all the network requests that are made when a page is loaded.
* It contains information about the request and response headers, cookies, content, timings, and more. You can use HAR files to mock network requests in your tests.
* HAR will be saved to `output/har`. More info could be found here https://playwright.dev/docs/api/class-browser#browser-new-context-option-record-har.
*
* ```
* ...
* recordHar: {
* mode: 'minimal', // possible values: 'minimal'|'full'.
* content: 'embed' // possible values: "omit"|"embed"|"attach".
* }
* ...
*```
*
* #### Example #1: Wait for 0 network connections.
*
* ```js
* {
* helpers: {
* Playwright : {
* url: "http://localhost",
* restart: false,
* waitForNavigation: "networkidle0",
* waitForAction: 500
* }
* }
* }
* ```
*
* #### Example #2: Wait for DOMContentLoaded event
*
* ```js
* {
* helpers: {
* Playwright : {
* url: "http://localhost",
* restart: false,
* waitForNavigation: "domcontentloaded",
* waitForAction: 500
* }
* }
* }
* ```
*
* #### Example #3: Debug in window mode
*
* ```js
* {
* helpers: {
* Playwright : {
* url: "http://localhost",
* show: true
* }
* }
* }
* ```
*
* #### Example #4: Connect to remote browser by specifying [websocket endpoint](https://playwright.dev/docs/api/class-browsertype#browsertypeconnectparams)
*
* ```js
* {
* helpers: {
* Playwright: {
* url: "http://localhost",
* chromium: {
* browserWSEndpoint: 'ws://localhost:9222/devtools/browser/c5aa6160-b5bc-4d53-bb49-6ecb36cd2e0a',
* cdpConnection: false // default is false
* }
* }
* }
* }
* ```
*
* #### Example #5: Testing with Chromium extensions
*
* [official docs](https://github.com/microsoft/playwright/blob/v0.11.0/docs/api.md#working-with-chrome-extensions)
*
* ```js
* {
* helpers: {
* Playwright: {
* url: "http://localhost",
* show: true // headless mode not supported for extensions
* chromium: {
* // Note: due to this would launch persistent context, so to avoid the error when running tests with run-workers a timestamp would be appended to the defined folder name. For instance: playwright-tmp_1692715649511
* userDataDir: '/tmp/playwright-tmp', // necessary to launch the browser in normal mode instead of incognito,
* args: [
* `--disable-extensions-except=${pathToExtension}`,
* `--load-extension=${pathToExtension}`
* ]
* }
* }
* }
* }
* ```
*
* #### Example #6: Launch tests emulating iPhone 6
*
*
*
* ```js
* const { devices } = require('playwright');
*
* {
* helpers: {
* Playwright: {
* url: "http://localhost",
* emulate: devices['iPhone 6'],
* }
* }
* }
* ```
*
* #### Example #7: Launch test with a specific user locale
*
* ```js
* {
* helpers: {
* Playwright : {
* url: "http://localhost",
* locale: "fr-FR",
* }
* }
* }
* ```
*
* * #### Example #8: Launch test with a specific color scheme
*
* ```js
* {
* helpers: {
* Playwright : {
* url: "http://localhost",
* colorScheme: "dark",
* }
* }
* }
* ```
*
* * #### Example #9: Launch electron test
*
* ```js
* {
* helpers: {
* Playwright: {
* browser: 'electron',
* electron: {
* executablePath: require("electron"),
* args: [path.join('../', "main.js")],
* },
* }
* },
* }
* ```
*
* Note: When connecting to remote browser `show` and specific `chrome` options (e.g. `headless` or `devtools`) are ignored.
*
* ## Access From Helpers
*
* Receive Playwright client from a custom helper by accessing `browser` for the Browser object or `page` for the current Page object:
*
* ```js
* const { browser } = this.helpers.Playwright;
* await browser.pages(); // List of pages in the browser
*
* // get current page
* const { page } = this.helpers.Playwright;
* await page.url(); // Get the url of the current page
*
* const { browserContext } = this.helpers.Playwright;
* await browserContext.cookies(); // get current browser context
* ```
*/
class Playwright extends Helper {
constructor(config) {
super(config)
// playwright will be loaded dynamically in _init method
// set defaults
this.isRemoteBrowser = false
this.isRunning = false
this.isAuthenticated = false
this.sessionPages = {}
this.activeSessionName = ''
this.isElectron = false
this.isCDPConnection = false
this.electronSessions = []
this.storageState = null
// for network stuff
this.requests = []
this.recording = false
this.recordedAtLeastOnce = false
// for websocket messages
this.webSocketMessages = []
this.recordingWebSocketMessages = false
this.recordedWebSocketMessagesAtLeastOnce = false
this.cdpSession = null
// Filter out invalid customLocatorStrategies (empty arrays, objects without functions)
// This can happen in worker threads where config is serialized/deserialized
this.customLocatorStrategies = this._parseCustomLocatorStrategies(config.customLocatorStrategies)
this._customLocatorsRegistered = false
// Add custom locator strategies to global registry for early registration
if (this.customLocatorStrategies) {
for (const [name, func] of Object.entries(this.customLocatorStrategies)) {
globalCustomLocatorStrategies.set(name, func)
}
}
// Add test failure tracking to prevent false positives
this.testFailures = []
this.hasCleanupError = false
// override defaults with config
this._setConfig(config)
// pass storageState directly (string path or object) and let Playwright handle errors/missing file
if (typeof config.storageState !== 'undefined') {
this.storageState = config.storageState
}
}
_validateConfig(config) {
const defaults = {
// options to emulate context
emulate: {},
browser: 'chromium',
waitForAction: 100,
waitForTimeout: 1000,
pressKeyDelay: 10,
timeout: 5000,
fullPageScreenshots: false,
disableScreenshots: false,
ignoreLog: ['warning', 'log'],
uniqueScreenshotNames: false,
manualStart: false,
getPageTimeout: 30000,
waitForNavigation: 'load',
restart: false,
keepCookies: false,
keepBrowserState: false,
show: false,
defaultPopupAction: 'accept',
use: { actionTimeout: 0 },
ignoreHTTPSErrors: false, // Adding it here o that context can be set up to ignore the SSL errors,
highlightElement: false,
storageState: undefined,
onResponse: null,
}
process.env.testIdAttribute = 'data-testid'
config = Object.assign(defaults, config)
if (availableBrowsers.indexOf(config.browser) < 0) {
throw new Error(`Invalid config. Can't use browser "${config.browser}". Accepted values: ${availableBrowsers.join(', ')}`)
}
return config
}
_getOptionsForBrowser(config) {
if (config[config.browser]) {
if (config[config.browser].browserWSEndpoint && config[config.browser].browserWSEndpoint.wsEndpoint) {
config[config.browser].browserWSEndpoint = config[config.browser].browserWSEndpoint.wsEndpoint
}
return {
...config[config.browser],
wsEndpoint: config[config.browser].browserWSEndpoint,
}
}
return {}
}
_setConfig(config) {
this.options = this._validateConfig(config)
setRestartStrategy(this.options)
this.playwrightOptions = {
headless: !this.options.show,
...this._getOptionsForBrowser(config),
}
if (this.options.channel && this.options.browser === 'chromium') {
this.playwrightOptions.channel = this.options.channel
}
if (this.options.video) {
// set the video resolution with window size
let size = parseWindowSize(this.options.windowSize)
// if the video resolution is passed, set the record resoultion with that resolution
if (this.options.recordVideo && this.options.recordVideo.size) {
size = parseWindowSize(this.options.recordVideo.size)
}
this.options.recordVideo = { size }
}
if (this.options.recordVideo && !this.options.recordVideo.dir) {
this.options.recordVideo.dir = `${global.output_dir}/videos/`
}
this.isRemoteBrowser = !!this.playwrightOptions.browserWSEndpoint
this.isElectron = this.options.browser === 'electron'
this.userDataDir = this.playwrightOptions.userDataDir ? `${this.playwrightOptions.userDataDir}_${Date.now().toString()}` : undefined
this.isCDPConnection = this.playwrightOptions.cdpConnection
popupStore.defaultAction = this.options.defaultPopupAction
}
static _config() {
return [
{
name: 'browser',
message: 'Browser in which testing will be performed. Possible options: chromium, firefox, webkit or electron',
default: 'chromium',
},
{
name: 'url',
message: 'Base url of site to be tested',
default: 'http://localhost',
when: answers => answers.Playwright_browser !== 'electron',
},
{
name: 'show',
message: 'Show browser window',
default: true,
type: 'confirm',
when: answers => answers.Playwright_browser !== 'electron',
},
]
}
static _checkRequirements() {
try {
// In ESM, playwright will be checked via dynamic import in constructor
// The import will fail at module load time if playwright is missing
return null
} catch (e) {
return ['playwright@^1.18']
}
}
async _init() {
// Load playwright dynamically with fallback
if (!playwright) {
try {
playwright = await import('playwright')
playwright = playwright.default || playwright
} catch (e) {
try {
playwright = await import('playwright-core')
playwright = playwright.default || playwright
} catch (e2) {
throw new Error('Neither playwright nor playwright-core could be loaded. Please install one of them.')
}
}
}
// Ensure custom locators from this instance are in the global registry
// This is critical for worker threads where globalCustomLocatorStrategies is a new Map
if (this.customLocatorStrategies) {
for (const [strategyName, strategyFunction] of Object.entries(this.customLocatorStrategies)) {
if (!globalCustomLocatorStrategies.has(strategyName)) {
globalCustomLocatorStrategies.set(strategyName, strategyFunction)
}
}
}
// register an internal selector engine for reading value property of elements in a selector
try {
// Always wrap in try-catch since selectors might be registered globally across workers
// Check global flag to avoid re-registration in worker processes
if (!global.__playwrightSelectorsRegistered) {
try {
await playwright.selectors.register('__value', createValueEngine)
await playwright.selectors.register('__disabled', createDisabledEngine)
global.__playwrightSelectorsRegistered = true
defaultSelectorEnginesInitialized = true
} catch (e) {
if (!e.message.includes('already registered')) {
throw e
}
// Selector already registered globally by another worker
global.__playwrightSelectorsRegistered = true
defaultSelectorEnginesInitialized = true
}
} else {
// Selectors already registered in a worker, skip
defaultSelectorEnginesInitialized = true
this.debugSection('Init', 'Default selector engines already registered globally, skipping')
}
if (process.env.testIdAttribute) {
try {
await playwright.selectors.setTestIdAttribute(process.env.testIdAttribute)
} catch (e) {
// Ignore if already set
}
}
// Register all custom locator strategies from the global registry
await this._registerGlobalCustomLocators()
} catch (e) {
console.warn(e)
}
}
async _registerGlobalCustomLocators() {
for (const [name, func] of globalCustomLocatorStrategies.entries()) {
if (registeredCustomLocatorStrategies.has(name)) continue
try {
await playwright.selectors.register(name, createCustomSelectorEngine(name, func))
registeredCustomLocatorStrategies.add(name)
} catch (e) {
if (!e.message.includes('already registered')) {
this.debugSection('Custom Locator', `Failed to register '${name}': ${e.message}`)
}
}
}
}
_beforeSuite() {
// Skip browser start in dry-run mode (used by check command)
if (store.dryRun) {
this.debugSection('Dry Run', 'Skipping browser start')
return
}
// Start browser if not manually started and not already running
// Browser should start in singleton mode (restart: false) or when restart strategy is enabled
if (!this.options.manualStart && !this.isRunning) {
this.debugSection('Session', 'Starting singleton browser session')
return this._startBrowser()
}
}
async _before(test) {
// Skip browser operations in dry-run mode (used by check command)
if (store.dryRun) {
this.currentRunningTest = test
return
}
this.currentRunningTest = test
// Reset failure tracking for each test to prevent false positives
this.hasCleanupError = false
this.testFailures = []
// Reset frame context to ensure clean state for each test
this.context = this.page
this.frame = null
this.contextLocator = null
// Clear popup state to ensure clean state for each test
popupStore.clear()
recorder.retry({
retries: test?.opts?.conditionalRetries || 3,
when: err => {
if (!err || typeof err.message !== 'string') {
return false
}
// ignore context errors
return err.message.includes('context')
},
})
// Start browser if needed (initial start or browser restart strategy)
if (!this.isRunning && !this.options.manualStart) await this._startBrowser()
else if (restartsBrowser() && !this.options.manualStart) {
// Browser restart strategy: start browser for each test
await this._startBrowser()
}
this.isAuthenticated = false
if (this.isElectron) {
this.browserContext = this.browser.context()
} else if (this.playwrightOptions.userDataDir) {
this.browserContext = this.browser
} else {
const contextOptions = {
ignoreHTTPSErrors: this.options.ignoreHTTPSErrors,
acceptDownloads: true,
...this.options.emulate,
}
if (this.options.basicAuth) {
contextOptions.httpCredentials = this.options.basicAuth
this.isAuthenticated = true
}
if (this.options.bypassCSP) contextOptions.bypassCSP = this.options.bypassCSP
if (this.options.recordVideo) contextOptions.recordVideo = this.options.recordVideo
if (this.options.recordHar) {
const harExt = this.options.recordHar.content && this.options.recordHar.content === 'attach' ? 'zip' : 'har'
const fileName = `${`${global.output_dir}${path.sep}har${path.sep}${uuidv4()}_${clearString(this.currentRunningTest.title)}`.slice(0, 245)}.${harExt}`
const dir = path.dirname(fileName)
if (!fileExists(dir)) fs.mkdirSync(dir)
this.options.recordHar.path = fileName
this.currentRunningTest.artifacts.har = fileName
contextOptions.recordHar = this.options.recordHar
}
// load pre-saved cookies
if (test?.opts?.cookies) contextOptions.storageState = { cookies: test.opts.cookies }
else if (this.storageState) contextOptions.storageState = this.storageState
if (this.options.userAgent) contextOptions.userAgent = this.options.userAgent
if (this.options.locale) contextOptions.locale = this.options.locale
if (this.options.colorScheme) contextOptions.colorScheme = this.options.colorScheme
this.contextOptions = contextOptions
if (!this.browserContext || !restartsSession()) {
if (!this.browser) {
if (this.options.manualStart) {
this.debugSection('Manual Start', 'Browser not started - skipping context creation')
return // Skip context creation when manualStart is true
} else {
throw new Error('Browser not started. This should not happen.')
}
}
this.debugSection('New Session', JSON.stringify(this.contextOptions))
try {
this.browserContext = await this.browser.newContext(this.contextOptions) // Adding the HTTPSError ignore in the context so that we can ignore those errors
} catch (err) {
// In worker mode with Playwright 1.x, there's a known issue where newContext() fails
// with "selector engine already registered" when selectors are registered globally
// across worker threads. This is safe to retry without ANY custom options.
if (err.message && err.message.includes('already registered')) {
this.debugSection('Worker Mode', 'Selector conflict detected, retrying context creation with no options')
// Create context with NO options to avoid selector conflicts
this.browserContext = await this.browser.newContext()
} else {
throw err
}
}
}
}
let mainPage
if (this.isElectron) {
mainPage = await this.browser.firstWindow()
} else {
try {
const existingPages = await this.browserContext.pages()
mainPage = existingPages[0] || (await this.browserContext.newPage())
} catch (e) {
if (this.playwrightOptions.userDataDir) {
this.browser = await playwright[this.options.browser].launchPersistentContext(this.userDataDir, this.playwrightOptions)
this.browserContext = this.browser
const existingPages = await this.browserContext.pages()
mainPage = existingPages[0]
}
}
}
await targetCreatedHandler.call(this, mainPage)
await this._setPage(mainPage)
try {
// set metadata for reporting
test.meta.browser = this.browser.browserType().name()
test.meta.browserVersion = this.browser.version()
test.meta.windowSize = `${this.page.viewportSize().width}x${this.page.viewportSize().height}`
} catch (e) {
this.debug('Failed to set metadata for reporting')
}
if (this.options.trace) await this.browserContext.tracing.start({ screenshots: true, snapshots: true })
return this.browser
}
async _after() {
if (!this.isRunning) return
// Clear popup state to prevent leakage between tests
popupStore.clear()
if (this.isElectron) {
try {
this.browser.close()
this.electronSessions.forEach(session => session.close())
} catch (e) {
console.warn('Warning during electron cleanup:', e.message)
}
return
}
if (restartsSession()) {
return refreshContextSession.bind(this)()
}
if (restartsBrowser()) {
// Close browser completely for restart strategy
if (this.isRunning) {
try {
// Close all pages first to release resources
if (this.browserContext) {
const pages = await this.browserContext.pages()
await Promise.allSettled(pages.map(p => p.close().catch(() => {})))
}
// Use timeout to prevent hanging (10s should be enough for browser cleanup)
await Promise.race([this._stopBrowser(), new Promise((_, reject) => setTimeout(() => reject(new Error('Browser stop timeout')), 10000))])
} catch (e) {
console.warn('Warning during browser restart in _after:', e.message)
// Force cleanup even on timeout
this.browser = null
this.browserContext = null
this.isRunning = false
}
}
return
}
// close other sessions with timeout protection, but only if restartsContext() is true
if (restartsContext()) {
try {
if ((await this.browser)?._type === 'Browser') {
const contexts = await Promise.race([this.browser.contexts(), new Promise((_, reject) => setTimeout(() => reject(new Error('Get contexts timeout')), 3000))])
const currentContext = contexts[0]
if (currentContext && (this.options.keepCookies || this.options.keepBrowserState)) {
try {
this.storageState = await currentContext.storageState()
} catch (e) {
console.warn('Warning during storage state save:', e.message)
}
}
await Promise.race([Promise.all(contexts.map(c => c.close())), new Promise((_, reject) => setTimeout(() => reject(new Error('Close contexts timeout')), 5000))])
}
} catch (e) {
console.warn('Warning during context cleanup in _after:', e.message)
}
}
return this.browser
}
async _afterSuite() {
// Stop browser after suite completes
// For restart strategies: stop after each suite
// For session mode (restart:false): stop after the last suite
if (this.isRunning) {
try {
// Add timeout protection to prevent hanging
await Promise.race([this._stopBrowser(), new Promise((_, reject) => setTimeout(() => reject(new Error('Browser stop timeout in afterSuite')), 10000))])
} catch (e) {
console.warn('Warning during suite cleanup:', e.message)
// Track suite cleanup failures
this.hasCleanupError = true
this.testFailures.push(`Suite cleanup failed: ${e.message}`)
// Force cleanup on timeout
this.browser = null
this.browserContext = null
this.isRunning = false
} finally {
this.isRunning = false
}
}
// Force cleanup of any remaining browser processes
try {
if (this.browser && (!this.browser.isConnected || this.browser)) {
await Promise.race([Promise.resolve(), new Promise(resolve => setTimeout(resolve, 1000))])
}
} catch (e) {
console.warn('Final cleanup warning:', e.message)
this.hasCleanupError = true
this.testFailures.push(`Final cleanup failed: ${e.message}`)
}
// Clean up session pages explicitly to prevent hanging references
try {
if (this.sessionPages && Object.keys(this.sessionPages).length > 0) {
for (const sessionName in this.sessionPages) {
const sessionPage = this.sessionPages[sessionName]
if (sessionPage && !sessionPage.isClosed()) {
try {
// Remove any remaining event listeners from session pages
sessionPage.removeAllListeners('dialog')
sessionPage.removeAllListeners('crash')
sessionPage.removeAllListeners('close')
sessionPage.removeAllListeners('error')
await sessionPage.close()
} catch (e) {
console.warn(`Warning closing session page ${sessionName}:`, e.message)
}
}
}
this.sessionPages = {} // Clear the session pages object
this.activeSessionName = '' // Reset active session name
}
} catch (e) {
console.warn('Session pages cleanup warning:', e.message)
this.hasCleanupError = true
this.testFailures.push(`Session cleanup failed: ${e.message}`)
}
// Clear any lingering DOM timeouts by executing cleanup in browser context
try {
if (this.page && !this.page.isClosed()) {
await this.page
.evaluate(() => {
// Clear any running highlight timeouts by clearing a range of timeout IDs
for (let i = 1; i <= 1000; i++) {
clearTimeout(i)
}
})
.catch(() => {
// Ignore errors if execution context is destroyed (e.g., due to navigation)
})
}
} catch (e) {
// Only log if it's not an execution context error
if (!e.message.includes('Execution context was destroyed')) {
console.warn('DOM timeout cleanup warning:', e.message)
this.hasCleanupError = true
this.testFailures.push(`DOM cleanup failed: ${e.message}`)
}
}
// If we have cleanup errors, throw to fail the test suite
if (this.hasCleanupError && this.testFailures.length > 0) {
const errorMessage = `Test suite cleanup failed: ${this.testFailures.join('; ')}`
console.error(errorMessage)
throw new Error(errorMessage)
}
}
async _finishTest() {
if ((restartsSession() || restartsContext() || restartsBrowser()) && this.isRunning) {
try {
await Promise.race([this._stopBrowser(), new Promise((_, reject) => setTimeout(() => reject(new Error('Test finish timeout')), 10000))])
} catch (e) {
console.warn('Warning during test finish cleanup:', e.message)
// Track cleanup failures to prevent false positives
this.hasCleanupError = true
this.testFailures.push(`Test finish cleanup failed: ${e.message}`)
this.isRunning = false
// Set flags to prevent further operations after cleanup failure
this.page = null
this.browserContext = null
this.browser = null
// Propagate the error to fail the test properly
throw new Error(`Test cleanup failed: ${e.message}`)
}
}
}
async _cleanup() {
// Final cleanup when test run completes
if (this.isRunning) {
try {
// Add timeout protection to prevent hanging
await Promise.race([this._stopBrowser(), new Promise((_, reject) => setTimeout(() => reject(new Error('Browser stop timeout in cleanup')), 10000))])
} catch (e) {
console.warn('Warning during final cleanup:', e.message)
// Force cleanup on timeout
this.browser = null
this.browserContext = null
this.isRunning = false
}
} else {
// Check if we still have a browser object despite isRunning being false
if (this.browser) {
try {
// Add timeout protection to prevent hanging
await Promise.race([this._stopBrowser(), new Promise((_, reject) => setTimeout(() => reject(new Error('Browser stop timeout in forced cleanup')), 10000))])
} catch (e) {
console.warn('Warning during forced cleanup:', e.message)
// Force cleanup on timeout
this.browser = null
this.browserContext = null
}
}
}
}
_session() {
const defaultContext = this.browserContext
return {
start: async (sessionName = '', config) => {
this.debugSection('New Context', config ? JSON.stringify(config) : 'opened')
this.activeSessionName = sessionName
let browserContext
let page
if (this.isElectron) {
const browser = await playwright._electron.launch(this.playwrightOptions)
this.electronSessions.push(browser)
browserContext = browser.context()
page = await browser.firstWindow()
} else {
try {
// Check if browser is still available before creating context
if (!this.browser) {
throw new Error('Browser is not available for session context creation')
}
browserContext = await Promise.race([this.browser.newContext(Object.assign(this.contextOptions, config)), new Promise((_, reject) => setTimeout(() => reject(new Error('New context timeout')), 10000))])
page = await Promise.race([browserContext.newPage(), new Promise((_, reject) => setTimeout(() => reject(new Error('New page timeout')), 5000))])
} catch (e) {
console.warn('Warning during context creation:', e.message)
if (this.playwrightOptions.userDataDir) {
browserContext = await playwright[this.options.browser].launchPersistentContext(`${this.userDataDir}_${this.activeSessionName}`, this.playwrightOptions)
this.browser = browserContext
page = await browserContext.pages()[0]
} else {
throw e
}
}
}
if (this.options.trace) await browserContext.tracing.start({ screenshots: true, snapshots: true })
await targetCreatedHandler.call(this, page)