forked from puppeteer/puppeteer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
page.spec.ts
2358 lines (2141 loc) · 74.1 KB
/
page.spec.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
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
/**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import fs from 'fs';
import {ServerResponse} from 'http';
import path from 'path';
import expect from 'expect';
import {KnownDevices, TimeoutError} from 'puppeteer';
import {Metrics, Page} from 'puppeteer-core/internal/api/Page.js';
import {CDPSession} from 'puppeteer-core/internal/common/Connection.js';
import {ConsoleMessage} from 'puppeteer-core/internal/common/ConsoleMessage.js';
import {CDPPage} from 'puppeteer-core/internal/common/Page.js';
import sinon from 'sinon';
import {
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {attachFrame, detachFrame, waitEvent} from './utils.js';
describe('Page', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Page.close', function () {
it('should reject all promises when page is closed', async () => {
const {context} = getTestState();
const newPage = await context.newPage();
let error!: Error;
await Promise.all([
newPage
.evaluate(() => {
return new Promise(() => {});
})
.catch(error_ => {
return (error = error_);
}),
newPage.close(),
]);
expect(error.message).toContain('Protocol error');
});
it('should not be visible in browser.pages', async () => {
const {browser} = getTestState();
const newPage = await browser.newPage();
expect(await browser.pages()).toContain(newPage);
await newPage.close();
expect(await browser.pages()).not.toContain(newPage);
});
it('should run beforeunload if asked for', async () => {
const {context, server, isChrome} = getTestState();
const newPage = await context.newPage();
await newPage.goto(server.PREFIX + '/beforeunload.html');
// We have to interact with a page so that 'beforeunload' handlers
// fire.
await newPage.click('body');
const pageClosingPromise = newPage.close({runBeforeUnload: true});
const dialog = await waitEvent(newPage, 'dialog');
expect(dialog.type()).toBe('beforeunload');
expect(dialog.defaultValue()).toBe('');
if (isChrome) {
expect(dialog.message()).toBe('');
} else {
expect(dialog.message()).toBeTruthy();
}
await dialog.accept();
await pageClosingPromise;
});
it('should *not* run beforeunload by default', async () => {
const {context, server} = getTestState();
const newPage = await context.newPage();
await newPage.goto(server.PREFIX + '/beforeunload.html');
// We have to interact with a page so that 'beforeunload' handlers
// fire.
await newPage.click('body');
await newPage.close();
});
it('should set the page close state', async () => {
const {context} = getTestState();
const newPage = await context.newPage();
expect(newPage.isClosed()).toBe(false);
await newPage.close();
expect(newPage.isClosed()).toBe(true);
});
it('should terminate network waiters', async () => {
const {context, server} = getTestState();
const newPage = await context.newPage();
const results = await Promise.all([
newPage.waitForRequest(server.EMPTY_PAGE).catch(error => {
return error;
}),
newPage.waitForResponse(server.EMPTY_PAGE).catch(error => {
return error;
}),
newPage.close(),
]);
for (let i = 0; i < 2; i++) {
const message = results[i].message;
expect(message).toContain('Target closed');
expect(message).not.toContain('Timeout');
}
});
});
describe('Page.Events.Load', function () {
it('should fire when expected', async () => {
const {page} = getTestState();
await Promise.all([page.goto('about:blank'), waitEvent(page, 'load')]);
});
});
describe('removing and adding event handlers', () => {
it('should correctly fire event handlers as they are added and then removed', async () => {
const {page, server} = getTestState();
const handler = sinon.spy();
const onResponse = (response: {url: () => string}) => {
// Ignore default favicon requests.
if (!response.url().endsWith('favicon.ico')) {
handler();
}
};
page.on('response', onResponse);
await page.goto(server.EMPTY_PAGE);
expect(handler.callCount).toBe(1);
page.off('response', onResponse);
await page.goto(server.EMPTY_PAGE);
// Still one because we removed the handler.
expect(handler.callCount).toBe(1);
page.on('response', onResponse);
await page.goto(server.EMPTY_PAGE);
// Two now because we added the handler back.
expect(handler.callCount).toBe(2);
});
it('should correctly added and removed request events', async () => {
const {page, server} = getTestState();
const handler = sinon.spy();
const onResponse = (response: {url: () => string}) => {
// Ignore default favicon requests.
if (!response.url().endsWith('favicon.ico')) {
handler();
}
};
page.on('request', onResponse);
page.on('request', onResponse);
await page.goto(server.EMPTY_PAGE);
expect(handler.callCount).toBe(2);
page.off('request', onResponse);
await page.goto(server.EMPTY_PAGE);
// Still one because we removed the handler.
expect(handler.callCount).toBe(3);
page.off('request', onResponse);
await page.goto(server.EMPTY_PAGE);
expect(handler.callCount).toBe(3);
page.on('request', onResponse);
await page.goto(server.EMPTY_PAGE);
// Two now because we added the handler back.
expect(handler.callCount).toBe(4);
});
});
describe('Page.Events.error', function () {
it('should throw when page crashes', async () => {
const {page, isChrome} = getTestState();
let error!: Error;
page.on('error', err => {
return (error = err);
});
if (isChrome) {
page.goto('chrome://crash').catch(() => {});
} else {
page.goto('about:crashcontent').catch(() => {});
}
await waitEvent(page, 'error');
expect(error.message).toBe('Page crashed!');
});
});
describe('Page.Events.Popup', function () {
it('should work', async () => {
const {page} = getTestState();
const [popup] = await Promise.all([
new Promise<Page>(x => {
return page.once('popup', x);
}),
page.evaluate(() => {
return window.open('about:blank');
}),
]);
expect(
await page.evaluate(() => {
return !!window.opener;
})
).toBe(false);
expect(
await popup.evaluate(() => {
return !!window.opener;
})
).toBe(true);
});
it('should work with noopener', async () => {
const {page} = getTestState();
const [popup] = await Promise.all([
new Promise<Page>(x => {
return page.once('popup', x);
}),
page.evaluate(() => {
return window.open('about:blank', undefined, 'noopener');
}),
]);
expect(
await page.evaluate(() => {
return !!window.opener;
})
).toBe(false);
expect(
await popup.evaluate(() => {
return !!window.opener;
})
).toBe(false);
});
it('should work with clicking target=_blank and without rel=opener', async () => {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
await page.setContent('<a target=_blank href="/one-style.html">yo</a>');
const [popup] = await Promise.all([
new Promise<Page>(x => {
return page.once('popup', x);
}),
page.click('a'),
]);
expect(
await page.evaluate(() => {
return !!window.opener;
})
).toBe(false);
expect(
await popup.evaluate(() => {
return !!window.opener;
})
).toBe(false);
});
it('should work with clicking target=_blank and with rel=opener', async () => {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
await page.setContent(
'<a target=_blank rel=opener href="/one-style.html">yo</a>'
);
const [popup] = await Promise.all([
new Promise<Page>(x => {
return page.once('popup', x);
}),
page.click('a'),
]);
expect(
await page.evaluate(() => {
return !!window.opener;
})
).toBe(false);
expect(
await popup.evaluate(() => {
return !!window.opener;
})
).toBe(true);
});
it('should work with fake-clicking target=_blank and rel=noopener', async () => {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
await page.setContent(
'<a target=_blank rel=noopener href="/one-style.html">yo</a>'
);
const [popup] = await Promise.all([
new Promise<Page>(x => {
return page.once('popup', x);
}),
page.$eval('a', a => {
return (a as HTMLAnchorElement).click();
}),
]);
expect(
await page.evaluate(() => {
return !!window.opener;
})
).toBe(false);
expect(
await popup.evaluate(() => {
return !!window.opener;
})
).toBe(false);
});
it('should work with clicking target=_blank and rel=noopener', async () => {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
await page.setContent(
'<a target=_blank rel=noopener href="/one-style.html">yo</a>'
);
const [popup] = await Promise.all([
new Promise<Page>(x => {
return page.once('popup', x);
}),
page.click('a'),
]);
expect(
await page.evaluate(() => {
return !!window.opener;
})
).toBe(false);
expect(
await popup.evaluate(() => {
return !!window.opener;
})
).toBe(false);
});
});
describe('BrowserContext.overridePermissions', function () {
function getPermission(page: Page, name: PermissionName) {
return page.evaluate(name => {
return navigator.permissions.query({name}).then(result => {
return result.state;
});
}, name);
}
it('should be prompt by default', async () => {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
expect(await getPermission(page, 'geolocation')).toBe('prompt');
});
it('should deny permission when not listed', async () => {
const {page, server, context} = getTestState();
await page.goto(server.EMPTY_PAGE);
await context.overridePermissions(server.EMPTY_PAGE, []);
expect(await getPermission(page, 'geolocation')).toBe('denied');
});
it('should fail when bad permission is given', async () => {
const {page, server, context} = getTestState();
await page.goto(server.EMPTY_PAGE);
let error!: Error;
await context
// @ts-expect-error purposeful bad input for test
.overridePermissions(server.EMPTY_PAGE, ['foo'])
.catch(error_ => {
return (error = error_);
});
expect(error.message).toBe('Unknown permission: foo');
});
it('should grant permission when listed', async () => {
const {page, server, context} = getTestState();
await page.goto(server.EMPTY_PAGE);
await context.overridePermissions(server.EMPTY_PAGE, ['geolocation']);
expect(await getPermission(page, 'geolocation')).toBe('granted');
});
it('should reset permissions', async () => {
const {page, server, context} = getTestState();
await page.goto(server.EMPTY_PAGE);
await context.overridePermissions(server.EMPTY_PAGE, ['geolocation']);
expect(await getPermission(page, 'geolocation')).toBe('granted');
await context.clearPermissionOverrides();
expect(await getPermission(page, 'geolocation')).toBe('prompt');
});
it('should trigger permission onchange', async () => {
const {page, server, context} = getTestState();
await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => {
(globalThis as any).events = [];
return navigator.permissions
.query({name: 'geolocation'})
.then(function (result) {
(globalThis as any).events.push(result.state);
result.onchange = function () {
(globalThis as any).events.push(result.state);
};
});
});
expect(
await page.evaluate(() => {
return (globalThis as any).events;
})
).toEqual(['prompt']);
await context.overridePermissions(server.EMPTY_PAGE, []);
expect(
await page.evaluate(() => {
return (globalThis as any).events;
})
).toEqual(['prompt', 'denied']);
await context.overridePermissions(server.EMPTY_PAGE, ['geolocation']);
expect(
await page.evaluate(() => {
return (globalThis as any).events;
})
).toEqual(['prompt', 'denied', 'granted']);
await context.clearPermissionOverrides();
expect(
await page.evaluate(() => {
return (globalThis as any).events;
})
).toEqual(['prompt', 'denied', 'granted', 'prompt']);
});
it('should isolate permissions between browser contexts', async () => {
const {page, server, context, browser} = getTestState();
await page.goto(server.EMPTY_PAGE);
const otherContext = await browser.createIncognitoBrowserContext();
const otherPage = await otherContext.newPage();
await otherPage.goto(server.EMPTY_PAGE);
expect(await getPermission(page, 'geolocation')).toBe('prompt');
expect(await getPermission(otherPage, 'geolocation')).toBe('prompt');
await context.overridePermissions(server.EMPTY_PAGE, []);
await otherContext.overridePermissions(server.EMPTY_PAGE, [
'geolocation',
]);
expect(await getPermission(page, 'geolocation')).toBe('denied');
expect(await getPermission(otherPage, 'geolocation')).toBe('granted');
await context.clearPermissionOverrides();
expect(await getPermission(page, 'geolocation')).toBe('prompt');
expect(await getPermission(otherPage, 'geolocation')).toBe('granted');
await otherContext.close();
});
it('should grant persistent-storage', async () => {
const {page, server, context} = getTestState();
await page.goto(server.EMPTY_PAGE);
expect(await getPermission(page, 'persistent-storage')).not.toBe(
'granted'
);
await context.overridePermissions(server.EMPTY_PAGE, [
'persistent-storage',
]);
expect(await getPermission(page, 'persistent-storage')).toBe('granted');
});
});
describe('Page.setGeolocation', function () {
it('should work', async () => {
const {page, server, context} = getTestState();
await context.overridePermissions(server.PREFIX, ['geolocation']);
await page.goto(server.EMPTY_PAGE);
await page.setGeolocation({longitude: 10, latitude: 10});
const geolocation = await page.evaluate(() => {
return new Promise(resolve => {
return navigator.geolocation.getCurrentPosition(position => {
resolve({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
});
});
});
});
expect(geolocation).toEqual({
latitude: 10,
longitude: 10,
});
});
it('should throw when invalid longitude', async () => {
const {page} = getTestState();
let error!: Error;
try {
await page.setGeolocation({longitude: 200, latitude: 10});
} catch (error_) {
error = error_ as Error;
}
expect(error.message).toContain('Invalid longitude "200"');
});
});
describe('Page.setOfflineMode', function () {
it('should work', async () => {
const {page, server} = getTestState();
await page.setOfflineMode(true);
let error!: Error;
await page.goto(server.EMPTY_PAGE).catch(error_ => {
return (error = error_);
});
expect(error).toBeTruthy();
await page.setOfflineMode(false);
const response = (await page.reload())!;
expect(response.status()).toBe(200);
});
it('should emulate navigator.onLine', async () => {
const {page} = getTestState();
expect(
await page.evaluate(() => {
return window.navigator.onLine;
})
).toBe(true);
await page.setOfflineMode(true);
expect(
await page.evaluate(() => {
return window.navigator.onLine;
})
).toBe(false);
await page.setOfflineMode(false);
expect(
await page.evaluate(() => {
return window.navigator.onLine;
})
).toBe(true);
});
});
describe('ExecutionContext.queryObjects', function () {
it('should work', async () => {
const {page} = getTestState();
// Create a custom class
const classHandle = await page.evaluateHandle(() => {
return class CustomClass {};
});
// Create an instance.
await page.evaluate(CustomClass => {
// @ts-expect-error: Different context.
self.customClass = new CustomClass();
}, classHandle);
// Validate only one has been added.
const prototypeHandle = await page.evaluateHandle(CustomClass => {
return CustomClass.prototype;
}, classHandle);
const objectsHandle = await page.queryObjects(prototypeHandle);
await expect(
page.evaluate(objects => {
return objects.length;
}, objectsHandle)
).resolves.toBe(1);
// Check that instances.
await expect(
page.evaluate(objects => {
// @ts-expect-error: Different context.
return objects[0] === self.customClass;
}, objectsHandle)
).resolves.toBeTruthy();
});
it('should work for non-trivial page', async () => {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
// Create a custom class
const classHandle = await page.evaluateHandle(() => {
return class CustomClass {};
});
// Create an instance.
await page.evaluate(CustomClass => {
// @ts-expect-error: Different context.
self.customClass = new CustomClass();
}, classHandle);
// Validate only one has been added.
const prototypeHandle = await page.evaluateHandle(CustomClass => {
return CustomClass.prototype;
}, classHandle);
const objectsHandle = await page.queryObjects(prototypeHandle);
await expect(
page.evaluate(objects => {
return objects.length;
}, objectsHandle)
).resolves.toBe(1);
// Check that instances.
await expect(
page.evaluate(objects => {
// @ts-expect-error: Different context.
return objects[0] === self.customClass;
}, objectsHandle)
).resolves.toBeTruthy();
});
it('should fail for disposed handles', async () => {
const {page} = getTestState();
const prototypeHandle = await page.evaluateHandle(() => {
return HTMLBodyElement.prototype;
});
await prototypeHandle.dispose();
let error!: Error;
await page.queryObjects(prototypeHandle).catch(error_ => {
return (error = error_);
});
expect(error.message).toBe('Prototype JSHandle is disposed!');
});
it('should fail primitive values as prototypes', async () => {
const {page} = getTestState();
const prototypeHandle = await page.evaluateHandle(() => {
return 42;
});
let error!: Error;
await page.queryObjects(prototypeHandle).catch(error_ => {
return (error = error_);
});
expect(error.message).toBe(
'Prototype JSHandle must not be referencing primitive value'
);
});
});
describe('Page.Events.Console', function () {
it('should work', async () => {
const {page} = getTestState();
let message!: ConsoleMessage;
page.once('console', m => {
return (message = m);
});
await Promise.all([
page.evaluate(() => {
return console.log('hello', 5, {foo: 'bar'});
}),
waitEvent(page, 'console'),
]);
expect(message.text()).toEqual('hello 5 JSHandle@object');
expect(message.type()).toEqual('log');
expect(message.args()).toHaveLength(3);
expect(message.location()).toEqual({
url: expect.any(String),
lineNumber: expect.any(Number),
columnNumber: expect.any(Number),
});
expect(await message.args()[0]!.jsonValue()).toEqual('hello');
expect(await message.args()[1]!.jsonValue()).toEqual(5);
expect(await message.args()[2]!.jsonValue()).toEqual({foo: 'bar'});
});
it('should work for different console API calls with logging functions', async () => {
const {page} = getTestState();
const messages: any[] = [];
page.on('console', msg => {
return messages.push(msg);
});
// All console events will be reported before `page.evaluate` is finished.
await page.evaluate(() => {
console.trace('calling console.trace');
console.dir('calling console.dir');
console.warn('calling console.warn');
console.error('calling console.error');
console.log(Promise.resolve('should not wait until resolved!'));
});
expect(
messages.map(msg => {
return msg.type();
})
).toEqual(['trace', 'dir', 'warning', 'error', 'log']);
expect(
messages.map(msg => {
return msg.text();
})
).toEqual([
'calling console.trace',
'calling console.dir',
'calling console.warn',
'calling console.error',
'JSHandle@promise',
]);
});
it('should work for different console API calls with timing functions', async () => {
const {page} = getTestState();
const messages: any[] = [];
page.on('console', msg => {
return messages.push(msg);
});
// All console events will be reported before `page.evaluate` is finished.
await page.evaluate(() => {
// A pair of time/timeEnd generates only one Console API call.
console.time('calling console.time');
console.timeEnd('calling console.time');
});
expect(
messages.map(msg => {
return msg.type();
})
).toEqual(['timeEnd']);
expect(messages[0]!.text()).toContain('calling console.time');
});
it('should not fail for window object', async () => {
const {page} = getTestState();
let message!: ConsoleMessage;
page.once('console', msg => {
return (message = msg);
});
await Promise.all([
page.evaluate(() => {
return console.error(window);
}),
waitEvent(page, 'console'),
]);
expect(message.text()).toBe('JSHandle@object');
});
it('should trigger correct Log', async () => {
const {page, server, isChrome} = getTestState();
await page.goto('about:blank');
const [message] = await Promise.all([
waitEvent(page, 'console'),
page.evaluate(async (url: string) => {
return fetch(url).catch(() => {});
}, server.EMPTY_PAGE),
]);
expect(message.text()).toContain('Access-Control-Allow-Origin');
if (isChrome) {
expect(message.type()).toEqual('error');
} else {
expect(message.type()).toEqual('warn');
}
});
it('should have location when fetch fails', async () => {
const {page, server} = getTestState();
// The point of this test is to make sure that we report console messages from
// Log domain: https://vanilla.aslushnikov.com/?Log.entryAdded
await page.goto(server.EMPTY_PAGE);
const [message] = await Promise.all([
waitEvent(page, 'console'),
page.setContent(`<script>fetch('http://wat');</script>`),
]);
expect(message.text()).toContain(`ERR_NAME_NOT_RESOLVED`);
expect(message.type()).toEqual('error');
expect(message.location()).toEqual({
url: 'http://wat/',
lineNumber: undefined,
});
});
it('should have location and stack trace for console API calls', async () => {
const {page, server, isChrome} = getTestState();
await page.goto(server.EMPTY_PAGE);
const [message] = await Promise.all([
waitEvent(page, 'console'),
page.goto(server.PREFIX + '/consolelog.html'),
]);
expect(message.text()).toBe('yellow');
expect(message.type()).toBe('log');
expect(message.location()).toEqual({
url: server.PREFIX + '/consolelog.html',
lineNumber: 8,
columnNumber: isChrome ? 16 : 8, // console.|log vs |console.log
});
expect(message.stackTrace()).toEqual([
{
url: server.PREFIX + '/consolelog.html',
lineNumber: 8,
columnNumber: isChrome ? 16 : 8, // console.|log vs |console.log
},
{
url: server.PREFIX + '/consolelog.html',
lineNumber: 11,
columnNumber: 8,
},
{
url: server.PREFIX + '/consolelog.html',
lineNumber: 13,
columnNumber: 6,
},
]);
});
// @see https://github.com/puppeteer/puppeteer/issues/3865
it('should not throw when there are console messages in detached iframes', async () => {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
await page.evaluate(async () => {
// 1. Create a popup that Puppeteer is not connected to.
const win = window.open(
window.location.href,
'Title',
'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=0,left=0'
)!;
await new Promise(x => {
return (win.onload = x);
});
// 2. In this popup, create an iframe that console.logs a message.
win.document.body.innerHTML = `<iframe src='/consolelog.html'></iframe>`;
const frame = win.document.querySelector('iframe')!;
await new Promise(x => {
return (frame.onload = x);
});
// 3. After that, remove the iframe.
frame.remove();
});
const popupTarget = page
.browserContext()
.targets()
.find(target => {
return target !== page.target();
})!;
// 4. Connect to the popup and make sure it doesn't throw.
await popupTarget.page();
});
});
describe('Page.Events.DOMContentLoaded', function () {
it('should fire when expected', async () => {
const {page} = getTestState();
page.goto('about:blank');
await waitEvent(page, 'domcontentloaded');
});
});
describe('Page.metrics', function () {
it('should get metrics from a page', async () => {
const {page} = getTestState();
await page.goto('about:blank');
const metrics = await page.metrics();
checkMetrics(metrics);
});
it('metrics event fired on console.timeStamp', async () => {
const {page} = getTestState();
const metricsPromise = new Promise<{metrics: Metrics; title: string}>(
fulfill => {
return page.once('metrics', fulfill);
}
);
await page.evaluate(() => {
return console.timeStamp('test42');
});
const metrics = await metricsPromise;
expect(metrics.title).toBe('test42');
checkMetrics(metrics.metrics);
});
function checkMetrics(metrics: Metrics) {
const metricsToCheck = new Set([
'Timestamp',
'Documents',
'Frames',
'JSEventListeners',
'Nodes',
'LayoutCount',
'RecalcStyleCount',
'LayoutDuration',
'RecalcStyleDuration',
'ScriptDuration',
'TaskDuration',
'JSHeapUsedSize',
'JSHeapTotalSize',
]);
for (const name in metrics) {
expect(metricsToCheck.has(name)).toBeTruthy();
expect(metrics[name as keyof Metrics]).toBeGreaterThanOrEqual(0);
metricsToCheck.delete(name);
}
expect(metricsToCheck.size).toBe(0);
}
});
describe('Page.waitForRequest', function () {
it('should work', async () => {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
const [request] = await Promise.all([
page.waitForRequest(server.PREFIX + '/digits/2.png'),
page.evaluate(() => {
fetch('/digits/1.png');
fetch('/digits/2.png');
fetch('/digits/3.png');
}),
]);
expect(request.url()).toBe(server.PREFIX + '/digits/2.png');
});
it('should work with predicate', async () => {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
const [request] = await Promise.all([
page.waitForRequest(request => {
return request.url() === server.PREFIX + '/digits/2.png';
}),
page.evaluate(() => {
fetch('/digits/1.png');
fetch('/digits/2.png');
fetch('/digits/3.png');
}),
]);
expect(request.url()).toBe(server.PREFIX + '/digits/2.png');
});
it('should work with async predicate', async () => {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
const [request] = await Promise.all([
page.waitForRequest(async request => {
return request.url() === server.PREFIX + '/digits/2.png';
}),
page.evaluate(() => {
fetch('/digits/1.png');
fetch('/digits/2.png');
fetch('/digits/3.png');
}),
]);
expect(request.url()).toBe(server.PREFIX + '/digits/2.png');
});
it('should respect timeout', async () => {
const {page} = getTestState();
let error!: Error;
await page
.waitForRequest(
() => {
return false;
},
{timeout: 1}
)
.catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(TimeoutError);
});
it('should respect default timeout', async () => {
const {page} = getTestState();
let error!: Error;
page.setDefaultTimeout(1);
await page
.waitForRequest(() => {
return false;
})
.catch(error_ => {
return (error = error_);
});
expect(error).toBeInstanceOf(TimeoutError);
});
it('should work with no timeout', async () => {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
const [request] = await Promise.all([
page.waitForRequest(server.PREFIX + '/digits/2.png', {timeout: 0}),
page.evaluate(() => {
return setTimeout(() => {
fetch('/digits/1.png');
fetch('/digits/2.png');
fetch('/digits/3.png');
}, 50);
}),
]);
expect(request.url()).toBe(server.PREFIX + '/digits/2.png');
});
});
describe('Page.waitForResponse', function () {
it('should work', async () => {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
const [response] = await Promise.all([
page.waitForResponse(server.PREFIX + '/digits/2.png'),
page.evaluate(() => {
fetch('/digits/1.png');
fetch('/digits/2.png');
fetch('/digits/3.png');
}),