/
puppeteer-element.ts
732 lines (608 loc) · 18.7 KB
/
puppeteer-element.ts
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
import type { EventInitDict, SerializedEvent } from '@stencil/core/internal';
import { cloneAttributes, MockHTMLElement, parseHtmlToFragment } from '@stencil/core/mock-doc';
import type * as puppeteer from 'puppeteer';
import type * as pd from './puppeteer-declarations';
import { addE2EListener, EventSpy, waitForEvent } from './puppeteer-events';
export class E2EElement extends MockHTMLElement implements pd.E2EElementInternal {
private _queuedActions: ElementAction[] = [];
private _queueAction(action: ElementAction) {
this._queuedActions.push(action);
}
constructor(private _page: pd.E2EPageInternal, private _elmHandle: puppeteer.ElementHandle) {
super(null, null);
_page._e2eElements.push(this);
}
find(selector: string) {
return find(this._page, this._elmHandle, selector);
}
findAll(selector: string) {
return findAll(this._page, this._elmHandle, selector);
}
callMethod(methodName: string, ...methodArgs: any[]) {
this._queueAction({
methodName: methodName,
methodArgs: methodArgs,
});
return this.e2eRunActions();
}
triggerEvent(eventName: string, eventInitDict?: EventInitDict) {
this._queueAction({
eventName: eventName,
eventInitDict: eventInitDict,
});
}
async spyOnEvent(eventName: string) {
const eventSpy = new EventSpy(eventName);
await addE2EListener(this._page, this._elmHandle, eventName, (ev: SerializedEvent) => {
eventSpy.push(ev);
});
return eventSpy;
}
override async click(options?: puppeteer.ClickOptions) {
await this._elmHandle.click(options);
await this._page.waitForChanges();
}
override async focus() {
await this._elmHandle.focus();
await this._page.waitForChanges();
}
async hover() {
await this._elmHandle.hover();
await this._page.waitForChanges();
}
async isVisible() {
this._validate();
let isVisible = false;
try {
const executionContext = this._elmHandle.executionContext();
isVisible = await executionContext.evaluate((elm) => {
return new Promise<boolean>((resolve) => {
window.requestAnimationFrame(() => {
if (elm.isConnected) {
const style = window.getComputedStyle(elm);
const isVisible =
!!style && style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0';
if (isVisible) {
window.requestAnimationFrame(() => {
elm.clientWidth;
resolve(true);
});
} else {
resolve(false);
}
} else {
resolve(false);
}
});
});
}, this._elmHandle);
} catch (e) {}
return isVisible;
}
waitForEvent(eventName: string) {
return waitForEvent(this._page, eventName, this._elmHandle);
}
waitForVisible() {
return new Promise<void>((resolve, reject) => {
const checkVisible = async () => {
const isVisible = await this.isVisible();
if (isVisible) {
clearInterval(resolveTmr);
clearTimeout(rejectTmr);
resolve();
}
};
const resolveTmr = setInterval(checkVisible, 10);
const timeout = jasmine.DEFAULT_TIMEOUT_INTERVAL * 0.5;
const timeoutError = new Error(`waitForVisible timed out: ${timeout}ms`);
const rejectTmr = setTimeout(() => {
clearTimeout(resolveTmr);
reject(timeoutError);
}, timeout);
});
}
waitForNotVisible() {
return new Promise<void>((resolve, reject) => {
const checkVisible = async () => {
const isVisible = await this.isVisible();
if (!isVisible) {
clearInterval(resolveTmr);
clearTimeout(rejectTmr);
resolve();
}
};
const resolveTmr = setInterval(checkVisible, 10);
const timeout = jasmine.DEFAULT_TIMEOUT_INTERVAL * 0.5;
const timeoutError = new Error(`waitForNotVisible timed out: ${timeout}ms`);
const rejectTmr = setTimeout(() => {
clearTimeout(resolveTmr);
reject(timeoutError);
}, timeout);
});
}
isIntersectingViewport() {
return this._elmHandle.isIntersectingViewport();
}
async press(key: puppeteer.KeyInput, options?: { text?: string; delay?: number }) {
await this._elmHandle.press(key, options);
await this._page.waitForChanges();
}
async tap() {
await this._elmHandle.tap();
await this._page.waitForChanges();
}
async type(text: string, options?: { delay: number }) {
await this._elmHandle.type(text, options);
await this._page.waitForChanges();
}
async getProperty(propertyName: string) {
this._validate();
const executionContext = this._elmHandle.executionContext();
const propValue = await executionContext.evaluate(
(elm: any, propertyName: string) => {
return elm[propertyName];
},
this._elmHandle,
propertyName
);
return propValue;
}
setProperty(propertyName: string, value: any) {
this._queueAction({
setPropertyName: propertyName,
setPropertyValue: value,
});
}
override getAttribute(name: string) {
this._validate();
return super.getAttribute(name);
}
override setAttribute(name: string, value: any) {
this._queueAction({
setAttributeName: name,
setAttributeValue: value,
});
}
override removeAttribute(name: string) {
this._queueAction({
removeAttribute: name,
});
}
toggleAttribute(name: string, force?: boolean) {
this._queueAction({
toggleAttributeName: name,
toggleAttributeForce: force,
});
}
override get classList() {
const api: any = {
add: (...classNames: string[]) => {
classNames.forEach((className) => {
this._queueAction({
classAdd: className,
});
});
},
remove: (...classNames: string[]) => {
classNames.forEach((className) => {
this._queueAction({
classRemove: className,
});
});
},
toggle: (className: string) => {
this._queueAction({
classToggle: className,
});
},
contains: (className: string) => {
this._validate();
return super.className.split(' ').includes(className);
},
};
return api;
}
override get className() {
this._validate();
return super.className;
}
override set className(value: string) {
this._queueAction({
setPropertyName: 'className',
setPropertyValue: value,
});
}
override get id() {
this._validate();
return super.id;
}
override set id(value: string) {
this._queueAction({
setPropertyName: 'id',
setPropertyValue: value,
});
}
override get innerHTML() {
this._validate();
return super.innerHTML;
}
override set innerHTML(value: string) {
this._queueAction({
setPropertyName: 'innerHTML',
setPropertyValue: value,
});
}
override get innerText() {
this._validate();
return super.innerText;
}
override set innerText(value: string) {
this._queueAction({
setPropertyName: 'innerText',
setPropertyValue: value,
});
}
override get nodeValue() {
this._validate();
return super.nodeValue;
}
override set nodeValue(value: string) {
if (typeof value === 'string') {
this._queueAction({
setPropertyName: 'nodeValue',
setPropertyValue: value,
});
}
}
override get outerHTML() {
this._validate();
return super.outerHTML;
}
override set outerHTML(_: any) {
throw new Error(`outerHTML is read-only`);
}
override get shadowRoot() {
this._validate();
return super.shadowRoot;
}
override set shadowRoot(value: any) {
super.shadowRoot = value;
}
override get tabIndex() {
this._validate();
return super.tabIndex;
}
override set tabIndex(value: number) {
this._queueAction({
setPropertyName: 'tabIndex',
setPropertyValue: value,
});
}
override get textContent() {
this._validate();
return super.textContent;
}
override set textContent(value: string) {
this._queueAction({
setPropertyName: 'textContent',
setPropertyValue: value,
});
}
override get title() {
this._validate();
return super.title;
}
override set title(value: string) {
this._queueAction({
setPropertyName: 'title',
setPropertyValue: value,
});
}
async getComputedStyle(pseudoElt?: string | null) {
const style = await this._page.evaluate(
(elm: Element, pseudoElt: string) => {
const rtn: any = {};
const computedStyle = window.getComputedStyle(elm, pseudoElt);
const keys = Object.keys(computedStyle);
keys.forEach((key) => {
if (isNaN(key as any)) {
const value = computedStyle[key as any];
if (value != null) {
rtn[key] = value;
}
} else {
const dashProp = computedStyle[key as any];
if (dashProp.includes('-')) {
const value = computedStyle.getPropertyValue(dashProp);
if (value != null) {
rtn[dashProp] = value;
}
}
}
});
return rtn;
},
this._elmHandle,
pseudoElt
);
style.getPropertyValue = (propName: string) => {
return style[propName];
};
return style;
}
async e2eRunActions() {
if (this._queuedActions.length === 0) {
return;
}
const executionContext = this._elmHandle.executionContext();
const rtn = await executionContext.evaluate(
(elm: Element, queuedActions: ElementAction[]) => {
// BROWSER CONTEXT
// cannot use async/await in here cuz typescript transpiles it in the node context
return (elm as any).componentOnReady().then(() => {
let rtn: any = null;
queuedActions.forEach((queuedAction) => {
if (queuedAction.methodName) {
rtn = (elm as any)[queuedAction.methodName].apply(elm, queuedAction.methodArgs);
} else if (queuedAction.setPropertyName) {
(elm as any)[queuedAction.setPropertyName] = queuedAction.setPropertyValue;
} else if (queuedAction.setAttributeName) {
elm.setAttribute(queuedAction.setAttributeName, queuedAction.setAttributeValue);
} else if (queuedAction.removeAttribute) {
elm.removeAttribute(queuedAction.removeAttribute);
} else if (queuedAction.toggleAttributeName) {
if (typeof queuedAction.toggleAttributeForce === 'boolean') {
elm.toggleAttribute(queuedAction.toggleAttributeName, queuedAction.toggleAttributeForce);
} else {
elm.toggleAttribute(queuedAction.toggleAttributeName);
}
} else if (queuedAction.classAdd) {
elm.classList.add(queuedAction.classAdd);
} else if (queuedAction.classRemove) {
elm.classList.remove(queuedAction.classRemove);
} else if (queuedAction.classToggle) {
elm.classList.toggle(queuedAction.classToggle);
} else if (queuedAction.eventName) {
const eventInitDict = queuedAction.eventInitDict || {};
if (typeof eventInitDict.bubbles !== 'boolean') {
eventInitDict.bubbles = true;
}
if (typeof eventInitDict.cancelable !== 'boolean') {
eventInitDict.cancelable = true;
}
if (typeof eventInitDict.composed !== 'boolean') {
eventInitDict.composed = true;
}
const ev = new CustomEvent(queuedAction.eventName, eventInitDict);
elm.dispatchEvent(ev);
}
});
if (rtn && typeof rtn.then === 'function') {
return rtn.then((value: any) => {
return value;
});
}
return rtn;
});
},
this._elmHandle,
this._queuedActions as any
);
this._queuedActions.length = 0;
return rtn;
}
async e2eSync() {
const executionContext = this._elmHandle.executionContext();
const { outerHTML, shadowRootHTML } = await executionContext.evaluate((elm) => {
return {
outerHTML: elm.outerHTML,
shadowRootHTML: elm.shadowRoot ? elm.shadowRoot.innerHTML : null,
};
}, this._elmHandle);
if (typeof shadowRootHTML === 'string') {
(this as any).shadowRoot = parseHtmlToFragment(shadowRootHTML) as any;
(this as any).shadowRoot.host = this;
} else {
(this as any).shadowRoot = null;
}
const frag = parseHtmlToFragment(outerHTML);
const rootElm = frag.firstElementChild;
this.nodeName = rootElm.nodeName;
this.attributes = cloneAttributes(rootElm.attributes);
while (this.childNodes.length > 0) {
this.removeChild(this.childNodes[0]);
}
while (rootElm.childNodes.length > 0) {
this.appendChild(rootElm.childNodes[0]);
}
}
private _validate() {
if (this._queuedActions.length > 0) {
throw new Error(`await page.waitForChanges() must be called before reading element information`);
}
}
async e2eDispose() {
if (this._elmHandle) {
await this._elmHandle.dispose();
this._elmHandle = null;
}
const index = this._page._e2eElements.indexOf(this);
if (index > -1) {
this._page._e2eElements.splice(index, 1);
}
this._page = null;
}
}
export async function find(page: pd.E2EPageInternal, rootHandle: puppeteer.ElementHandle, selector: pd.FindSelector) {
const { lightSelector, shadowSelector, text, contains } = getSelector(selector);
let elmHandle: puppeteer.ElementHandle;
if (typeof lightSelector === 'string') {
elmHandle = await findWithCssSelector(page, rootHandle, lightSelector, shadowSelector);
} else {
elmHandle = await findWithText(page, rootHandle, text, contains);
}
if (!elmHandle) {
return null;
}
const elm = new E2EElement(page, elmHandle);
await elm.e2eSync();
return elm;
}
async function findWithCssSelector(
page: pd.E2EPageInternal,
rootHandle: puppeteer.ElementHandle,
lightSelector: string,
shadowSelector: string
) {
let elmHandle = await rootHandle.$(lightSelector);
if (!elmHandle) {
return null;
}
if (shadowSelector) {
const shadowHandle = await page.evaluateHandle(
(elm: Element, shadowSelector: string) => {
if (!elm.shadowRoot) {
throw new Error(`shadow root does not exist for element: ${elm.tagName.toLowerCase()}`);
}
return elm.shadowRoot.querySelector(shadowSelector);
},
elmHandle,
shadowSelector
);
await elmHandle.dispose();
if (!shadowHandle) {
return null;
}
elmHandle = shadowHandle.asElement();
}
return elmHandle;
}
async function findWithText(
page: pd.E2EPageInternal,
rootHandle: puppeteer.ElementHandle,
text: string,
contains: string
) {
const jsHandle = await page.evaluateHandle(
(rootElm: Element, text: string, contains: string) => {
let foundElm: any = null;
function checkContent(elm: Node) {
if (!elm || foundElm) {
return;
}
if (elm.nodeType === 3) {
if (typeof text === 'string' && elm.textContent.trim() === text) {
foundElm = elm.parentElement;
return;
}
if (typeof contains === 'string' && elm.textContent.includes(contains)) {
foundElm = elm.parentElement;
return;
}
} else {
if (elm.nodeName === 'SCRIPT' || elm.nodeName === 'STYLE') {
return;
}
checkContent((elm as Element).shadowRoot);
if (elm.childNodes) {
for (let i = 0; i < elm.childNodes.length; i++) {
checkContent(elm.childNodes[i]);
}
}
}
}
checkContent(rootElm);
return foundElm;
},
rootHandle,
text,
contains
);
if (jsHandle) {
return jsHandle.asElement();
}
return null;
}
export async function findAll(
page: pd.E2EPageInternal,
rootHandle: puppeteer.ElementHandle,
selector: pd.FindSelector
) {
const foundElms: E2EElement[] = [];
const { lightSelector, shadowSelector } = getSelector(selector);
const lightElmHandles = await rootHandle.$$(lightSelector);
if (lightElmHandles.length === 0) {
return foundElms;
}
if (shadowSelector) {
// light dom selected, then shadow dom selected inside of light dom elements
for (let i = 0; i < lightElmHandles.length; i++) {
const executionContext = lightElmHandles[i].executionContext();
const shadowJsHandle = await executionContext.evaluateHandle(
(elm, shadowSelector) => {
if (!elm.shadowRoot) {
throw new Error(`shadow root does not exist for element: ${elm.tagName.toLowerCase()}`);
}
return elm.shadowRoot.querySelectorAll(shadowSelector);
},
lightElmHandles[i],
shadowSelector
);
await lightElmHandles[i].dispose();
const shadowJsProperties = await shadowJsHandle.getProperties();
await shadowJsHandle.dispose();
for (const shadowJsProperty of shadowJsProperties.values()) {
const shadowElmHandle = shadowJsProperty.asElement() as puppeteer.ElementHandle;
if (shadowElmHandle) {
const elm = new E2EElement(page, shadowElmHandle);
await elm.e2eSync();
foundElms.push(elm);
}
}
}
} else {
// light dom only
for (let i = 0; i < lightElmHandles.length; i++) {
const elm = new E2EElement(page, lightElmHandles[i]);
await elm.e2eSync();
foundElms.push(elm);
}
}
return foundElms;
}
function getSelector(selector: pd.FindSelector) {
const rtn = {
lightSelector: null as string,
shadowSelector: null as string,
text: null as string,
contains: null as string,
};
if (typeof selector === 'string') {
const splt = selector.split('>>>');
rtn.lightSelector = splt[0].trim();
rtn.shadowSelector = splt.length > 1 ? splt[1].trim() : null;
} else if (typeof selector.text === 'string') {
rtn.text = selector.text.trim();
} else if (typeof selector.contains === 'string') {
rtn.contains = selector.contains.trim();
} else {
throw new Error(`invalid find selector: ${selector}`);
}
return rtn;
}
interface ElementAction {
classAdd?: string;
classRemove?: string;
classToggle?: string;
eventName?: string;
eventInitDict?: EventInitDict;
methodName?: string;
methodArgs?: any[];
removeAttribute?: string;
setAttributeName?: string;
setAttributeValue?: any;
setPropertyName?: string;
setPropertyValue?: any;
toggleAttributeName?: string;
toggleAttributeForce?: boolean;
}