-
-
Notifications
You must be signed in to change notification settings - Fork 736
/
Copy pathPlaywright.js
3910 lines (3498 loc) · 118 KB
/
Playwright.js
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
const path = require('path')
const fs = require('fs')
const Helper = require('@codeceptjs/helper')
const { v4: uuidv4 } = require('uuid')
const assert = require('assert')
const promiseRetry = require('promise-retry')
const Locator = require('../locator')
const recorder = require('../recorder')
const store = require('../store')
const stringIncludes = require('../assert/include').includes
const { urlEquals } = require('../assert/equal')
const { equals } = require('../assert/equal')
const { empty } = require('../assert/empty')
const { truth } = require('../assert/truth')
const {
xpathLocator,
ucfirst,
fileExists,
chunkArray,
convertCssPropertiesToCamelCase,
screenshotOutputFolder,
getNormalizedKeyAttributeValue,
isModifierKey,
clearString,
requireWithFallback,
normalizeSpacesInString,
relativeDir,
} = require('../utils')
const { isColorProperty, convertColorToRGBA } = require('../colorUtils')
const ElementNotFound = require('./errors/ElementNotFound')
const RemoteBrowserConnectionRefused = require('./errors/RemoteBrowserConnectionRefused')
const Popup = require('./extras/Popup')
const Console = require('./extras/Console')
const { findReact, findVue, findByPlaywrightLocator } = require('./extras/PlaywrightReactVueLocator')
let playwright
let perfTiming
let defaultSelectorEnginesInitialized = false
const popupStore = new Popup()
const consoleLogStore = new Console()
const availableBrowsers = ['chromium', 'webkit', 'firefox', 'electron']
const { setRestartStrategy, restartsSession, restartsContext, restartsBrowser } = require('./extras/PlaywrightRestartOpts')
const { createValueEngine, createDisabledEngine } = require('./extras/PlaywrightPropEngine')
const { seeElementError, dontSeeElementError, dontSeeElementInDOMError, seeElementInDOMError } = require('./errors/ElementAssertion')
const { dontSeeTraffic, seeTraffic, grabRecordedNetworkTraffics, stopRecordingTraffic, flushNetworkTraffics } = require('./network/actions')
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.
* * 'browser' or **true** - closes browser and opens it again between tests.
* * '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).
*/
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 = requireWithFallback('playwright', 'playwright-core')
// 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
// override defaults with config
this._setConfig(config)
}
_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,
}
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 {
requireWithFallback('playwright', 'playwright-core')
} catch (e) {
return ['playwright@^1.18']
}
}
async _init() {
// register an internal selector engine for reading value property of elements in a selector
if (defaultSelectorEnginesInitialized) return
defaultSelectorEnginesInitialized = true
try {
await playwright.selectors.register('__value', createValueEngine)
await playwright.selectors.register('__disabled', createDisabledEngine)
if (process.env.testIdAttribute) await playwright.selectors.setTestIdAttribute(process.env.testIdAttribute)
} catch (e) {
console.warn(e)
}
}
_beforeSuite() {
if ((restartsSession() || restartsContext()) && !this.options.manualStart && !this.isRunning) {
this.debugSection('Session', 'Starting singleton browser session')
return this._startBrowser()
}
}
async _before(test) {
this.currentRunningTest = test
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')
},
})
if (restartsBrowser() && !this.options.manualStart) await this._startBrowser()
if (!this.isRunning && !this.options.manualStart) 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 }
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()) {
this.debugSection('New Session', JSON.stringify(this.contextOptions))
this.browserContext = await this.browser.newContext(this.contextOptions) // Adding the HTTPSError ignore in the context so that we can ignore those errors
}
}
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
if (this.isElectron) {
this.browser.close()
this.electronSessions.forEach(session => session.close())
return
}
if (restartsSession()) {
return refreshContextSession.bind(this)()
}
if (restartsBrowser()) {
this.isRunning = false
return this._stopBrowser()
}
// close other sessions
try {
if ((await this.browser)._type === 'Browser') {
const contexts = await this.browser.contexts()
const currentContext = contexts[0]
if (currentContext && (this.options.keepCookies || this.options.keepBrowserState)) {
this.storageState = await currentContext.storageState()
}
await Promise.all(contexts.map(c => c.close()))
}
} catch (e) {
console.log(e)
}
// await this.closeOtherTabs();
return this.browser
}
_afterSuite() {}
async _finishTest() {
if ((restartsSession() || restartsContext()) && this.isRunning) return this._stopBrowser()
}
_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 {
browserContext = await this.browser.newContext(Object.assign(this.contextOptions, config))
page = await browserContext.newPage()
} catch (e) {
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]
}
}
}
if (this.options.trace) await browserContext.tracing.start({ screenshots: true, snapshots: true })
await targetCreatedHandler.call(this, page)
await this._setPage(page)
// Create a new page inside context.
return browserContext
},
stop: async () => {
// is closed by _after
},
loadVars: async context => {
if (context) {
this.browserContext = context
const existingPages = await context.pages()
this.sessionPages[this.activeSessionName] = existingPages[0]
return this._setPage(this.sessionPages[this.activeSessionName])
}
},
restoreVars: async session => {
this.withinLocator = null
this.browserContext = defaultContext
if (!session) {
this.activeSessionName = ''
} else {
this.activeSessionName = session
}
const existingPages = await this.browserContext.pages()
await this._setPage(existingPages[0])
return this._waitForAction()
},
}
}
/**
* Use Playwright API inside a test.
*
* First argument is a description of an action.
* Second argument is async function that gets this helper as parameter.
*
* { [`page`](https://github.com/microsoft/playwright/blob/main/docs/src/api/class-page.md), [`browserContext`](https://github.com/microsoft/playwright/blob/main/docs/src/api/class-browsercontext.md) [`browser`](https://github.com/microsoft/playwright/blob/main/docs/src/api/class-browser.md) } objects from Playwright API are available.
*
* ```js
* I.usePlaywrightTo('emulate offline mode', async ({ browserContext }) => {
* await browserContext.setOffline(true);
* });
* ```
*
* @param {string} description used to show in logs.
* @param {function} fn async function that executed with Playwright helper as arguments
*/
usePlaywrightTo(description, fn) {
return this._useTo(...arguments)
}
/**
* Set the automatic popup response to Accept.
* This must be set before a popup is triggered.
*
* ```js
* I.amAcceptingPopups();
* I.click('#triggerPopup');
* I.acceptPopup();
* ```
*/
amAcceptingPopups() {
popupStore.actionType = 'accept'
}
/**
* Accepts the active JavaScript native popup window, as created by window.alert|window.confirm|window.prompt.
* Don't confuse popups with modal windows, as created by [various
* libraries](http://jster.net/category/windows-modals-popups).
*/
acceptPopup() {
popupStore.assertPopupActionType('accept')
}
/**
* Set the automatic popup response to Cancel/Dismiss.
* This must be set before a popup is triggered.
*
* ```js
* I.amCancellingPopups();
* I.click('#triggerPopup');
* I.cancelPopup();
* ```
*/
amCancellingPopups() {
popupStore.actionType = 'cancel'
}
/**
* Dismisses the active JavaScript popup, as created by window.alert|window.confirm|window.prompt.
*/
cancelPopup() {
popupStore.assertPopupActionType('cancel')
}
/**
* {{> seeInPopup }}
*/
async seeInPopup(text) {
popupStore.assertPopupVisible()
const popupText = await popupStore.popup.message()
stringIncludes('text in popup').assert(text, popupText)
}
/**
* Set current page
* @param {object} page page to set
*/
async _setPage(page) {
page = await page
this._addPopupListener(page)
this.page = page
if (!page) return
this.browserContext.setDefaultTimeout(0)
page.setDefaultNavigationTimeout(this.options.getPageTimeout)
page.setDefaultTimeout(this.options.timeout)
page.on('crash', async () => {
console.log('ERROR: Page has crashed, closing page!')
await page.close()
})
this.context = await this.page
this.contextLocator = null
await page.bringToFront()
}
/**
* Add the 'dialog' event listener to a page
* @page {playwright.Page}
*
* The popup listener handles the dialog with the predefined action when it appears on the page.
* It also saves a reference to the object which is used in seeInPopup.
*/
_addPopupListener(page) {
if (!page) {
return
}
page.removeAllListeners('dialog')
page.on('dialog', async dialog => {
popupStore.popup = dialog
const action = popupStore.actionType || this.options.defaultPopupAction
await this._waitForAction()
switch (action) {
case 'accept':
return dialog.accept()
case 'cancel':
return dialog.dismiss()
default: {
throw new Error('Unknown popup action type. Only "accept" or "cancel" are accepted')
}
}
})
}
/**
* Gets page URL including hash.
*/
async _getPageUrl() {
return this.executeScript(() => window.location.href)
}
/**
* Grab the text within the popup. If no popup is visible then it will return null
*
* ```js
* await I.grabPopupText();
* ```
* @return {Promise<string | null>}
*/
async grabPopupText() {
if (popupStore.popup) {
return popupStore.popup.message()
}
return null
}
async _startBrowser() {
if (this.isElectron) {
this.browser = await playwright._electron.launch(this.playwrightOptions)
} else if (this.isRemoteBrowser && this.isCDPConnection) {
try {
this.browser = await playwright[this.options.browser].connectOverCDP(this.playwrightOptions)
} catch (err) {
if (err.toString().indexOf('ECONNREFUSED')) {
throw new RemoteBrowserConnectionRefused(err)
}
throw err
}
} else if (this.isRemoteBrowser) {
try {
this.browser = await playwright[this.options.browser].connect(this.playwrightOptions)
} catch (err) {
if (err.toString().indexOf('ECONNREFUSED')) {
throw new RemoteBrowserConnectionRefused(err)
}
throw err
}
} else if (this.playwrightOptions.userDataDir) {
this.browser = await playwright[this.options.browser].launchPersistentContext(this.userDataDir, this.playwrightOptions)
} else {
this.browser = await playwright[this.options.browser].launch(this.playwrightOptions)
}
// works only for Chromium
this.browser.on('targetchanged', target => {
this.debugSection('Url', target.url())
})
this.isRunning = true
return this.browser
}
/**
* Create a new browser context with a page. \
* Usually it should be run from a custom helper after call of `_startBrowser()`
* @param {object} [contextOptions] See https://playwright.dev/docs/api/class-browser#browser-new-context
*/
async _createContextPage(contextOptions) {
this.browserContext = await this.browser.newContext(contextOptions)
const page = await this.browserContext.newPage()
targetCreatedHandler.call(this, page)
await this._setPage(page)
}
_getType() {
return this.browser._type
}
async _stopBrowser() {
this.withinLocator = null
await this._setPage(null)
this.context = null
this.frame = null
popupStore.clear()
if (this.options.recordHar) await this.browserContext.close()
await this.browser.close()
}
async _evaluateHandeInContext(...args) {
const context = await this._getContext()
return context.evaluateHandle(...args)
}
async _withinBegin(locator) {
if (this.withinLocator) {
throw new Error("Can't start within block inside another within block")
}
const frame = isFrameLocator(locator)
if (frame) {
if (Array.isArray(frame)) {
await this.switchTo(null)
return frame.reduce((p, frameLocator) => p.then(() => this.switchTo(frameLocator)), Promise.resolve())
}
await this.switchTo(frame)
this.withinLocator = new Locator(frame)
return
}
const el = await this._locateElement(locator)
assertElementExists(el, locator)
this.context = el
this.contextLocator = locator
this.withinLocator = new Locator(locator)
}
async _withinEnd() {
this.withinLocator = null
this.context = await this.page
this.contextLocator = null
this.frame = null
}
_extractDataFromPerformanceTiming(timing, ...dataNames) {
const navigationStart = timing.navigationStart
const extractedData = {}
dataNames.forEach(name => {
extractedData[name] = timing[name] - navigationStart
})
return extractedData
}
/**
* {{> amOnPage }}
*/
async amOnPage(url) {
if (this.isElectron) {
throw new Error('Cannot open pages inside an Electron container')
}
if (!/^\w+\:(\/\/|.+)/.test(url)) {
url = this.options.url + (!this.options.url.endsWith('/') && url.startsWith('/') ? url : `/${url}`)
this.debug(`Changed URL to base url + relative path: ${url}`)
}
if (this.options.basicAuth && this.isAuthenticated !== true) {
if (url.includes(this.options.url)) {
await this.browserContext.setHTTPCredentials(this.options.basicAuth)
this.isAuthenticated = true
}
}
await this.page.goto(url, { waitUntil: this.options.waitForNavigation })
const performanceTiming = JSON.parse(await this.page.evaluate(() => JSON.stringify(window.performance.timing)))
perfTiming = this._extractDataFromPerformanceTiming(performanceTiming, 'responseEnd', 'domInteractive', 'domContentLoadedEventEnd', 'loadEventEnd')
return this._waitForAction()
}
/**
*
* Unlike other drivers Playwright changes the size of a viewport, not the window!
* Playwright does not control the window of a browser, so it can't adjust its real size.
* It also can't maximize a window.
*
* Update configuration to change real window size on start:
*
* ```js
* // inside codecept.conf.js
* // @codeceptjs/configure package must be installed
* { setWindowSize } = require('@codeceptjs/configure');
* ````
*
* {{> resizeWindow }}
*/
async resizeWindow(width, height) {
if (width === 'maximize') {
throw new Error("Playwright can't control windows, so it can't maximize it")
}
await this.page.setViewportSize({ width, height })
return this._waitForAction()
}
/**
* Set headers for all next requests
*
* ```js
* I.setPlaywrightRequestHeaders({
* 'X-Sent-By': 'CodeceptJS',
* });
* ```
*
* @param {object} customHeaders headers to set