forked from puppeteer/puppeteer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
page.spec.js
1889 lines (1790 loc) · 80.6 KB
/
page.spec.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 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.
*/
const fs = require('fs');
const path = require('path');
const utils = require('./utils');
const {waitForEvents, getPDFPages, cssPixelsToInches} = require('./utils');
module.exports.addTests = function({testRunner, expect, defaultBrowserOptions, puppeteer, PROJECT_ROOT}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const DeviceDescriptors = require(path.join(PROJECT_ROOT, 'DeviceDescriptors'));
const iPhone = DeviceDescriptors['iPhone 6'];
const iPhoneLandscape = DeviceDescriptors['iPhone 6 landscape'];
const headless = defaultBrowserOptions.headless;
describe('Page', function() {
beforeAll(async state => {
state.browser = await puppeteer.launch(defaultBrowserOptions);
});
afterAll(async state => {
await state.browser.close();
state.browser = null;
});
beforeEach(async state => {
state.page = await state.browser.newPage();
});
afterEach(async state => {
await state.page.close();
state.page = null;
});
const testFiles = [
'browser.spec.js',
'elementhandle.spec.js',
'jshandle.spec.js',
'tracing.spec.js',
'frame.spec.js',
'input.spec.js',
'network.spec.js',
'cookies.spec.js',
'target.spec.js',
'CDPSession.spec.js',
'coverage.spec.js'
];
testFiles
.map(file => path.join(__dirname, file))
.forEach(file =>
require(file).addTests({testRunner, expect, defaultBrowserOptions, PROJECT_ROOT, puppeteer})
);
describe('Page.close', function() {
it('should reject all promises when page is closed', async({browser}) => {
const newPage = await browser.newPage();
const neverResolves = newPage.evaluate(() => new Promise(r => {}));
newPage.close();
let error = null;
await neverResolves.catch(e => error = e);
expect(error.message).toContain('Protocol error');
});
it('should not be visible in browser.pages', async({browser}) => {
const newPage = await browser.newPage();
expect(await browser.pages()).toContain(newPage);
await newPage.close();
expect(await browser.pages()).not.toContain(newPage);
});
});
describe('Page.Events.error', function() {
it('should throw when page crashes', async({page}) => {
let error = null;
page.on('error', err => error = err);
page.goto('chrome://crash').catch(e => {});
await waitForEvents(page, 'error');
expect(error.message).toBe('Page crashed!');
});
});
describe('Page.evaluate', function() {
it('should work', async({page, server}) => {
const result = await page.evaluate(() => 7 * 3);
expect(result).toBe(21);
});
it('should throw when evaluation triggers reload', async({page, server}) => {
let error = null;
await page.evaluate(() => {
location.reload();
return new Promise(resolve => {
setTimeout(() => resolve(1), 0);
});
}).catch(e => error = e);
expect(error.message).toContain('Protocol error');
});
it('should await promise', async({page, server}) => {
const result = await page.evaluate(() => Promise.resolve(8 * 7));
expect(result).toBe(56);
});
it('should work right after framenavigated', async({page, server}) => {
let frameEvaluation = null;
page.on('framenavigated', async frame => {
frameEvaluation = frame.evaluate(() => 6 * 7);
});
await page.goto(server.EMPTY_PAGE);
expect(await frameEvaluation).toBe(42);
});
it('should work from-inside an exposed function', async({page, server}) => {
// Setup inpage callback, which calls Page.evaluate
await page.exposeFunction('callController', async function(a, b) {
return await page.evaluate((a, b) => a * b, a, b);
});
const result = await page.evaluate(async function() {
return await callController(9, 3);
});
expect(result).toBe(27);
});
it('should reject promise with exception', async({page, server}) => {
let error = null;
await page.evaluate(() => not.existing.object.property).catch(e => error = e);
expect(error).toBeTruthy();
expect(error.message).toContain('not is not defined');
});
it('should return complex objects', async({page, server}) => {
const object = {foo: 'bar!'};
const result = await page.evaluate(a => a, object);
expect(result).not.toBe(object);
expect(result).toEqual(object);
});
it('should return NaN', async({page, server}) => {
const result = await page.evaluate(() => NaN);
expect(Object.is(result, NaN)).toBe(true);
});
it('should return -0', async({page, server}) => {
const result = await page.evaluate(() => -0);
expect(Object.is(result, -0)).toBe(true);
});
it('should return Infinity', async({page, server}) => {
const result = await page.evaluate(() => Infinity);
expect(Object.is(result, Infinity)).toBe(true);
});
it('should return -Infinity', async({page, server}) => {
const result = await page.evaluate(() => -Infinity);
expect(Object.is(result, -Infinity)).toBe(true);
});
it('should accept "undefined" as one of multiple parameters', async({page, server}) => {
const result = await page.evaluate((a, b) => Object.is(a, undefined) && Object.is(b, 'foo'), undefined, 'foo');
expect(result).toBe(true);
});
it('should properly serialize null fields', async({page}) => {
expect(await page.evaluate(() => ({a: undefined}))).toEqual({});
});
it('should fail for window object', async({page, server}) => {
const result = await page.evaluate(() => window);
expect(result).toBe(undefined);
});
it('should fail for circular object', async({page, server}) => {
const result = await page.evaluate(() => {
const a = {};
const b = {a};
a.b = b;
return a;
});
expect(result).toBe(undefined);
});
it('should accept a string', async({page, server}) => {
const result = await page.evaluate('1 + 2');
expect(result).toBe(3);
});
it('should accept a string with semi colons', async({page, server}) => {
const result = await page.evaluate('1 + 5;');
expect(result).toBe(6);
});
it('should accept a string with comments', async({page, server}) => {
const result = await page.evaluate('2 + 5;\n// do some math!');
expect(result).toBe(7);
});
it('should accept element handle as an argument', async({page, server}) => {
await page.setContent('<section>42</section>');
const element = await page.$('section');
const text = await page.evaluate(e => e.textContent, element);
expect(text).toBe('42');
});
it('should throw if underlying element was disposed', async({page, server}) => {
await page.setContent('<section>39</section>');
const element = await page.$('section');
expect(element).toBeTruthy();
await element.dispose();
let error = null;
await page.evaluate(e => e.textContent, element).catch(e => error = e);
expect(error.message).toContain('JSHandle is disposed');
});
it('should throw if elementHandles are from other frames', async({page, server}) => {
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
const bodyHandle = await page.frames()[1].$('body');
let error = null;
await page.evaluate(body => body.innerHTML, bodyHandle).catch(e => error = e);
expect(error).toBeTruthy();
expect(error.message).toContain('JSHandles can be evaluated only in the context they were created');
});
it('should accept object handle as an argument', async({page, server}) => {
const navigatorHandle = await page.evaluateHandle(() => navigator);
const text = await page.evaluate(e => e.userAgent, navigatorHandle);
expect(text).toContain('Mozilla');
});
it('should accept object handle to primitive types', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => 5);
const isFive = await page.evaluate(e => Object.is(e, 5), aHandle);
expect(isFive).toBeTruthy();
});
});
describe('Page.setOfflineMode', function() {
it('should work', async({page, server}) => {
await page.setOfflineMode(true);
let error = null;
await page.goto(server.EMPTY_PAGE).catch(e => error = e);
expect(error).toBeTruthy();
await page.setOfflineMode(false);
const response = await page.reload();
expect(response.status()).toBe(200);
});
it('should emulate navigator.onLine', async({page, server}) => {
expect(await page.evaluate(() => window.navigator.onLine)).toBe(true);
await page.setOfflineMode(true);
expect(await page.evaluate(() => window.navigator.onLine)).toBe(false);
await page.setOfflineMode(false);
expect(await page.evaluate(() => window.navigator.onLine)).toBe(true);
});
});
describe('Page.evaluateHandle', function() {
it('should work', async({page, server}) => {
const windowHandle = await page.evaluateHandle(() => window);
expect(windowHandle).toBeTruthy();
});
});
describe('ExecutionContext.queryObjects', function() {
it('should work', async({page, server}) => {
// Instantiate an object
await page.evaluate(() => window.set = new Set(['hello', 'world']));
const prototypeHandle = await page.evaluateHandle(() => Set.prototype);
const objectsHandle = await page.queryObjects(prototypeHandle);
const count = await page.evaluate(objects => objects.length, objectsHandle);
expect(count).toBe(1);
const values = await page.evaluate(objects => Array.from(objects[0].values()), objectsHandle);
expect(values).toEqual(['hello', 'world']);
});
it('should fail for disposed handles', async({page, server}) => {
const prototypeHandle = await page.evaluateHandle(() => HTMLBodyElement.prototype);
await prototypeHandle.dispose();
let error = null;
await page.queryObjects(prototypeHandle).catch(e => error = e);
expect(error.message).toBe('Prototype JSHandle is disposed!');
});
it('should fail primitive values as prototypes', async({page, server}) => {
const prototypeHandle = await page.evaluateHandle(() => 42);
let error = null;
await page.queryObjects(prototypeHandle).catch(e => error = e);
expect(error.message).toBe('Prototype JSHandle must not be referencing primitive value');
});
});
describe('Page.waitFor', function() {
it('should wait for selector', async({page, server}) => {
let found = false;
const waitFor = page.waitFor('div').then(() => found = true);
await page.goto(server.EMPTY_PAGE);
expect(found).toBe(false);
await page.goto(server.PREFIX + '/grid.html');
await waitFor;
expect(found).toBe(true);
});
it('should wait for an xpath', async({page, server}) => {
let found = false;
const waitFor = page.waitFor('//div').then(() => found = true);
await page.goto(server.EMPTY_PAGE);
expect(found).toBe(false);
await page.goto(server.PREFIX + '/grid.html');
await waitFor;
expect(found).toBe(true);
});
it('should not allow you to select an element with single slash xpath', async({page, server}) => {
await page.setContent(`<div>some text</div>`);
let error = null;
await page.waitFor('/html/body/div').catch(e => error = e);
expect(error).toBeTruthy();
});
it('should timeout', async({page, server}) => {
const startTime = Date.now();
const timeout = 42;
await page.waitFor(timeout);
expect(Date.now() - startTime).not.toBeLessThan(timeout / 2);
});
it('should wait for predicate', async({page, server}) => {
const watchdog = page.waitFor(() => window.innerWidth < 100);
page.setViewport({width: 10, height: 10});
await watchdog;
});
it('should throw when unknown type', async({page, server}) => {
let error = null;
await page.waitFor({foo: 'bar'}).catch(e => error = e);
expect(error.message).toContain('Unsupported target type');
});
it('should wait for predicate with arguments', async({page, server}) => {
await page.waitFor((arg1, arg2) => arg1 !== arg2, {}, 1, 2);
});
});
describe('Page.Events.Console', function() {
it('should work', async({page, server}) => {
let message = null;
page.once('console', m => message = m);
await Promise.all([
page.evaluate(() => console.log('hello', 5, {foo: 'bar'})),
waitForEvents(page, 'console')
]);
expect(message.text()).toEqual('hello 5 JSHandle@object');
expect(message.type()).toEqual('log');
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', async({page, server}) => {
const messages = [];
page.on('console', msg => messages.push(msg));
await Promise.all([
page.evaluate(() => {
// A pair of time/timeEnd generates only one Console API call.
console.time('calling console.time');
console.timeEnd('calling console.time');
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!'));
}),
// Wait for 5 events to hit - console.time is not reported
waitForEvents(page, 'console', 5)
]);
expect(messages.map(msg => msg.type())).toEqual([
'timeEnd', 'trace', 'dir', 'warning', 'error', 'log'
]);
expect(messages[0].text()).toContain('calling console.time');
expect(messages.slice(1).map(msg => msg.text())).toEqual([
'calling console.trace',
'calling console.dir',
'calling console.warn',
'calling console.error',
'JSHandle@promise',
]);
});
it('should not fail for window object', async({page, server}) => {
let message = null;
page.once('console', msg => message = msg);
await Promise.all([
page.evaluate(() => console.error(window)),
waitForEvents(page, 'console')
]);
expect(message.text()).toBe('JSHandle@object');
});
});
describe('Page.Events.DOMContentLoaded', function() {
it('should fire when expected', async({page, server}) => {
page.goto('about:blank');
await waitForEvents(page, 'domcontentloaded', 1);
});
});
describe('Page.metrics', function() {
it('should get metrics from a page', async({page, server}) => {
await page.goto('about:blank');
const metrics = await page.metrics();
checkMetrics(metrics);
});
it('metrics event fired on console.timeStamp', async({page, server}) => {
const metricsPromise = new Promise(fulfill => page.once('metrics', fulfill));
await page.evaluate(() => console.timeStamp('test42'));
const metrics = await metricsPromise;
expect(metrics.title).toBe('test42');
checkMetrics(metrics.metrics);
});
function checkMetrics(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]).toBeGreaterThanOrEqual(0);
metricsToCheck.delete(name);
}
expect(metricsToCheck.size).toBe(0);
}
});
describe('Page.goto', function() {
it('should navigate to about:blank', async({page, server}) => {
const response = await page.goto('about:blank');
expect(response).toBe(null);
});
it('should navigate to empty page with domcontentloaded', async({page, server}) => {
const response = await page.goto(server.EMPTY_PAGE, {waitUntil: 'domcontentloaded'});
expect(response.status()).toBe(200);
expect(response.securityDetails()).toBe(null);
});
it('should navigate to empty page with networkidle0', async({page, server}) => {
const response = await page.goto(server.EMPTY_PAGE, {waitUntil: 'networkidle0'});
expect(response.status()).toBe(200);
});
it('should navigate to empty page with networkidle2', async({page, server}) => {
const response = await page.goto(server.EMPTY_PAGE, {waitUntil: 'networkidle2'});
expect(response.status()).toBe(200);
});
it('should fail when navigating to bad url', async({page, server}) => {
let error = null;
await page.goto('asdfasdf').catch(e => error = e);
expect(error.message).toContain('Cannot navigate to invalid URL');
});
it('should fail when navigating to bad SSL', async({page, httpsServer}) => {
// Make sure that network events do not emit 'undefined'.
// @see https://crbug.com/750469
page.on('request', request => expect(request).toBeTruthy());
page.on('requestfinished', request => expect(request).toBeTruthy());
page.on('requestfailed', request => expect(request).toBeTruthy());
let error = null;
await page.goto(httpsServer.EMPTY_PAGE).catch(e => error = e);
expect(error.message).toContain('net::ERR_CERT_AUTHORITY_INVALID');
});
it('should fail when navigating to bad SSL after redirects', async({page, server, httpsServer}) => {
server.setRedirect('/redirect/1.html', '/redirect/2.html');
server.setRedirect('/redirect/2.html', '/empty.html');
let error = null;
await page.goto(httpsServer.PREFIX + '/redirect/1.html').catch(e => error = e);
expect(error.message).toContain('net::ERR_CERT_AUTHORITY_INVALID');
});
it('should throw if networkidle is passed as an option', async({page, server}) => {
let error = null;
await page.goto(server.EMPTY_PAGE, {waitUntil: 'networkidle'}).catch(err => error = err);
expect(error.message).toContain('"networkidle" option is no longer supported');
});
it('should fail when main resources failed to load', async({page, server}) => {
let error = null;
await page.goto('http://localhost:44123/non-existing-url').catch(e => error = e);
expect(error.message).toContain('net::ERR_CONNECTION_REFUSED');
});
it('should fail when exceeding maximum navigation timeout', async({page, server}) => {
// Hang for request to the empty.html
server.setRoute('/empty.html', (req, res) => { });
let error = null;
await page.goto(server.PREFIX + '/empty.html', {timeout: 1}).catch(e => error = e);
expect(error.message).toContain('Navigation Timeout Exceeded: 1ms');
});
it('should fail when exceeding default maximum navigation timeout', async({page, server}) => {
// Hang for request to the empty.html
server.setRoute('/empty.html', (req, res) => { });
let error = null;
page.setDefaultNavigationTimeout(1);
await page.goto(server.PREFIX + '/empty.html').catch(e => error = e);
expect(error.message).toContain('Navigation Timeout Exceeded: 1ms');
});
it('should disable timeout when its set to 0', async({page, server}) => {
let error = null;
let loaded = false;
page.once('load', () => loaded = true);
await page.goto(server.PREFIX + '/grid.html', {timeout: 0, waitUntil: ['load']}).catch(e => error = e);
expect(error).toBe(null);
expect(loaded).toBe(true);
});
it('should work when navigating to valid url', async({page, server}) => {
const response = await page.goto(server.EMPTY_PAGE);
expect(response.ok()).toBe(true);
});
it('should work when navigating to data url', async({page, server}) => {
const response = await page.goto('data:text/html,hello');
expect(response.ok()).toBe(true);
});
it('should work when navigating to 404', async({page, server}) => {
const response = await page.goto(server.PREFIX + '/not-found');
expect(response.ok()).toBe(false);
expect(response.status()).toBe(404);
});
it('should return last response in redirect chain', async({page, server}) => {
server.setRedirect('/redirect/1.html', '/redirect/2.html');
server.setRedirect('/redirect/2.html', '/redirect/3.html');
server.setRedirect('/redirect/3.html', server.EMPTY_PAGE);
const response = await page.goto(server.PREFIX + '/redirect/1.html');
expect(response.ok()).toBe(true);
expect(response.url()).toBe(server.EMPTY_PAGE);
});
it('should wait for network idle to succeed navigation', async({page, server}) => {
let responses = [];
// Hold on to a bunch of requests without answering.
server.setRoute('/fetch-request-a.js', (req, res) => responses.push(res));
server.setRoute('/fetch-request-b.js', (req, res) => responses.push(res));
server.setRoute('/fetch-request-c.js', (req, res) => responses.push(res));
server.setRoute('/fetch-request-d.js', (req, res) => responses.push(res));
const initialFetchResourcesRequested = Promise.all([
server.waitForRequest('/fetch-request-a.js'),
server.waitForRequest('/fetch-request-b.js'),
server.waitForRequest('/fetch-request-c.js'),
]);
const secondFetchResourceRequested = server.waitForRequest('/fetch-request-d.js');
// Navigate to a page which loads immediately and then does a bunch of
// requests via javascript's fetch method.
const navigationPromise = page.goto(server.PREFIX + '/networkidle.html', {
waitUntil: 'networkidle0',
});
// Track when the navigation gets completed.
let navigationFinished = false;
navigationPromise.then(() => navigationFinished = true);
// Wait for the page's 'load' event.
await new Promise(fulfill => page.once('load', fulfill));
expect(navigationFinished).toBe(false);
// Wait for the initial three resources to be requested.
await initialFetchResourcesRequested;
// Expect navigation still to be not finished.
expect(navigationFinished).toBe(false);
// Respond to initial requests.
for (const response of responses) {
response.statusCode = 404;
response.end(`File not found`);
}
// Reset responses array
responses = [];
// Wait for the second round to be requested.
await secondFetchResourceRequested;
// Expect navigation still to be not finished.
expect(navigationFinished).toBe(false);
// Respond to requests.
for (const response of responses) {
response.statusCode = 404;
response.end(`File not found`);
}
const response = await navigationPromise;
// Expect navigation to succeed.
expect(response.ok()).toBe(true);
});
it('should not leak listeners during navigation', async({page, server}) => {
let warning = null;
const warningHandler = w => warning = w;
process.on('warning', warningHandler);
for (let i = 0; i < 20; ++i)
await page.goto(server.EMPTY_PAGE);
process.removeListener('warning', warningHandler);
expect(warning).toBe(null);
});
it('should not leak listeners during bad navigation', async({page, server}) => {
let warning = null;
const warningHandler = w => warning = w;
process.on('warning', warningHandler);
for (let i = 0; i < 20; ++i)
await page.goto('asdf').catch(e => {/* swallow navigation error */});
process.removeListener('warning', warningHandler);
expect(warning).toBe(null);
});
it('should navigate to dataURL and fire dataURL requests', async({page, server}) => {
const requests = [];
page.on('request', request => requests.push(request));
const dataURL = 'data:text/html,<div>yo</div>';
const response = await page.goto(dataURL);
expect(response.status()).toBe(200);
expect(requests.length).toBe(1);
expect(requests[0].url()).toBe(dataURL);
});
it('should navigate to URL with hash and fire requests without hash', async({page, server}) => {
const requests = [];
page.on('request', request => requests.push(request));
const response = await page.goto(server.EMPTY_PAGE + '#hash');
expect(response.status()).toBe(200);
expect(response.url()).toBe(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests[0].url()).toBe(server.EMPTY_PAGE);
});
it('should work with self requesting page', async({page, server}) => {
const response = await page.goto(server.PREFIX + '/self-request.html');
expect(response.status()).toBe(200);
expect(response.url()).toContain('self-request.html');
});
it('should fail when navigating and show the url at the error message', async function({page, server, httpsServer}) {
const url = httpsServer.PREFIX + '/redirect/1.html';
let error = null;
try {
await page.goto(url);
} catch (e) {
error = e;
}
expect(error.message).toContain(url);
});
});
describe('Page.waitForNavigation', function() {
it('should work', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const [result] = await Promise.all([
page.waitForNavigation(),
page.evaluate(url => window.location.href = url, server.PREFIX + '/grid.html')
]);
const response = await result;
expect(response.ok()).toBe(true);
expect(response.url()).toContain('grid.html');
});
it('should work with both domcontentloaded and load', async({page, server}) => {
let response = null;
server.setRoute('/one-style.css', (req, res) => response = res);
const navigationPromise = page.goto(server.PREFIX + '/one-style.html');
const domContentLoadedPromise = page.waitForNavigation({
waitUntil: 'domcontentloaded'
});
let bothFired = false;
const bothFiredPromise = page.waitForNavigation({
waitUntil: ['load', 'domcontentloaded']
}).then(() => bothFired = true);
await server.waitForRequest('/one-style.css');
await domContentLoadedPromise;
expect(bothFired).toBe(false);
response.end();
await bothFiredPromise;
await navigationPromise;
});
});
describe('Page.goBack', function() {
it('should work', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.goto(server.PREFIX + '/grid.html');
let response = await page.goBack();
expect(response.ok()).toBe(true);
expect(response.url()).toContain(server.EMPTY_PAGE);
response = await page.goForward();
expect(response.ok()).toBe(true);
expect(response.url()).toContain('/grid.html');
response = await page.goForward();
expect(response).toBe(null);
});
});
describe('Page.exposeFunction', function() {
it('should work', async({page, server}) => {
await page.exposeFunction('compute', function(a, b) {
return a * b;
});
const result = await page.evaluate(async function() {
return await compute(9, 4);
});
expect(result).toBe(36);
});
it('should survive navigation', async({page, server}) => {
await page.exposeFunction('compute', function(a, b) {
return a * b;
});
await page.goto(server.EMPTY_PAGE);
const result = await page.evaluate(async function() {
return await compute(9, 4);
});
expect(result).toBe(36);
});
it('should await returned promise', async({page, server}) => {
await page.exposeFunction('compute', function(a, b) {
return Promise.resolve(a * b);
});
const result = await page.evaluate(async function() {
return await compute(3, 5);
});
expect(result).toBe(15);
});
it('should work on frames', async({page, server}) => {
await page.exposeFunction('compute', function(a, b) {
return Promise.resolve(a * b);
});
await page.goto(server.PREFIX + '/frames/nested-frames.html');
const frame = page.frames()[1];
const result = await frame.evaluate(async function() {
return await compute(3, 5);
});
expect(result).toBe(15);
});
it('should work on frames before navigation', async({page, server}) => {
await page.goto(server.PREFIX + '/frames/nested-frames.html');
await page.exposeFunction('compute', function(a, b) {
return Promise.resolve(a * b);
});
const frame = page.frames()[1];
const result = await frame.evaluate(async function() {
return await compute(3, 5);
});
expect(result).toBe(15);
});
});
describe('Page.setRequestInterception', function() {
it('should intercept', async({page, server}) => {
await page.setRequestInterception(true);
page.on('request', request => {
expect(request.url()).toContain('empty.html');
expect(request.headers()['user-agent']).toBeTruthy();
expect(request.method()).toBe('GET');
expect(request.postData()).toBe(undefined);
expect(request.resourceType()).toBe('document');
expect(request.frame() === page.mainFrame()).toBe(true);
expect(request.frame().url()).toBe('about:blank');
request.continue();
});
const response = await page.goto(server.EMPTY_PAGE);
expect(response.ok()).toBe(true);
});
it('should stop intercepting', async({page, server}) => {
await page.setRequestInterception(true);
page.once('request', request => request.continue());
await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(false);
await page.goto(server.EMPTY_PAGE);
});
it('should show custom HTTP headers', async({page, server}) => {
await page.setExtraHTTPHeaders({
foo: 'bar'
});
await page.setRequestInterception(true);
page.on('request', request => {
expect(request.headers()['foo']).toBe('bar');
request.continue();
});
const response = await page.goto(server.EMPTY_PAGE);
expect(response.ok()).toBe(true);
});
it('should works with customizing referer headers', async({page, server}) => {
await page.setExtraHTTPHeaders({ 'referer': server.EMPTY_PAGE });
await page.setRequestInterception(true);
page.on('request', request => {
expect(request.headers()['referer']).toBe(server.EMPTY_PAGE);
request.continue();
});
const response = await page.goto(server.EMPTY_PAGE);
expect(response.ok()).toBe(true);
});
it('should be abortable', async({page, server}) => {
await page.setRequestInterception(true);
page.on('request', request => {
if (request.url().endsWith('.css'))
request.abort();
else
request.continue();
});
let failedRequests = 0;
page.on('requestfailed', event => ++failedRequests);
const response = await page.goto(server.PREFIX + '/one-style.html');
expect(response.ok()).toBe(true);
expect(response.request().failure()).toBe(null);
expect(failedRequests).toBe(1);
});
it('should be abortable with custom error codes', async({page, server}) => {
await page.setRequestInterception(true);
page.on('request', request => {
request.abort('internetdisconnected');
});
let failedRequest = null;
page.on('requestfailed', request => failedRequest = request);
await page.goto(server.EMPTY_PAGE).catch(e => {});
expect(failedRequest).toBeTruthy();
expect(failedRequest.failure().errorText).toBe('net::ERR_INTERNET_DISCONNECTED');
});
it('should send referer', async({page, server}) => {
await page.setExtraHTTPHeaders({
referer: 'http://google.com/'
});
await page.setRequestInterception(true);
page.on('request', request => request.continue());
const [request] = await Promise.all([
server.waitForRequest('/grid.html'),
page.goto(server.PREFIX + '/grid.html'),
]);
expect(request.headers['referer']).toBe('http://google.com/');
});
it('should amend HTTP headers', async({page, server}) => {
await page.setRequestInterception(true);
page.on('request', request => {
const headers = Object.assign({}, request.headers());
headers['FOO'] = 'bar';
request.continue({ headers });
});
await page.goto(server.EMPTY_PAGE);
const [request] = await Promise.all([
server.waitForRequest('/sleep.zzz'),
page.evaluate(() => fetch('/sleep.zzz'))
]);
expect(request.headers['foo']).toBe('bar');
});
it('should fail navigation when aborting main resource', async({page, server}) => {
await page.setRequestInterception(true);
page.on('request', request => request.abort());
let error = null;
await page.goto(server.EMPTY_PAGE).catch(e => error = e);
expect(error).toBeTruthy();
expect(error.message).toContain('net::ERR_FAILED');
});
it('should work with redirects', async({page, server}) => {
await page.setRequestInterception(true);
const requests = [];
page.on('request', request => {
request.continue();
requests.push(request);
});
server.setRedirect('/non-existing-page.html', '/non-existing-page-2.html');
server.setRedirect('/non-existing-page-2.html', '/non-existing-page-3.html');
server.setRedirect('/non-existing-page-3.html', '/non-existing-page-4.html');
server.setRedirect('/non-existing-page-4.html', '/empty.html');
const response = await page.goto(server.PREFIX + '/non-existing-page.html');
expect(response.status()).toBe(200);
expect(response.url()).toContain('empty.html');
expect(requests.length).toBe(5);
expect(requests[2].resourceType()).toBe('document');
// Check redirect chain
const redirectChain = response.request().redirectChain();
expect(redirectChain.length).toBe(4);
expect(redirectChain[0].url()).toContain('/non-existing-page.html');
expect(redirectChain[2].url()).toContain('/non-existing-page-3.html');
for (let i = 0; i < redirectChain.length; ++i) {
const request = redirectChain[i];
expect(request.redirectChain().indexOf(request)).toBe(i);
}
});
it('should be able to abort redirects', async({page, server}) => {
await page.setRequestInterception(true);
server.setRedirect('/non-existing.json', '/non-existing-2.json');
server.setRedirect('/non-existing-2.json', '/simple.html');
page.on('request', request => {
if (request.url().includes('non-existing-2'))
request.abort();
else
request.continue();
});
await page.goto(server.EMPTY_PAGE);
const result = await page.evaluate(async() => {
try {
await fetch('/non-existing.json');
} catch (e) {
return e.message;
}
});
expect(result).toContain('Failed to fetch');
});
it('should work with equal requests', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
let responseCount = 1;
server.setRoute('/zzz', (req, res) => res.end((responseCount++) * 11 + ''));
await page.setRequestInterception(true);
let spinner = false;
// Cancel 2nd request.
page.on('request', request => {
spinner ? request.abort() : request.continue();
spinner = !spinner;
});
const results = await page.evaluate(() => Promise.all([
fetch('/zzz').then(response => response.text()).catch(e => 'FAILED'),
fetch('/zzz').then(response => response.text()).catch(e => 'FAILED'),
fetch('/zzz').then(response => response.text()).catch(e => 'FAILED'),
]));
expect(results).toEqual(['11', 'FAILED', '22']);
});
it('should navigate to dataURL and fire dataURL requests', async({page, server}) => {
await page.setRequestInterception(true);
const requests = [];
page.on('request', request => {
requests.push(request);
request.continue();
});
const dataURL = 'data:text/html,<div>yo</div>';
const response = await page.goto(dataURL);
expect(response.status()).toBe(200);
expect(requests.length).toBe(1);
expect(requests[0].url()).toBe(dataURL);
});
it('should abort data server', async({page, server}) => {
await page.setRequestInterception(true);
page.on('request', request => {
request.abort();
});
let error = null;
await page.goto('data:text/html,No way!').catch(err => error = err);
expect(error.message).toContain('net::ERR_FAILED');
});
it('should navigate to URL with hash and and fire requests without hash', async({page, server}) => {
await page.setRequestInterception(true);
const requests = [];
page.on('request', request => {
requests.push(request);
request.continue();
});
const response = await page.goto(server.EMPTY_PAGE + '#hash');
expect(response.status()).toBe(200);
expect(response.url()).toBe(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests[0].url()).toBe(server.EMPTY_PAGE);
});
it('should work with encoded server', async({page, server}) => {
// The requestWillBeSent will report encoded URL, whereas interception will
// report URL as-is. @see crbug.com/759388
await page.setRequestInterception(true);
page.on('request', request => request.continue());
const response = await page.goto(server.PREFIX + '/some nonexisting page');
expect(response.status()).toBe(404);
});
it('should work with badly encoded server', async({page, server}) => {
await page.setRequestInterception(true);
server.setRoute('/malformed?rnd=%911', (req, res) => res.end());
page.on('request', request => request.continue());
const response = await page.goto(server.PREFIX + '/malformed?rnd=%911');
expect(response.status()).toBe(200);
});
it('should work with encoded server - 2', async({page, server}) => {
// The requestWillBeSent will report URL as-is, whereas interception will
// report encoded URL for stylesheet. @see crbug.com/759388
await page.setRequestInterception(true);
const requests = [];
page.on('request', request => {
request.continue();
requests.push(request);
});
const response = await page.goto(`data:text/html,<link rel="stylesheet" href="${server.PREFIX}/fonts?helvetica|arial"/>`);
expect(response.status()).toBe(200);
expect(requests.length).toBe(2);
expect(requests[1].response().status()).toBe(404);
});
it('should not throw "Invalid Interception Id" if the request was cancelled', async({page, server}) => {
await page.setContent('<iframe></iframe>');
await page.setRequestInterception(true);
let request = null;
page.on('request', async r => request = r);
page.$eval('iframe', (frame, url) => frame.src = url, server.EMPTY_PAGE),
// Wait for request interception.
await waitForEvents(page, 'request');
// Delete frame to cause request to be canceled.
await page.$eval('iframe', frame => frame.remove());
let error = null;
await request.continue().catch(e => error = e);
expect(error).toBe(null);
});
it('should throw if interception is not enabled', async({page, server}) => {
let error = null;
page.on('request', async request => {
try {
await request.continue();
} catch (e) {
error = e;
}
});
await page.goto(server.EMPTY_PAGE);
expect(error.message).toContain('Request Interception is not enabled');
});
});
describe('Request.respond', function() {
it('should work', async({page, server}) => {