summaryrefslogtreecommitdiffstats
path: root/remote/test/puppeteer/test/src/elementhandle.spec.ts
blob: e0f1e4187848f5589e2bb4b9820cbc28afdffb99 (plain)
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
/**
 * @license
 * Copyright 2018 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */

import expect from 'expect';
import {Puppeteer} from 'puppeteer';
import {ElementHandle} from 'puppeteer-core/internal/api/ElementHandle.js';
import {
  asyncDisposeSymbol,
  disposeSymbol,
} from 'puppeteer-core/internal/util/disposable.js';
import sinon from 'sinon';

import {
  getTestState,
  setupTestBrowserHooks,
  shortWaitForArrayToHaveAtLeastNElements,
} from './mocha-utils.js';
import {attachFrame} from './utils.js';

describe('ElementHandle specs', function () {
  setupTestBrowserHooks();

  describe('ElementHandle.boundingBox', function () {
    it('should work', async () => {
      const {page, server} = await getTestState();

      await page.setViewport({width: 500, height: 500});
      await page.goto(server.PREFIX + '/grid.html');
      using elementHandle = (await page.$('.box:nth-of-type(13)'))!;
      const box = await elementHandle.boundingBox();
      expect(box).toEqual({x: 100, y: 50, width: 50, height: 50});
    });
    it('should handle nested frames', async () => {
      const {page, server} = await getTestState();

      await page.setViewport({width: 500, height: 500});
      await page.goto(server.PREFIX + '/frames/nested-frames.html');
      const nestedFrame = page.frames()[1]!.childFrames()[1]!;
      using elementHandle = (await nestedFrame.$('div'))!;
      const box = await elementHandle.boundingBox();
      expect(box).toEqual({x: 28, y: 182, width: 300, height: 18});
    });
    it('should return null for invisible elements', async () => {
      const {page} = await getTestState();

      await page.setContent('<div style="display:none">hi</div>');
      using element = (await page.$('div'))!;
      expect(await element.boundingBox()).toBe(null);
    });
    it('should force a layout', async () => {
      const {page} = await getTestState();

      await page.setViewport({width: 500, height: 500});
      await page.setContent(
        '<div style="width: 100px; height: 100px">hello</div>'
      );
      using elementHandle = (await page.$('div'))!;
      await page.evaluate((element: HTMLElement) => {
        return (element.style.height = '200px');
      }, elementHandle);
      const box = await elementHandle.boundingBox();
      expect(box).toEqual({x: 8, y: 8, width: 100, height: 200});
    });
    it('should work with SVG nodes', async () => {
      const {page} = await getTestState();

      await page.setContent(`
        <svg xmlns="http://www.w3.org/2000/svg" width="500" height="500">
          <rect id="theRect" x="30" y="50" width="200" height="300"></rect>
        </svg>
      `);
      using element = (await page.$(
        '#therect'
      )) as ElementHandle<SVGRectElement>;
      const pptrBoundingBox = await element.boundingBox();
      const webBoundingBox = await page.evaluate(e => {
        const rect = e.getBoundingClientRect();
        return {x: rect.x, y: rect.y, width: rect.width, height: rect.height};
      }, element);
      expect(pptrBoundingBox).toEqual(webBoundingBox);
    });
  });

  describe('ElementHandle.boxModel', function () {
    it('should work', async () => {
      const {page, server} = await getTestState();

      await page.goto(server.PREFIX + '/resetcss.html');

      // Step 1: Add Frame and position it absolutely.
      await attachFrame(page, 'frame1', server.PREFIX + '/resetcss.html');
      await page.evaluate(() => {
        const frame = document.querySelector<HTMLElement>('#frame1')!;
        frame.style.position = 'absolute';
        frame.style.left = '1px';
        frame.style.top = '2px';
      });

      // Step 2: Add div and position it absolutely inside frame.
      const frame = page.frames()[1]!;
      using divHandle = (
        await frame.evaluateHandle(() => {
          const div = document.createElement('div');
          document.body.appendChild(div);
          div.style.boxSizing = 'border-box';
          div.style.position = 'absolute';
          div.style.borderLeft = '1px solid black';
          div.style.paddingLeft = '2px';
          div.style.marginLeft = '3px';
          div.style.left = '4px';
          div.style.top = '5px';
          div.style.width = '6px';
          div.style.height = '7px';
          return div;
        })
      ).asElement()!;

      // Step 3: query div's boxModel and assert box values.
      const box = (await divHandle.boxModel())!;
      expect(box.width).toBe(6);
      expect(box.height).toBe(7);
      expect(box.margin[0]).toEqual({
        x: 1 + 4, // frame.left + div.left
        y: 2 + 5,
      });
      expect(box.border[0]).toEqual({
        x: 1 + 4 + 3, // frame.left + div.left + div.margin-left
        y: 2 + 5,
      });
      expect(box.padding[0]).toEqual({
        x: 1 + 4 + 3 + 1, // frame.left + div.left + div.marginLeft + div.borderLeft
        y: 2 + 5,
      });
      expect(box.content[0]).toEqual({
        x: 1 + 4 + 3 + 1 + 2, // frame.left + div.left + div.marginLeft + div.borderLeft + div.paddingLeft
        y: 2 + 5,
      });
    });

    it('should return null for invisible elements', async () => {
      const {page} = await getTestState();

      await page.setContent('<div style="display:none">hi</div>');
      using element = (await page.$('div'))!;
      expect(await element.boxModel()).toBe(null);
    });
  });

  describe('ElementHandle.contentFrame', function () {
    it('should work', async () => {
      const {page, server} = await getTestState();

      await page.goto(server.EMPTY_PAGE);
      await attachFrame(page, 'frame1', server.EMPTY_PAGE);
      using elementHandle = (await page.$('#frame1'))!;
      const frame = await elementHandle.contentFrame();
      expect(frame).toBe(page.frames()[1]);
    });
  });

  describe('ElementHandle.isVisible and ElementHandle.isHidden', function () {
    it('should work', async () => {
      const {page} = await getTestState();
      await page.setContent('<div style="display: none">text</div>');
      using element = (await page.waitForSelector('div'))!;
      await expect(element.isVisible()).resolves.toBeFalsy();
      await expect(element.isHidden()).resolves.toBeTruthy();
      await element.evaluate(e => {
        e.style.removeProperty('display');
      });
      await expect(element.isVisible()).resolves.toBeTruthy();
      await expect(element.isHidden()).resolves.toBeFalsy();
    });
  });

  describe('ElementHandle.click', function () {
    it('should work', async () => {
      const {page, server} = await getTestState();

      await page.goto(server.PREFIX + '/input/button.html');
      using button = (await page.$('button'))!;
      await button.click();
      expect(
        await page.evaluate(() => {
          return (globalThis as any).result;
        })
      ).toBe('Clicked');
    });
    it('should return Point data', async () => {
      const {page} = await getTestState();

      const clicks: Array<[x: number, y: number]> = [];

      await page.exposeFunction('reportClick', (x: number, y: number): void => {
        clicks.push([x, y]);
      });

      await page.evaluate(() => {
        document.body.style.padding = '0';
        document.body.style.margin = '0';
        document.body.innerHTML = `
          <div style="cursor: pointer; width: 120px; height: 60px; margin: 30px; padding: 15px;"></div>
        `;
        document.body.addEventListener('click', e => {
          (window as any).reportClick(e.clientX, e.clientY);
        });
      });

      using divHandle = (await page.$('div'))!;
      await divHandle.click();
      await divHandle.click({
        offset: {
          x: 10,
          y: 15,
        },
      });
      await shortWaitForArrayToHaveAtLeastNElements(clicks, 2);
      expect(clicks).toEqual([
        [45 + 60, 45 + 30], // margin + middle point offset
        [30 + 10, 30 + 15], // margin + offset
      ]);
    });
    it('should work for Shadow DOM v1', async () => {
      const {page, server} = await getTestState();

      await page.goto(server.PREFIX + '/shadow.html');
      using buttonHandle = await page.evaluateHandle(() => {
        // @ts-expect-error button is expected to be in the page's scope.
        return button as HTMLButtonElement;
      });
      await buttonHandle.click();
      expect(
        await page.evaluate(() => {
          // @ts-expect-error clicked is expected to be in the page's scope.
          return clicked;
        })
      ).toBe(true);
    });
    it('should not work for TextNodes', async () => {
      const {page, server} = await getTestState();

      await page.goto(server.PREFIX + '/input/button.html');
      using buttonTextNode = await page.evaluateHandle(() => {
        return document.querySelector('button')!.firstChild as HTMLElement;
      });
      let error!: Error;
      await buttonTextNode.click().catch(error_ => {
        return (error = error_);
      });
      expect(error.message).atLeastOneToContain([
        'Node is not of type HTMLElement',
        'no such node',
      ]);
    });
    it('should throw for detached nodes', async () => {
      const {page, server} = await getTestState();

      await page.goto(server.PREFIX + '/input/button.html');
      using button = (await page.$('button'))!;
      await page.evaluate((button: HTMLElement) => {
        return button.remove();
      }, button);
      let error!: Error;
      await button.click().catch(error_ => {
        return (error = error_);
      });
      expect(error.message).atLeastOneToContain([
        'Node is detached from document',
        'no such node',
      ]);
    });
    it('should throw for hidden nodes', async () => {
      const {page, server} = await getTestState();

      await page.goto(server.PREFIX + '/input/button.html');
      using button = (await page.$('button'))!;
      await page.evaluate((button: HTMLElement) => {
        return (button.style.display = 'none');
      }, button);
      const error = await button.click().catch(error_ => {
        return error_;
      });
      expect(error.message).atLeastOneToContain([
        'Node is either not clickable or not an Element',
        'no such element',
      ]);
    });
    it('should throw for recursively hidden nodes', async () => {
      const {page, server} = await getTestState();

      await page.goto(server.PREFIX + '/input/button.html');
      using button = (await page.$('button'))!;
      await page.evaluate((button: HTMLElement) => {
        return (button.parentElement!.style.display = 'none');
      }, button);
      const error = await button.click().catch(error_ => {
        return error_;
      });
      expect(error.message).atLeastOneToContain([
        'Node is either not clickable or not an Element',
        'no such element',
      ]);
    });
    it('should throw for <br> elements', async () => {
      const {page} = await getTestState();

      await page.setContent('hello<br>goodbye');
      using br = (await page.$('br'))!;
      const error = await br.click().catch(error_ => {
        return error_;
      });
      expect(error.message).atLeastOneToContain([
        'Node is either not clickable or not an Element',
        'no such node',
      ]);
    });
  });

  describe('ElementHandle.clickablePoint', function () {
    it('should work', async () => {
      const {page} = await getTestState();

      await page.evaluate(() => {
        document.body.style.padding = '0';
        document.body.style.margin = '0';
        document.body.innerHTML = `
          <div style="cursor: pointer; width: 120px; height: 60px; margin: 30px; padding: 15px;"></div>
        `;
      });
      await page.evaluate(async () => {
        return await new Promise(resolve => {
          return window.requestAnimationFrame(resolve);
        });
      });
      using divHandle = (await page.$('div'))!;
      expect(await divHandle.clickablePoint()).toEqual({
        x: 45 + 60, // margin + middle point offset
        y: 45 + 30, // margin + middle point offset
      });
      expect(
        await divHandle.clickablePoint({
          x: 10,
          y: 15,
        })
      ).toEqual({
        x: 30 + 10, // margin + offset
        y: 30 + 15, // margin + offset
      });
    });

    it('should not work if the click box is not visible', async () => {
      const {page} = await getTestState();

      await page.setContent(
        '<button style="width: 10px; height: 10px; position: absolute; left: -20px"></button>'
      );
      using handle = await page.locator('button').waitHandle();
      await expect(handle.clickablePoint()).rejects.toBeInstanceOf(Error);

      await page.setContent(
        '<button style="width: 10px; height: 10px; position: absolute; right: -20px"></button>'
      );
      using handle2 = await page.locator('button').waitHandle();
      await expect(handle2.clickablePoint()).rejects.toBeInstanceOf(Error);

      await page.setContent(
        '<button style="width: 10px; height: 10px; position: absolute; top: -20px"></button>'
      );
      using handle3 = await page.locator('button').waitHandle();
      await expect(handle3.clickablePoint()).rejects.toBeInstanceOf(Error);

      await page.setContent(
        '<button style="width: 10px; height: 10px; position: absolute; bottom: -20px"></button>'
      );
      using handle4 = await page.locator('button').waitHandle();
      await expect(handle4.clickablePoint()).rejects.toBeInstanceOf(Error);
    });

    it('should not work if the click box is not visible due to the iframe', async () => {
      const {page} = await getTestState();

      await page.setContent(
        `<iframe name='frame' style='position: absolute; left: -100px' srcdoc="<button style='width: 10px; height: 10px;'></button>"></iframe>`
      );
      const frame = await page.waitForFrame(frame => {
        return frame.name() === 'frame';
      });

      using handle = await frame.locator('button').waitHandle();
      await expect(handle.clickablePoint()).rejects.toBeInstanceOf(Error);

      await page.setContent(
        `<iframe name='frame2' style='position: absolute; top: -100px' srcdoc="<button style='width: 10px; height: 10px;'></button>"></iframe>`
      );
      const frame2 = await page.waitForFrame(frame => {
        return frame.name() === 'frame2';
      });

      using handle2 = await frame2.locator('button').waitHandle();
      await expect(handle2.clickablePoint()).rejects.toBeInstanceOf(Error);
    });

    it('should work for iframes', async () => {
      const {page} = await getTestState();
      await page.evaluate(() => {
        document.body.style.padding = '10px';
        document.body.style.margin = '10px';
        document.body.innerHTML = `
          <iframe style="border: none; margin: 0; padding: 0;" seamless sandbox srcdoc="<style>* { margin: 0; padding: 0;}</style><div style='cursor: pointer; width: 120px; height: 60px; margin: 30px; padding: 15px;' />"></iframe>
        `;
      });
      await page.evaluate(async () => {
        return await new Promise(resolve => {
          return window.requestAnimationFrame(resolve);
        });
      });
      const frame = page.frames()[1]!;
      using divHandle = (await frame.$('div'))!;
      expect(await divHandle.clickablePoint()).toEqual({
        x: 20 + 45 + 60, // iframe pos + margin + middle point offset
        y: 20 + 45 + 30, // iframe pos + margin + middle point offset
      });
      expect(
        await divHandle.clickablePoint({
          x: 10,
          y: 15,
        })
      ).toEqual({
        x: 20 + 30 + 10, // iframe pos + margin + offset
        y: 20 + 30 + 15, // iframe pos + margin + offset
      });
    });
  });

  describe('Element.waitForSelector', () => {
    it('should wait correctly with waitForSelector on an element', async () => {
      const {page} = await getTestState();
      const waitFor = page.waitForSelector('.foo').catch(err => {
        return err;
      }) as Promise<ElementHandle<HTMLDivElement>>;
      // Set the page content after the waitFor has been started.
      await page.setContent(
        '<div id="not-foo"></div><div class="bar">bar2</div><div class="foo">Foo1</div>'
      );
      using element = (await waitFor)!;
      if (element instanceof Error) {
        throw element;
      }
      expect(element).toBeDefined();

      const innerWaitFor = element.waitForSelector('.bar').catch(err => {
        return err;
      }) as Promise<ElementHandle<HTMLDivElement>>;
      await element.evaluate(el => {
        el.innerHTML = '<div class="bar">bar1</div>';
      });
      using element2 = (await innerWaitFor)!;
      if (element2 instanceof Error) {
        throw element2;
      }
      expect(element2).toBeDefined();
      expect(
        await element2.evaluate(el => {
          return (el as HTMLElement).innerText;
        })
      ).toStrictEqual('bar1');
    });

    it('should wait correctly with waitForSelector and xpath on an element', async () => {
      const {page} = await getTestState();
      // Set the page content after the waitFor has been started.
      await page.setContent(
        `<div id=el1>
          el1
          <div id=el2>
            el2
          </div>
        </div>
        <div id=el3>
          el3
        </div>`
      );

      using elById = (await page.waitForSelector(
        '#el1'
      )) as ElementHandle<HTMLDivElement>;

      using elByXpath = (await elById.waitForSelector(
        'xpath/.//div'
      )) as ElementHandle<HTMLDivElement>;
      expect(
        await elByXpath.evaluate(el => {
          return el.id;
        })
      ).toStrictEqual('el2');
    });
  });

  describe('ElementHandle.hover', function () {
    it('should work', async () => {
      const {page, server} = await getTestState();

      await page.goto(server.PREFIX + '/input/scrollable.html');
      using button = (await page.$('#button-6'))!;
      await button.hover();
      expect(
        await page.evaluate(() => {
          return document.querySelector('button:hover')!.id;
        })
      ).toBe('button-6');
    });
  });

  describe('ElementHandle.isIntersectingViewport', function () {
    it('should work', async () => {
      const {page, server} = await getTestState();

      async function getVisibilityForButton(selector: string) {
        using button = (await page.$(selector))!;
        return await button.isIntersectingViewport();
      }

      await page.goto(server.PREFIX + '/offscreenbuttons.html');
      const buttonsPromises = [];
      // Firefox seems slow when using `isIntersectingViewport`
      // so we do all the tasks asynchronously
      for (let i = 0; i < 11; ++i) {
        buttonsPromises.push(getVisibilityForButton('#btn' + i));
      }
      const buttonVisibility = await Promise.all(buttonsPromises);
      for (let i = 0; i < 11; ++i) {
        // All but last button are visible.
        const visible = i < 10;
        expect(buttonVisibility[i]).toBe(visible);
      }
    });
    it('should work with threshold', async () => {
      const {page, server} = await getTestState();

      await page.goto(server.PREFIX + '/offscreenbuttons.html');
      // a button almost cannot be seen
      // sometimes we expect to return false by isIntersectingViewport1
      using button = (await page.$('#btn11'))!;
      expect(
        await button.isIntersectingViewport({
          threshold: 0.001,
        })
      ).toBe(false);
    });
    it('should work with threshold of 1', async () => {
      const {page, server} = await getTestState();

      await page.goto(server.PREFIX + '/offscreenbuttons.html');
      // a button almost cannot be seen
      // sometimes we expect to return false by isIntersectingViewport1
      using button = (await page.$('#btn0'))!;
      expect(
        await button.isIntersectingViewport({
          threshold: 1,
        })
      ).toBe(true);
    });
    it('should work with svg elements', async () => {
      const {page, server} = await getTestState();

      await page.goto(server.PREFIX + '/inline-svg.html');
      const [visibleCircle, visibleSvg] = await Promise.all([
        page.$('circle'),
        page.$('svg'),
      ]);

      // Firefox seems slow when using `isIntersectingViewport`
      // so we do all the tasks asynchronously
      const [
        circleThresholdOne,
        circleThresholdZero,
        svgThresholdOne,
        svgThresholdZero,
      ] = await Promise.all([
        visibleCircle!.isIntersectingViewport({
          threshold: 1,
        }),
        visibleCircle!.isIntersectingViewport({
          threshold: 0,
        }),
        visibleSvg!.isIntersectingViewport({
          threshold: 1,
        }),
        visibleSvg!.isIntersectingViewport({
          threshold: 0,
        }),
      ]);

      expect(circleThresholdOne).toBe(true);
      expect(circleThresholdZero).toBe(true);
      expect(svgThresholdOne).toBe(true);
      expect(svgThresholdZero).toBe(true);

      const [invisibleCircle, invisibleSvg] = await Promise.all([
        page.$('div circle'),
        page.$('div svg'),
      ]);

      // Firefox seems slow when using `isIntersectingViewport`
      // so we do all the tasks asynchronously
      const [
        invisibleCircleThresholdOne,
        invisibleCircleThresholdZero,
        invisibleSvgThresholdOne,
        invisibleSvgThresholdZero,
      ] = await Promise.all([
        invisibleCircle!.isIntersectingViewport({
          threshold: 1,
        }),
        invisibleCircle!.isIntersectingViewport({
          threshold: 0,
        }),
        invisibleSvg!.isIntersectingViewport({
          threshold: 1,
        }),
        invisibleSvg!.isIntersectingViewport({
          threshold: 0,
        }),
      ]);

      expect(invisibleCircleThresholdOne).toBe(false);
      expect(invisibleCircleThresholdZero).toBe(false);
      expect(invisibleSvgThresholdOne).toBe(false);
      expect(invisibleSvgThresholdZero).toBe(false);
    });
  });

  describe('Custom queries', function () {
    afterEach(() => {
      Puppeteer.clearCustomQueryHandlers();
    });
    it('should register and unregister', async () => {
      const {page} = await getTestState();
      await page.setContent('<div id="not-foo"></div><div id="foo"></div>');

      // Register.
      Puppeteer.registerCustomQueryHandler('getById', {
        queryOne: (_element, selector) => {
          return document.querySelector(`[id="${selector}"]`);
        },
      });
      using element = (await page.$(
        'getById/foo'
      )) as ElementHandle<HTMLDivElement>;
      expect(
        await page.evaluate(element => {
          return element.id;
        }, element)
      ).toBe('foo');
      const handlerNamesAfterRegistering = Puppeteer.customQueryHandlerNames();
      expect(handlerNamesAfterRegistering.includes('getById')).toBeTruthy();

      // Unregister.
      Puppeteer.unregisterCustomQueryHandler('getById');
      try {
        await page.$('getById/foo');
        throw new Error('Custom query handler name not set - throw expected');
      } catch (error) {
        expect(error).not.toStrictEqual(
          new Error('Custom query handler name not set - throw expected')
        );
      }
      const handlerNamesAfterUnregistering =
        Puppeteer.customQueryHandlerNames();
      expect(handlerNamesAfterUnregistering.includes('getById')).toBeFalsy();
    });
    it('should throw with invalid query names', async () => {
      try {
        Puppeteer.registerCustomQueryHandler('1/2/3', {
          queryOne: () => {
            return document.querySelector('foo');
          },
        });
        throw new Error(
          'Custom query handler name was invalid - throw expected'
        );
      } catch (error) {
        expect(error).toStrictEqual(
          new Error('Custom query handler names may only contain [a-zA-Z]')
        );
      }
    });
    it('should work for multiple elements', async () => {
      const {page} = await getTestState();
      await page.setContent(
        '<div id="not-foo"></div><div class="foo">Foo1</div><div class="foo baz">Foo2</div>'
      );
      Puppeteer.registerCustomQueryHandler('getByClass', {
        queryAll: (_element, selector) => {
          return [...document.querySelectorAll(`.${selector}`)];
        },
      });
      const elements = (await page.$$('getByClass/foo')) as Array<
        ElementHandle<HTMLDivElement>
      >;
      const classNames = await Promise.all(
        elements.map(async element => {
          return await page.evaluate(element => {
            return element.className;
          }, element);
        })
      );

      expect(classNames).toStrictEqual(['foo', 'foo baz']);
    });
    it('should eval correctly', async () => {
      const {page} = await getTestState();
      await page.setContent(
        '<div id="not-foo"></div><div class="foo">Foo1</div><div class="foo baz">Foo2</div>'
      );
      Puppeteer.registerCustomQueryHandler('getByClass', {
        queryAll: (_element, selector) => {
          return [...document.querySelectorAll(`.${selector}`)];
        },
      });
      const elements = await page.$$eval('getByClass/foo', divs => {
        return divs.length;
      });

      expect(elements).toBe(2);
    });
    it('should wait correctly with waitForSelector', async () => {
      const {page} = await getTestState();
      Puppeteer.registerCustomQueryHandler('getByClass', {
        queryOne: (element, selector) => {
          return (element as Element).querySelector(`.${selector}`);
        },
      });
      const waitFor = page.waitForSelector('getByClass/foo').catch(err => {
        return err;
      });

      // Set the page content after the waitFor has been started.
      await page.setContent(
        '<div id="not-foo"></div><div class="foo">Foo1</div>'
      );
      const element = await waitFor;

      if (element instanceof Error) {
        throw element;
      }

      expect(element).toBeDefined();
    });

    it('should wait correctly with waitForSelector on an element', async () => {
      const {page} = await getTestState();
      Puppeteer.registerCustomQueryHandler('getByClass', {
        queryOne: (element, selector) => {
          return (element as Element).querySelector(`.${selector}`);
        },
      });
      const waitFor = page.waitForSelector('getByClass/foo').catch(err => {
        return err;
      }) as Promise<ElementHandle<HTMLElement>>;

      // Set the page content after the waitFor has been started.
      await page.setContent(
        '<div id="not-foo"></div><div class="bar">bar2</div><div class="foo">Foo1</div>'
      );
      using element = (await waitFor)!;
      if (element instanceof Error) {
        throw element;
      }
      expect(element).toBeDefined();

      const innerWaitFor = element
        .waitForSelector('getByClass/bar')
        .catch(err => {
          return err;
        }) as Promise<ElementHandle<HTMLElement>>;

      await element.evaluate(el => {
        el.innerHTML = '<div class="bar">bar1</div>';
      });

      using element2 = (await innerWaitFor)!;
      if (element2 instanceof Error) {
        throw element2;
      }
      expect(element2).toBeDefined();
      expect(
        await element2.evaluate(el => {
          return el.innerText;
        })
      ).toStrictEqual('bar1');
    });

    it('should wait correctly with waitFor', async () => {
      /* page.waitFor is deprecated so we silence the warning to avoid test noise */
      sinon.stub(console, 'warn').callsFake(() => {});
      const {page} = await getTestState();
      Puppeteer.registerCustomQueryHandler('getByClass', {
        queryOne: (element, selector) => {
          return (element as Element).querySelector(`.${selector}`);
        },
      });
      const waitFor = page.waitForSelector('getByClass/foo').catch(err => {
        return err;
      });

      // Set the page content after the waitFor has been started.
      await page.setContent(
        '<div id="not-foo"></div><div class="foo">Foo1</div>'
      );
      const element = await waitFor;

      if (element instanceof Error) {
        throw element;
      }

      expect(element).toBeDefined();
    });
    it('should work when both queryOne and queryAll are registered', async () => {
      const {page} = await getTestState();
      await page.setContent(
        '<div id="not-foo"></div><div class="foo"><div id="nested-foo" class="foo"/></div><div class="foo baz">Foo2</div>'
      );
      Puppeteer.registerCustomQueryHandler('getByClass', {
        queryOne: (element, selector) => {
          return (element as Element).querySelector(`.${selector}`);
        },
        queryAll: (element, selector) => {
          return [...(element as Element).querySelectorAll(`.${selector}`)];
        },
      });

      using element = (await page.$('getByClass/foo'))!;
      expect(element).toBeDefined();

      const elements = await page.$$('getByClass/foo');
      expect(elements).toHaveLength(3);
    });
    it('should eval when both queryOne and queryAll are registered', async () => {
      const {page} = await getTestState();
      await page.setContent(
        '<div id="not-foo"></div><div class="foo">text</div><div class="foo baz">content</div>'
      );
      Puppeteer.registerCustomQueryHandler('getByClass', {
        queryOne: (element, selector) => {
          return (element as Element).querySelector(`.${selector}`);
        },
        queryAll: (element, selector) => {
          return [...(element as Element).querySelectorAll(`.${selector}`)];
        },
      });

      const txtContent = await page.$eval('getByClass/foo', div => {
        return div.textContent;
      });
      expect(txtContent).toBe('text');

      const txtContents = await page.$$eval('getByClass/foo', divs => {
        return divs
          .map(d => {
            return d.textContent;
          })
          .join('');
      });
      expect(txtContents).toBe('textcontent');
    });

    it('should work with function shorthands', async () => {
      const {page} = await getTestState();
      await page.setContent('<div id="not-foo"></div><div id="foo"></div>');

      Puppeteer.registerCustomQueryHandler('getById', {
        // This is a function shorthand
        queryOne(_element, selector) {
          return document.querySelector(`[id="${selector}"]`);
        },
      });

      using element = (await page.$(
        'getById/foo'
      )) as ElementHandle<HTMLDivElement>;
      expect(
        await page.evaluate(element => {
          return element.id;
        }, element)
      ).toBe('foo');
    });
  });

  describe('ElementHandle.toElement', () => {
    it('should work', async () => {
      const {page} = await getTestState();
      await page.setContent('<div class="foo">Foo1</div>');
      using element = await page.$('.foo');
      using div = await element?.toElement('div');
      expect(div).toBeDefined();
    });
  });

  describe('ElementHandle[Symbol.dispose]', () => {
    it('should work', async () => {
      const {page} = await getTestState();
      using handle = await page.evaluateHandle('document');
      const spy = sinon.spy(handle, disposeSymbol);
      {
        using _ = handle;
      }
      expect(handle).toBeInstanceOf(ElementHandle);
      expect(spy.calledOnce).toBeTruthy();
      expect(handle.disposed).toBeTruthy();
    });
  });

  describe('ElementHandle[Symbol.asyncDispose]', () => {
    it('should work', async () => {
      const {page} = await getTestState();
      using handle = await page.evaluateHandle('document');
      const spy = sinon.spy(handle, asyncDisposeSymbol);
      {
        await using _ = handle;
      }
      expect(handle).toBeInstanceOf(ElementHandle);
      expect(spy.calledOnce).toBeTruthy();
      expect(handle.disposed).toBeTruthy();
    });
  });

  describe('ElementHandle.move', () => {
    it('should work', async () => {
      const {page} = await getTestState();
      using handle = await page.evaluateHandle('document');
      const spy = sinon.spy(handle, disposeSymbol);
      {
        using _ = handle;
        handle.move();
      }
      expect(handle).toBeInstanceOf(ElementHandle);
      expect(spy.calledOnce).toBeTruthy();
      expect(handle.disposed).toBeFalsy();
    });
  });
});