-
Notifications
You must be signed in to change notification settings - Fork 23
/
test-helper-puppeteer.js
931 lines (907 loc) · 27.2 KB
/
test-helper-puppeteer.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
const fs = require('fs')
const Log = require('./src/log.js')('dashboard-test-helper-puppeteer')
const path = require('path')
const puppeteer = require('puppeteer')
const util = require('util')
const wait = util.promisify(function (amount, callback) {
if (amount && !callback) {
callback = amount
amount = null
}
return setTimeout(callback, amount || 1)
})
module.exports = {
fetch,
fill,
close: () => {
if (browser && browser.close) {
browser.close()
browser = null
}
}
}
let devices, allDevices, browser
async function fetch (method, req) {
allDevices = allDevices || require('puppeteer/lib/cjs/puppeteer/common/DeviceDescriptors.js')
devices = devices || [{
name: 'Desktop',
userAgent: 'Desktop browser',
viewport: {
width: 1920,
height: 1080,
deviceScaleFactor: 1,
isMobile: false,
hasTouch: false,
isLandscape: false
}
},
allDevices.devicesMap['iPad Pro'],
allDevices.devicesMap['iPad Mini'],
allDevices.devicesMap['Pixel 2 XL'],
allDevices.devicesMap['iPhone SE']
]
browser = await relaunchBrowser()
const result = {}
const page = await launchBrowserPage()
await emulate(page, devices[0])
page.on('error', (msg) => {
if (msg && msg.text) {
Log.error('puppeteer page error', msg.text())
} else {
Log.error('puppeteer page error', msg)
}
})
page.on('console', (msg) => {
if (msg && msg.text) {
Log.error('puppeteer console msg', msg.text())
} else {
Log.error('puppeteer console msg', msg)
}
})
// these huge timeouts allow webhooks to be received, in production
// you'd send an email with a link or otherwise notify your user
// asynchronously but tests wait for webhooks to be received
await page.setDefaultTimeout(3600000)
await page.setDefaultNavigationTimeout(3600000)
await page.setBypassCSP(true)
await page.setRequestInterception(true)
page.on('request', async (request) => {
await request.continue()
})
let html
page.on('response', async (response) => {
const status = await response.status()
if (status === 302) {
const headers = response.headers()
result.redirect = headers.location
}
return status === 200
})
if (req.screenshots) {
if (req.account) {
await setCookie(page, req)
await gotoURL(page, `${global.dashboardServer}/home`)
} else {
await gotoURL(page, global.dashboardServer)
}
let screenshotNumber = 1
let lastStep
const languages = global.languages || []
if (!languages.length) {
languages.push('en')
}
for (const step of req.screenshots) {
Log.info('screenshot step', JSON.stringify(step))
if (step.save) {
if (process.env.GENERATE_SCREENSHOTS && process.env.SCREENSHOT_PATH) {
let firstTitle
for (const language of languages) {
global.language = language.code
for (const device of devices) {
await emulate(page, device)
const thisTitle = await saveScreenshot(device, page, screenshotNumber, 'index', 'page', req.filename, firstTitle)
firstTitle = firstTitle || thisTitle
}
}
}
screenshotNumber++
continue
}
if (step.hover) {
if (process.env.GENERATE_SCREENSHOTS && process.env.SCREENSHOT_PATH) {
let firstTitle
for (const language of languages) {
for (const device of devices) {
global.language = language.code
await emulate(page, device)
await execute('hover', page, step.hover)
const thisTitle = await saveScreenshot(device, page, screenshotNumber, 'hover', step.hover, req.filename, firstTitle)
firstTitle = firstTitle || thisTitle
}
}
} else {
await execute('hover', page, step.hover)
}
screenshotNumber++
} else if (step.click) {
if (process.env.GENERATE_SCREENSHOTS && process.env.SCREENSHOT_PATH) {
let firstTitle
for (const language of languages) {
global.language = language.code
for (const device of devices) {
await emulate(page, device)
if (lastStep && lastStep.hover === '#account-menu-container') {
await execute('hover', page, '#account-menu-container')
} else if (lastStep && lastStep.hover === '#administrator-menu-container') {
await execute('hover', page, '#administrator-menu-container')
}
await execute('hover', page, step.click)
await execute('focus', page, step.click)
const thisTitle = await saveScreenshot(device, page, screenshotNumber, 'click', step.click, req.filename, firstTitle)
firstTitle = firstTitle || thisTitle
}
}
} else {
if (lastStep && lastStep.hover === '#account-menu-container') {
await execute('hover', page, '#account-menu-container')
} else if (lastStep && lastStep.hover === '#administrator-menu-container') {
await execute('hover', page, '#administrator-menu-container')
}
await execute('hover', page, step.click)
}
screenshotNumber++
if (step.waitBefore) {
await step.waitBefore(page)
}
html = await getContent(page)
await execute('click', page, step.click)
if (step.waitAfter) {
await step.waitAfter(page)
} else {
await page.waitForNavigation((response) => {
const status = response.status()
return status === 200
})
}
} else if (step.fill) {
if (step.waitBefore) {
await step.waitBefore(page)
}
if (process.env.GENERATE_SCREENSHOTS && process.env.SCREENSHOT_PATH) {
let firstTitle
for (const language of languages) {
global.language = language.code
for (const device of devices) {
await emulate(page, device, req)
if (step.waitFormLoad) {
await step.waitFormLoad(page)
}
await fillForm(page, step.fill, step.body || req.body, req.uploads)
await execute('hover', page, req.button || '#submit-button')
const thisTitle = await saveScreenshot(device, page, screenshotNumber, 'submit', step.fill, req.filename, firstTitle)
firstTitle = firstTitle || thisTitle
}
}
} else {
if (step.waitFormLoad) {
await step.waitFormLoad(page)
}
await fillForm(page, step.fill, step.body || req.body, step.uploads || req.uploads)
}
screenshotNumber++
await execute('focus', page, req.button || '#submit-button')
html = await getContent(page)
await execute('click', page, req.button || '#submit-button')
if (step.waitAfter) {
await step.waitAfter(page)
} else {
await page.waitForResponse((response) => {
const status = response.status()
return status === 200
})
}
html = await getContent(page)
if (html.indexOf('<meta http-equiv="refresh"') > -1) {
let redirectLocation = html.substring(html.indexOf(';url=') + 5)
redirectLocation = redirectLocation.substring(0, redirectLocation.indexOf('"'))
result.redirect = redirectLocation
}
}
lastStep = step
}
if (process.env.GENERATE_SCREENSHOTS && process.env.SCREENSHOT_PATH) {
let firstTitle
for (const language of languages) {
global.language = language.code
for (const device of devices) {
await emulate(page, device)
const thisTitle = await saveScreenshot(device, page, screenshotNumber, 'complete', null, req.filename, firstTitle)
firstTitle = firstTitle || thisTitle
}
}
}
screenshotNumber++
} else {
if (req.account) {
await setCookie(page, req)
}
await gotoURL(page, `${global.dashboardServer}${req.url}`)
if (method === 'POST') {
if (req.waitBefore) {
await req.waitBefore(page)
}
await fillForm(page, '#submit-form', req.body, req.uploads)
await execute('hover', page, req.button || '#submit-button')
html = await getContent(page)
await execute('click', page, req.button || '#submit-button')
if (req.waitAfter) {
await req.waitAfter(page)
} else {
await page.waitForResponse((response) => {
const status = response.status()
return status === 200
})
}
}
}
html = await getContent(page)
if (!result.redirect && html.indexOf('<meta http-equiv="refresh"') > -1) {
let redirectLocation = html.substring(html.indexOf(';url=') + 5)
redirectLocation = redirectLocation.substring(0, redirectLocation.indexOf('"'))
result.redirect = redirectLocation
}
if (result.redirect && !result.redirect.startsWith('/account/signin')) {
await gotoURL(page, `${global.dashboardServer}${result.redirect}`)
html = await getContent(page)
}
result.html = html
await page.close()
return result
}
async function relaunchBrowser () {
if (browser && browser.close) {
await browser.close()
browser = null
}
const launchOptions = {
headless: !(process.env.SHOW_BROWSERS === 'true'),
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--window-size=1920,1080',
'--incognito',
'--disable-dev-shm-usage',
'--disable-features=site-per-process'
],
slowMo: 10
}
if (process.env.CHROMIUM_EXECUTABLE) {
launchOptions.executablePath = process.env.CHROMIUM_EXECUTABLE
}
while (!browser) {
try {
browser = await puppeteer.launch(launchOptions)
if (browser) {
return browser
}
} catch (error) {
Log.error('error instantiating browser', error.toString())
}
await wait(100)
}
}
async function launchBrowserPage () {
let pages
while (!pages) {
try {
pages = await browser.pages()
} catch (error) {
}
if (pages && pages.length) {
break
}
await wait(100)
}
if (pages && pages.length) {
return pages[0]
}
let page
while (!page) {
try {
page = await browser.newPage()
} catch (error) {
}
if (page) {
return page
}
await wait(100)
}
}
async function gotoURL (page, url) {
while (true) {
try {
await page.goto(url, { waitLoad: true, waitNetworkIdle: true })
let content
while (!content || !content.length) {
content = await getContent(page)
}
return true
} catch (error) {
Log.error('puppeteer gotoURL error', error.toString())
}
await wait(100)
}
}
async function getContent (page) {
let html
while (!html || !html.length) {
try {
html = await page.content()
return html
} catch (error) {
}
await wait(100)
}
}
async function setCookie (page, req) {
const cookies = await page.cookies()
if (cookies.length) {
return
}
if (!req.session) {
return
}
const cookie = {
value: req.session.sessionid,
session: true,
name: 'sessionid',
url: global.dashboardServer
}
const cookie2 = {
value: req.session.token,
session: true,
name: 'token',
url: global.dashboardServer
}
while (true) {
try {
await page.setCookie(cookie)
break
} catch (error) {
}
await wait(100)
}
while (true) {
try {
await page.setCookie(cookie2)
return
} catch (error) {
}
await wait(100)
}
}
async function emulate (page, device) {
while (true) {
try {
await page.emulate(device)
return
} catch (error) {
}
await wait(100)
}
}
const screenshotCache = {
}
async function saveScreenshot (device, page, number, action, identifier, scriptName, overrideTitle) {
Log.info('taking screenshot', number, action, identifier, scriptName)
let filePath = scriptName.substring(scriptName.indexOf('/src/www/') + '/src/www/'.length)
filePath = filePath.substring(0, filePath.lastIndexOf('.test.js'))
filePath = path.join(process.env.SCREENSHOT_PATH, filePath)
if (!fs.existsSync(filePath)) {
createFolderSync(filePath)
}
let title
if (identifier === '#submit-form') {
title = 'form'
} else if (identifier === '#submit-button') {
const element = await getElement(page, identifier)
let text = await getText(page, element)
if (text.indexOf('_') > -1) {
text = text.substring(0, text.indexOf('_'))
} else {
text = text.split(' ').join('-').toLowerCase()
}
title = text
} else if (identifier && identifier[0] === '/') {
const element = await getElement(page, identifier)
let text = await getText(page, element)
if (text.indexOf('_') > -1) {
text = text.substring(0, text.indexOf('_'))
} else {
text = text.split(' ').join('-').toLowerCase()
}
title = text
} else if (action === 'index') {
title = 'index'
} else if (identifier) {
title = 'form'
} else {
title = ''
}
let filename
if (overrideTitle) {
filename = `${number}-${action}-${overrideTitle}-${device.name.split(' ').join('-')}-${global.language}.png`.toLowerCase()
} else {
if (title) {
filename = `${number}-${action}-${title}-${device.name.split(' ').join('-')}-${global.language}.png`.toLowerCase()
} else {
filename = `${number}-${action}-${device.name.split(' ').join('-')}-${global.language}.png`.toLowerCase()
}
}
if (screenshotCache[filename]) {
return fs.writeFileSync(`${filePath}/${filename}`, screenshotCache[filename])
}
await page.screenshot({ path: `${filePath}/${filename}`, type: 'png' })
if ((number === 1 && action === 'hover') ||
(number === 2 && action === 'click')) {
screenshotCache[filename] = fs.readFileSync(`${filePath}/${filename}`)
}
return title
}
async function fillForm (page, fieldContainer, body, uploads) {
while (true) {
try {
await fill(page, fieldContainer, body, uploads)
break
} catch (error) {
await wait(100)
}
}
}
async function execute (action, page, identifier) {
let method
switch (action) {
case 'hover':
method = hoverElement
break
case 'click':
method = clickElement
break
case 'focus':
method = focusElement
break
}
const element = await getElement(page, identifier)
if (element) {
return method(element, page)
}
throw new Error('element not found ' + identifier)
}
async function getText (page, element) {
return evaluate(page, (el) => {
if (!el) {
return ''
}
if (el.innerText && el.innerHTML.indexOf('>') === -1) {
return el.innerText
}
if (el.title) {
return el.title
}
for (let i = 0, len = el.children.length; i < len; i++) {
if (el.children[i].innerText) {
return el.children[i].innerText
}
if (el.children[i].title) {
return el.children[i].title
}
}
}, element)
}
async function fill (page, fieldContainer, body, uploads) {
if (!body && !uploads) {
return
}
const frame = await getOptionalApplicationFrame(page)
let formFields = await getElement(page, fieldContainer || '#submit-form')
if (!formFields && frame) {
formFields = await getElement(frame, fieldContainer || '#submit-form')
}
if (!formFields) {
formFields = await page.$('form')
if (!formFields) {
return
}
}
if (uploads) {
for (const field in uploads) {
const element = await getElement(formFields, `#${field}`)
if (element) {
await uploadFile(element, uploads[field].path)
}
continue
}
}
if (!body) {
return
}
for (const field in body) {
const element = await getElement(formFields, `#${field}`)
if (!element) {
const checkboxes = await getTags(formFields, 'input[type=checkbox]')
if (checkboxes && checkboxes.length) {
for (const checkbox of checkboxes) {
const name = await evaluate(formFields, el => el.name, checkbox)
if (name !== field) {
continue
}
const value = await evaluate(formFields, el => el.value, checkbox)
if (value === body[field]) {
await evaluate(formFields, el => { el.checked = true }, checkbox)
} else if (!body[field]) {
await evaluate(formFields, el => { el.checked = false }, checkbox)
}
}
}
const radios = await getTags(formFields, 'input[type=radio]')
if (radios && radios.length) {
for (const radio of radios) {
const name = await evaluate(formFields, el => el.name, radio)
if (name !== field) {
continue
}
const value = await evaluate(formFields, el => el.value, radio)
if (value === body[field]) {
await evaluate(formFields, el => { el.checked = true }, radio)
} else if (!body[field]) {
await evaluate(formFields, el => { el.checked = false }, radio)
}
}
}
continue
}
const tagName = await evaluate(formFields, el => el.tagName, element)
if (!tagName) {
throw new Error('unknown tag name')
}
await focusElement(element)
if (tagName === 'TEXTAREA') {
await (frame || page).$eval(`textarea[id=${field}]`, (el, value) => { el.value = value }, body[field])
} else if (tagName === 'SELECT') {
await selectOption(element, body[field])
} else if (tagName === 'INPUT') {
const inputType = await evaluate(formFields, el => el.type, element)
if (inputType === 'radio' || inputType === 'checkbox') {
if (body[field]) {
await evaluate(formFields, el => { el.checked = true }, element)
} else {
await evaluate(formFields, el => { el.checked = false }, element)
}
} else {
if (body[field]) {
await evaluate(formFields, el => { el.value = '' }, element)
await typeInElement(element, body[field])
} else {
await evaluate(formFields, el => { el.value = '' }, element)
}
}
} else {
// inaccessible input fields such as Stripe payment information
await element.click()
await wait(1)
for (let i = 0, len = 100; i < len; i++) {
await page.keyboard.press('Backspace')
await wait(1)
}
if (field.endsWith('-container')) {
for (const char of body[field]) {
await element.focus()
await wait(1)
await element.type(char)
await wait(1)
}
} else {
await wait(1)
await clickElement(element)
await wait(1)
await typeInElement(element, body[field])
}
}
}
}
async function getElement (page, identifier) {
const frame = await getOptionalApplicationFrame(page)
let element
if (identifier.startsWith('#')) {
if (frame) {
element = await frame.$(identifier)
if (element) {
return element
}
}
element = await page.$(identifier)
if (element) {
return element
}
return null
}
let elements
if (identifier.startsWith('/')) {
if (frame) {
elements = await getTags(frame, 'a')
if (elements && elements.length) {
for (element of elements) {
const href = await evaluate(page, el => el.href, element)
if (href) {
if (href === identifier ||
href.startsWith(`${identifier}?`) ||
href.startsWith(`${identifier}&`) ||
href === `${global.dashboardServer}${identifier}` ||
href.startsWith(`${global.dashboardServer}${identifier}?`) ||
href.startsWith(`${global.dashboardServer}${identifier}&`)) {
return element
}
}
}
}
}
elements = await getTags(page, 'a')
const menuLinks = []
if (elements && elements.length) {
for (element of elements) {
const href = await evaluate(page, el => el.href, element)
const isMenu = await evaluate(page, (el) => {
return el.parentNode.id === 'account-menu' ||
el.parentNode.id === 'administrator-menu' ||
el.parentNode.parentNode.id === 'account-menu' ||
el.parentNode.parentNode.id === 'administrator-menu'
}, element)
if (isMenu) {
menuLinks.push(element)
continue
}
if (href) {
if (href === identifier ||
href.startsWith(`${identifier}?`) ||
href.startsWith(`${identifier}&`) ||
href === `${global.dashboardServer}${identifier}` ||
href.startsWith(`${global.dashboardServer}${identifier}?`) ||
href.startsWith(`${global.dashboardServer}${identifier}&`)) {
return element
}
}
}
for (element of menuLinks) {
const href = await evaluate(page, el => el.href, element)
if (href) {
if (href === identifier ||
href.startsWith(`${identifier}?`) ||
href.startsWith(`${identifier}&`) ||
href === `${global.dashboardServer}${identifier}` ||
href.startsWith(`${global.dashboardServer}${identifier}?`) ||
href.startsWith(`${global.dashboardServer}${identifier}&`)) {
return element
}
}
}
}
}
const tags = ['button', 'input', 'select', 'textarea', 'img']
for (const tag of tags) {
if (frame) {
elements = await getTags(frame, tag)
if (!elements || !elements.length) {
continue
}
for (element of elements) {
const text = await getText(element)
if (text) {
if (text === identifier || text.indexOf(identifier) > -1) {
return element
}
}
}
}
elements = await getTags(page, tag)
if (!elements || !elements.length) {
continue
}
for (element of elements) {
const text = await getText(element)
if (text) {
if (text === identifier || text.indexOf(identifier) > -1) {
return element
}
}
}
}
}
async function evaluate (page, method, element) {
let fails = 0
const active = element || page
while (true) {
try {
const thing = await active.evaluate(method, element)
return thing
} catch (error) {
Log.error('puppeteer evaluate error', error.toString())
}
fails++
if (fails > 10) {
const content = await getContent(page)
Log.error('puppeteer evaluate fail ten times', content, global.testConfiguration, global.packageJSON)
throw new Error('evaluate failed ten times')
}
await wait(100)
}
}
async function getOptionalApplicationFrame (page) {
if (!page.frames) {
return null
}
let fails = 0
while (true) {
try {
const frame = await page.frames().find(f => f.name() === 'application-iframe')
if (frame) {
return frame
}
} catch (error) {
Log.error('puppeteer getOptionalApplicationFrame error', error.toString())
}
fails++
if (fails > 10) {
return null
}
await wait(100)
}
}
async function getTags (page, tag) {
let fails = 0
while (true) {
try {
const links = await page.$$(tag)
return links
} catch (error) {
Log.error(`puppeteer getTags(${tag}) error`, error.toString())
}
fails++
if (fails > 10) {
const content = await getContent(page)
Log.error('puppeteer getTags fail ten times', content, global.testConfiguration, global.packageJSON)
throw new Error('getTags failed ten times')
}
await wait(100)
}
}
async function hoverElement (element, page) {
let fails = 0
while (true) {
try {
await element.hover()
return
} catch (error) {
Log.error('puppeteer hoverElement error', error.toString())
}
fails++
if (fails > 10) {
const content = page ? await getContent(page) : null
Log.error('puppeteer hoverElement fail ten times', content, global.testConfiguration, global.packageJSON)
throw new Error('hoverElement failed ten times')
}
await wait(100)
}
}
async function clickElement (element) {
let fails = 0
while (true) {
try {
await element.click()
return
} catch (error) {
Log.error('puppeteer clickElement error', error.toString())
}
fails++
if (fails > 10) {
Log.error('puppeteer clickElement fail ten times', element, global.testConfiguration, global.packageJSON)
throw new Error('clickElement failed ten times')
}
await wait(100)
}
}
async function focusElement (element) {
let fails = 0
while (true) {
try {
await element.focus()
return
} catch (error) {
Log.error('puppeteer focusElement error', error.toString())
}
fails++
if (fails > 10) {
Log.error('puppeteer focusElement fail ten times', element, global.testConfiguration, global.packageJSON)
throw new Error('focusElement failed ten times')
}
await wait(100)
}
}
async function uploadFile (element, path) {
let fails = 0
while (true) {
try {
await element.uploadFile(path)
return
} catch (error) {
Log.error('puppeteer uploadFile error', error.toString())
}
fails++
if (fails > 10) {
Log.error('puppeteer uploadFile fail ten times', element, global.testConfiguration, global.packageJSON)
throw new Error('uploadFile failed ten times')
}
await wait(100)
}
}
async function typeInElement (element, text) {
let fails = 0
while (true) {
try {
if (!text || !text.length) {
await element.evaluate((element) => {
element.value = ''
}, element)
return
}
await element.type(text || '')
return
} catch (error) {
Log.error('puppeteer typeInElement error', error.toString())
}
fails++
if (fails > 10) {
Log.error('puppeteer typeInElement fail ten times', element, global.testConfiguration, global.packageJSON)
throw new Error('typeElement failed ten times')
}
await wait(100)
}
}
async function selectOption (element, value) {
const id = await element.evaluate(element => element.id, element)
let fails = 0
while (true) {
try {
await element.evaluate((_, data) => {
const select = document.getElementById(data.id)
for (let i = 0, len = select.options.length; i < len; i++) {
if (select.options[i].value === data.value ||
select.options[i].text === data.value ||
select.options[i].text.indexOf(data.value) === 0 ||
select.options[i].value.indexOf(data.value) === 0) {
select.selectedIndex = i
return
}
}
}, { id, value })
return
} catch (error) {
Log.error('puppeteer selectOption error', error.toString())
}
fails++
if (fails > 10) {
Log.error('puppeteer selectOption fail ten times', element, global.testConfiguration, global.packageJSON)
throw new Error('selectOption failed ten times')
}
await wait(100)
}
}
function createFolderSync (folderPath) {
const nestedParts = folderPath.split('/')
let nestedPath = ''
for (const part of nestedParts) {
nestedPath += `/${part}`
if (!fs.existsSync(nestedPath)) {
fs.mkdirSync(nestedPath)
}
}
}