forked from puppeteer/puppeteer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.js
3268 lines (3098 loc) · 133 KB
/
test.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 rm = require('rimraf').sync;
const path = require('path');
const {helper} = require('../lib/helper');
if (process.env.COVERAGE)
helper.recordPublicAPICoverage();
console.log('Testing on Node', process.version);
const puppeteer = require('..');
const SimpleServer = require('./server/SimpleServer');
const GoldenUtils = require('./golden-utils');
const YELLOW_COLOR = '\x1b[33m';
const RESET_COLOR = '\x1b[0m';
const GOLDEN_DIR = path.join(__dirname, 'golden');
const OUTPUT_DIR = path.join(__dirname, 'output');
const PORT = 8907;
const PREFIX = 'http://localhost:' + PORT;
const CROSS_PROCESS_PREFIX = 'http://127.0.0.1:' + PORT;
const EMPTY_PAGE = PREFIX + '/empty.html';
const HTTPS_PORT = 8908;
const HTTPS_PREFIX = 'https://localhost:' + HTTPS_PORT;
const headless = (process.env.HEADLESS || 'true').trim().toLowerCase() === 'true';
const slowMo = parseInt((process.env.SLOW_MO || '0').trim(), 10);
const executablePath = process.env.CHROME;
if (executablePath)
console.warn(`${YELLOW_COLOR}WARN: running tests with ${executablePath}${RESET_COLOR}`);
const defaultBrowserOptions = {
executablePath,
slowMo,
headless,
args: ['--no-sandbox']
};
if (process.env.DEBUG_TEST || slowMo)
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 1000 * 1000;
else
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10 * 1000;
// Make sure the `npm install` was run after the chromium roll.
{
const Downloader = require('../utils/ChromiumDownloader');
const chromiumRevision = require('../package.json').puppeteer.chromium_revision;
const revisionInfo = Downloader.revisionInfo(Downloader.currentPlatform(), chromiumRevision);
console.assert(revisionInfo.downloaded, `Chromium r${chromiumRevision} is not downloaded. Run 'npm install' and try to re-run tests.`);
}
let server;
let httpsServer;
beforeAll(SX(async function() {
const assetsPath = path.join(__dirname, 'assets');
server = await SimpleServer.create(assetsPath, PORT);
httpsServer = await SimpleServer.createHTTPS(assetsPath, HTTPS_PORT);
if (fs.existsSync(OUTPUT_DIR))
rm(OUTPUT_DIR);
}));
beforeEach(SX(async function() {
server.reset();
httpsServer.reset();
GoldenUtils.addMatchers(jasmine, GOLDEN_DIR, OUTPUT_DIR);
}));
afterAll(SX(async function() {
await Promise.all([
server.stop(),
httpsServer.stop(),
]);
}));
describe('Puppeteer', function() {
describe('Puppeteer.launch', function() {
it('should support ignoreHTTPSErrors option', SX(async function() {
const options = Object.assign({ignoreHTTPSErrors: true}, defaultBrowserOptions);
const browser = await puppeteer.launch(options);
const page = await browser.newPage();
let error = null;
const response = await page.goto(HTTPS_PREFIX + '/empty.html').catch(e => error = e);
expect(error).toBe(null);
expect(response.ok).toBe(true);
browser.close();
}));
it('should reject all promises when browser is closed', SX(async function() {
const browser = await puppeteer.launch(defaultBrowserOptions);
const page = await browser.newPage();
let error = null;
const neverResolves = page.evaluate(() => new Promise(r => {})).catch(e => error = e);
browser.close();
await neverResolves;
expect(error.message).toContain('Protocol error');
}));
it('should reject if executable path is invalid', SX(async function() {
let waitError = null;
const options = Object.assign({}, defaultBrowserOptions, {executablePath: 'random-invalid-path'});
await puppeteer.launch(options).catch(e => waitError = e);
expect(waitError.message.startsWith('Failed to launch chrome! spawn random-invalid-path ENOENT')).toBe(true);
}));
it('userDataDir option', SX(async function() {
const userDataDir = fs.mkdtempSync(path.join(__dirname, 'test-user-data-dir'));
const options = Object.assign({userDataDir}, defaultBrowserOptions);
const browser = await puppeteer.launch(options);
expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
await browser.close();
expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
rm(userDataDir);
}));
it('userDataDir argument', SX(async function() {
const userDataDir = fs.mkdtempSync(path.join(__dirname, 'test-user-data-dir'));
const options = Object.assign({}, defaultBrowserOptions);
options.args = [`--user-data-dir=${userDataDir}`].concat(options.args);
const browser = await puppeteer.launch(options);
expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
await browser.close();
expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
rm(userDataDir);
}));
it('userDataDir option should restore state', SX(async function() {
const userDataDir = fs.mkdtempSync(path.join(__dirname, 'test-user-data-dir'));
const options = Object.assign({userDataDir}, defaultBrowserOptions);
const browser = await puppeteer.launch(options);
const page = await browser.newPage();
await page.goto(EMPTY_PAGE);
await page.evaluate(() => localStorage.hey = 'hello');
await browser.close();
const browser2 = await puppeteer.launch(options);
const page2 = await browser2.newPage();
await page2.goto(EMPTY_PAGE);
expect(await page2.evaluate(() => localStorage.hey)).toBe('hello');
await browser2.close();
rm(userDataDir);
}));
it('userDataDir option should restore cookies', SX(async function() {
const userDataDir = fs.mkdtempSync(path.join(__dirname, 'test-user-data-dir'));
const options = Object.assign({userDataDir}, defaultBrowserOptions);
const browser = await puppeteer.launch(options);
const page = await browser.newPage();
await page.goto(EMPTY_PAGE);
await page.evaluate(() => document.cookie = 'doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT');
await browser.close();
const browser2 = await puppeteer.launch(options);
const page2 = await browser2.newPage();
await page2.goto(EMPTY_PAGE);
expect(await page2.evaluate(() => document.cookie)).toBe('doSomethingOnlyOnce=true');
await browser2.close();
rm(userDataDir);
}));
xit('headless should be able to read cookies written by headful', SX(async function() {
const userDataDir = fs.mkdtempSync(path.join(__dirname, 'test-user-data-dir'));
const options = Object.assign({userDataDir}, defaultBrowserOptions);
// Write a cookie in headful chrome
options.headless = false;
const headfulBrowser = await puppeteer.launch(options);
const headfulPage = await headfulBrowser.newPage();
await headfulPage.goto(EMPTY_PAGE);
await headfulPage.evaluate(() => document.cookie = 'foo=true; expires=Fri, 31 Dec 9999 23:59:59 GMT');
await headfulBrowser.close();
// Read the cookie from headless chrome
options.headless = true;
const headlessBrowser = await puppeteer.launch(options);
const headlessPage = await headlessBrowser.newPage();
await headlessPage.goto(EMPTY_PAGE);
const cookie = await headlessPage.evaluate(() => document.cookie);
await headlessBrowser.close();
rm(userDataDir);
expect(cookie).toBe('foo=true');
}));
});
describe('Puppeteer.connect', function() {
it('should be able to connect multiple times to the same browser', SX(async function() {
const originalBrowser = await puppeteer.launch(defaultBrowserOptions);
const browser = await puppeteer.connect({
browserWSEndpoint: originalBrowser.wsEndpoint()
});
const page = await browser.newPage();
expect(await page.evaluate(() => 7 * 8)).toBe(56);
browser.disconnect();
const secondPage = await originalBrowser.newPage();
expect(await secondPage.evaluate(() => 7 * 6)).toBe(42, 'original browser should still work');
await originalBrowser.close();
}));
it('should be able to reconnect to a disconnected browser', SX(async function() {
const originalBrowser = await puppeteer.launch(defaultBrowserOptions);
const browserWSEndpoint = originalBrowser.wsEndpoint();
const page = await originalBrowser.newPage();
await page.goto(PREFIX + '/frames/nested-frames.html');
originalBrowser.disconnect();
const FrameUtils = require('./frame-utils');
const browser = await puppeteer.connect({browserWSEndpoint});
const pages = await browser.pages();
const restoredPage = pages.find(page => page.url() === PREFIX + '/frames/nested-frames.html');
expect(FrameUtils.dumpFrames(restoredPage.mainFrame())).toBeGolden('reconnect-nested-frames.txt');
expect(await restoredPage.evaluate(() => 7 * 8)).toBe(56);
await browser.close();
}));
});
describe('Puppeteer.executablePath', function() {
it('should work', SX(async function() {
const executablePath = puppeteer.executablePath();
expect(fs.existsSync(executablePath)).toBe(true);
}));
});
});
describe('Page', function() {
const iPhone = require('../DeviceDescriptors')['iPhone 6'];
const iPhoneLandscape = require('../DeviceDescriptors')['iPhone 6 landscape'];
let browser;
let page;
beforeAll(SX(async function() {
browser = await puppeteer.launch(defaultBrowserOptions);
}));
afterAll(SX(async function() {
browser.close();
}));
beforeEach(SX(async function() {
page = await browser.newPage();
}));
afterEach(SX(async function() {
await page.close();
}));
describe('Browser.version', function() {
it('should return whether we are in headless', SX(async function() {
const version = await browser.version();
expect(version.length).toBeGreaterThan(0);
expect(version.startsWith('Headless')).toBe(headless);
}));
});
describe('Browser.Events.disconnected', function() {
it('should emitted when: browser gets closed, disconnected or underlying websocket gets closed', SX(async function() {
const originalBrowser = await puppeteer.launch(defaultBrowserOptions);
const browserWSEndpoint = originalBrowser.wsEndpoint();
const remoteBrowser1 = await puppeteer.connect({browserWSEndpoint});
const remoteBrowser2 = await puppeteer.connect({browserWSEndpoint});
let disconnectedOriginal = 0;
let disconnectedRemote1 = 0;
let disconnectedRemote2 = 0;
originalBrowser.on('disconnected', () => ++disconnectedOriginal);
remoteBrowser1.on('disconnected', () => ++disconnectedRemote1);
remoteBrowser2.on('disconnected', () => ++disconnectedRemote2);
await remoteBrowser2.disconnect();
expect(disconnectedOriginal).toBe(0);
expect(disconnectedRemote1).toBe(0);
expect(disconnectedRemote2).toBe(1);
await originalBrowser.close();
expect(disconnectedOriginal).toBe(1);
expect(disconnectedRemote1).toBe(1);
expect(disconnectedRemote2).toBe(1);
}));
});
describe('Page.close', function() {
it('should reject all promises when page is closed', SX(async function() {
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');
}));
});
describe('Page.Events.error', function() {
it('should throw when page crashes', SX(async function() {
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', SX(async function() {
const result = await page.evaluate(() => 7 * 3);
expect(result).toBe(21);
}));
it('should await promise', SX(async function() {
const result = await page.evaluate(() => Promise.resolve(8 * 7));
expect(result).toBe(56);
}));
it('should work from-inside an exposed function', SX(async function() {
// 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', SX(async function() {
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', SX(async function() {
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', SX(async function() {
const result = await page.evaluate(() => NaN);
expect(Object.is(result, NaN)).toBe(true);
}));
it('should return -0', SX(async function() {
const result = await page.evaluate(() => -0);
expect(Object.is(result, -0)).toBe(true);
}));
it('should return Infinity', SX(async function() {
const result = await page.evaluate(() => Infinity);
expect(Object.is(result, Infinity)).toBe(true);
}));
it('should return -Infinity', SX(async function() {
const result = await page.evaluate(() => -Infinity);
expect(Object.is(result, -Infinity)).toBe(true);
}));
it('should accept "undefined" as one of multiple parameters', SX(async function() {
const result = await page.evaluate((a, b) => Object.is(a, undefined) && Object.is(b, 'foo'), undefined, 'foo');
expect(result).toBe(true);
}));
it('should fail for window object', SX(async function() {
const result = await page.evaluate(() => window);
expect(result).toBe(undefined);
}));
it('should accept a string', SX(async function() {
const result = await page.evaluate('1 + 2');
expect(result).toBe(3);
}));
it('should accept a string with semi colons', SX(async function() {
const result = await page.evaluate('1 + 5;');
expect(result).toBe(6);
}));
it('should accept a string with comments', SX(async function() {
const result = await page.evaluate('2 + 5;\n// do some math!');
expect(result).toBe(7);
}));
it('should accept element handle as an argument', SX(async function() {
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', SX(async function() {
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', SX(async function() {
const FrameUtils = require('./frame-utils');
await FrameUtils.attachFrame(page, 'frame1', 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', SX(async function() {
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', SX(async function() {
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', SX(async function() {
await page.setOfflineMode(true);
let error = null;
await page.goto(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', SX(async function() {
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', SX(async function() {
const windowHandle = await page.evaluateHandle(() => window);
expect(windowHandle).toBeTruthy();
}));
});
describe('ExecutionContext.queryObjects', function() {
it('should work', SX(async function() {
// 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', SX(async function() {
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', SX(async function() {
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('JSHandle.getProperty', function() {
it('should work', SX(async function() {
const aHandle = await page.evaluateHandle(() => ({
one: 1,
two: 2,
three: 3
}));
const twoHandle = await aHandle.getProperty('two');
expect(await twoHandle.jsonValue()).toEqual(2);
}));
});
describe('JSHandle.jsonValue', function() {
it('should work', SX(async function() {
const aHandle = await page.evaluateHandle(() => ({foo: 'bar'}));
const json = await aHandle.jsonValue();
expect(json).toEqual({foo: 'bar'});
}));
it('should not work with dates', SX(async function() {
const dateHandle = await page.evaluateHandle(() => new Date('2017-09-26T00:00:00.000Z'));
const json = await dateHandle.jsonValue();
expect(json).toEqual({});
}));
it('should throw for circular objects', SX(async function() {
const windowHandle = await page.evaluateHandle('window');
let error = null;
await windowHandle.jsonValue().catch(e => error = e);
expect(error.message).toContain('Object reference chain is too long');
}));
});
describe('JSHandle.getProperties', function() {
it('should work', SX(async function() {
const aHandle = await page.evaluateHandle(() => ({
foo: 'bar'
}));
const properties = await aHandle.getProperties();
const foo = properties.get('foo');
expect(foo).toBeTruthy();
expect(await foo.jsonValue()).toBe('bar');
}));
it('should return even non-own properties', SX(async function() {
const aHandle = await page.evaluateHandle(() => {
class A {
constructor() {
this.a = '1';
}
}
class B extends A {
constructor() {
super();
this.b = '2';
}
}
return new B();
});
const properties = await aHandle.getProperties();
expect(await properties.get('a').jsonValue()).toBe('1');
expect(await properties.get('b').jsonValue()).toBe('2');
}));
});
describe('JSHandle.asElement', function() {
it('should work', SX(async function() {
const aHandle = await page.evaluateHandle(() => document.body);
const element = aHandle.asElement();
expect(element).toBeTruthy();
}));
it('should return null for non-elements', SX(async function() {
const aHandle = await page.evaluateHandle(() => 2);
const element = aHandle.asElement();
expect(element).toBeFalsy();
}));
it('should return ElementHandle for TextNodes', SX(async function() {
await page.setContent('<div>ee!</div>');
const aHandle = await page.evaluateHandle(() => document.querySelector('div').firstChild);
const element = aHandle.asElement();
expect(element).toBeTruthy();
expect(await page.evaluate(e => e.nodeType === HTMLElement.TEXT_NODE, element));
}));
});
describe('JSHandle.toString', function() {
it('should work for primitives', SX(async function() {
const numberHandle = await page.evaluateHandle(() => 2);
expect(numberHandle.toString()).toBe('JSHandle:2');
const stringHandle = await page.evaluateHandle(() => 'a');
expect(stringHandle.toString()).toBe('JSHandle:a');
}));
it('should work for complicated objects', SX(async function() {
const aHandle = await page.evaluateHandle(() => window);
expect(aHandle.toString()).toBe('JSHandle@object');
}));
});
describe('Frame.context', function() {
const FrameUtils = require('./frame-utils');
it('should work', SX(async function() {
await page.goto(EMPTY_PAGE);
await FrameUtils.attachFrame(page, 'frame1', EMPTY_PAGE);
expect(page.frames().length).toBe(2);
const [frame1, frame2] = page.frames();
expect(frame1.executionContext()).toBeTruthy();
expect(frame2.executionContext()).toBeTruthy();
expect(frame1.executionContext() !== frame2.executionContext()).toBeTruthy();
await Promise.all([
frame1.executionContext().evaluate(() => window.a = 1),
frame2.executionContext().evaluate(() => window.a = 2)
]);
const [a1, a2] = await Promise.all([
frame1.executionContext().evaluate(() => window.a),
frame2.executionContext().evaluate(() => window.a)
]);
expect(a1).toBe(1);
expect(a2).toBe(2);
}));
});
describe('Frame.evaluate', function() {
const FrameUtils = require('./frame-utils');
it('should have different execution contexts', SX(async function() {
await page.goto(EMPTY_PAGE);
await FrameUtils.attachFrame(page, 'frame1', EMPTY_PAGE);
expect(page.frames().length).toBe(2);
const frame1 = page.frames()[0];
const frame2 = page.frames()[1];
await frame1.evaluate(() => window.FOO = 'foo');
await frame2.evaluate(() => window.FOO = 'bar');
expect(await frame1.evaluate(() => window.FOO)).toBe('foo');
expect(await frame2.evaluate(() => window.FOO)).toBe('bar');
}));
it('should execute after cross-site navigation', SX(async function() {
await page.goto(EMPTY_PAGE);
const mainFrame = page.mainFrame();
expect(await mainFrame.evaluate(() => window.location.href)).toContain('localhost');
await page.goto(CROSS_PROCESS_PREFIX + '/empty.html');
expect(await mainFrame.evaluate(() => window.location.href)).toContain('127');
}));
});
describe('Frame.waitForFunction', function() {
it('should accept a string', SX(async function() {
const watchdog = page.waitForFunction('window.__FOO === 1');
await page.evaluate(() => window.__FOO = 1);
await watchdog;
}));
it('should poll on interval', SX(async function() {
let success = false;
const startTime = Date.now();
const polling = 100;
const watchdog = page.waitForFunction(() => window.__FOO === 'hit', {polling})
.then(() => success = true);
await page.evaluate(() => window.__FOO = 'hit');
expect(success).toBe(false);
await page.evaluate(() => document.body.appendChild(document.createElement('div')));
await watchdog;
expect(Date.now() - startTime).not.toBeLessThan(polling / 2);
}));
it('should poll on mutation', SX(async function() {
let success = false;
const watchdog = page.waitForFunction(() => window.__FOO === 'hit', {polling: 'mutation'})
.then(() => success = true);
await page.evaluate(() => window.__FOO = 'hit');
expect(success).toBe(false);
await page.evaluate(() => document.body.appendChild(document.createElement('div')));
await watchdog;
}));
it('should poll on raf', SX(async function() {
const watchdog = page.waitForFunction(() => window.__FOO === 'hit', {polling: 'raf'});
await page.evaluate(() => window.__FOO = 'hit');
await watchdog;
}));
it('should throw on bad polling value', SX(async function() {
let error = null;
try {
await page.waitForFunction(() => !!document.body, {polling: 'unknown'});
} catch (e) {
error = e;
}
expect(error).toBeTruthy();
expect(error.message).toContain('polling');
}));
it('should throw negative polling interval', SX(async function() {
let error = null;
try {
await page.waitForFunction(() => !!document.body, {polling: -10});
} catch (e) {
error = e;
}
expect(error).toBeTruthy();
expect(error.message).toContain('Cannot poll with non-positive interval');
}));
});
describe('Frame.waitForSelector', function() {
const FrameUtils = require('./frame-utils');
const addElement = tag => document.body.appendChild(document.createElement(tag));
it('should immediately resolve promise if node exists', SX(async function() {
await page.goto(EMPTY_PAGE);
const frame = page.mainFrame();
let added = false;
await frame.waitForSelector('*').then(() => added = true);
expect(added).toBe(true);
added = false;
await frame.evaluate(addElement, 'div');
await frame.waitForSelector('div').then(() => added = true);
expect(added).toBe(true);
}));
it('should resolve promise when node is added', SX(async function() {
await page.goto(EMPTY_PAGE);
const frame = page.mainFrame();
let added = false;
const watchdog = frame.waitForSelector('div').then(() => added = true);
// run nop function..
await frame.evaluate(() => 42);
// .. to be sure that waitForSelector promise is not resolved yet.
expect(added).toBe(false);
await frame.evaluate(addElement, 'br');
expect(added).toBe(false);
await frame.evaluate(addElement, 'div');
await watchdog;
expect(added).toBe(true);
}));
it('should work when node is added through innerHTML', SX(async function() {
await page.goto(EMPTY_PAGE);
const watchdog = page.waitForSelector('h3 div');
await page.evaluate(addElement, 'span');
await page.evaluate(() => document.querySelector('span').innerHTML = '<h3><div></div></h3>');
await watchdog;
}));
it('Page.waitForSelector is shortcut for main frame', SX(async function() {
await page.goto(EMPTY_PAGE);
await FrameUtils.attachFrame(page, 'frame1', EMPTY_PAGE);
const otherFrame = page.frames()[1];
let added = false;
page.waitForSelector('div').then(() => added = true);
await otherFrame.evaluate(addElement, 'div');
expect(added).toBe(false);
await page.evaluate(addElement, 'div');
expect(added).toBe(true);
}));
it('should run in specified frame', SX(async function() {
await FrameUtils.attachFrame(page, 'frame1', EMPTY_PAGE);
await FrameUtils.attachFrame(page, 'frame2', EMPTY_PAGE);
const frame1 = page.frames()[1];
const frame2 = page.frames()[2];
let added = false;
frame2.waitForSelector('div').then(() => added = true);
expect(added).toBe(false);
await frame1.evaluate(addElement, 'div');
expect(added).toBe(false);
await frame2.evaluate(addElement, 'div');
expect(added).toBe(true);
}));
it('should throw if evaluation failed', SX(async function() {
await page.evaluateOnNewDocument(function() {
document.querySelector = null;
});
await page.goto(EMPTY_PAGE);
let error = null;
await page.waitForSelector('*').catch(e => error = e);
expect(error.message).toContain('document.querySelector is not a function');
}));
it('should throw when frame is detached', SX(async function() {
await FrameUtils.attachFrame(page, 'frame1', EMPTY_PAGE);
const frame = page.frames()[1];
let waitError = null;
const waitPromise = frame.waitForSelector('.box').catch(e => waitError = e);
await FrameUtils.detachFrame(page, 'frame1');
await waitPromise;
expect(waitError).toBeTruthy();
expect(waitError.message).toContain('waitForSelector failed: frame got detached.');
}));
it('should survive cross-process navigation', SX(async function() {
let boxFound = false;
const waitForSelector = page.waitForSelector('.box').then(() => boxFound = true);
await page.goto(EMPTY_PAGE);
expect(boxFound).toBe(false);
await page.reload();
expect(boxFound).toBe(false);
await page.goto(CROSS_PROCESS_PREFIX + '/grid.html');
await waitForSelector;
expect(boxFound).toBe(true);
}));
it('should wait for visible', SX(async function() {
let divFound = false;
const waitForSelector = page.waitForSelector('div', {visible: true}).then(() => divFound = true);
await page.setContent(`<div style='display: none; visibility: hidden;'></div>`);
expect(divFound).toBe(false);
await page.evaluate(() => document.querySelector('div').style.removeProperty('display'));
expect(divFound).toBe(false);
await page.evaluate(() => document.querySelector('div').style.removeProperty('visibility'));
expect(await waitForSelector).toBe(true);
expect(divFound).toBe(true);
}));
it('hidden should wait for visibility: hidden', SX(async function() {
let divHidden = false;
await page.setContent(`<div style='display: block;'></div>`);
const waitForSelector = page.waitForSelector('div', {hidden: true}).then(() => divHidden = true);
await page.evaluate(() => document.querySelector('div').style.setProperty('visibility', 'hidden'));
expect(await waitForSelector).toBe(true);
expect(divHidden).toBe(true);
}));
it('hidden should wait for display: none', SX(async function() {
let divHidden = false;
await page.setContent(`<div style='display: block;'></div>`);
const waitForSelector = page.waitForSelector('div', {hidden: true}).then(() => divHidden = true);
await page.evaluate(() => document.querySelector('div').style.setProperty('display', 'none'));
expect(await waitForSelector).toBe(true);
expect(divHidden).toBe(true);
}));
it('hidden should wait for removal', SX(async function() {
await page.setContent(`<div></div>`);
let divRemoved = false;
const waitForSelector = page.waitForSelector('div', {hidden: true}).then(() => divRemoved = true);
expect(divRemoved).toBe(false);
await page.evaluate(() => document.querySelector('div').remove());
expect(await waitForSelector).toBe(true);
expect(divRemoved).toBe(true);
}));
it('should respect timeout', SX(async function() {
let error = null;
await page.waitForSelector('div', {timeout: 10}).catch(e => error = e);
expect(error).toBeTruthy();
expect(error.message).toContain('waiting failed: timeout');
}));
it('should respond to node attribute mutation', SX(async function() {
let divFound = false;
const waitForSelector = page.waitForSelector('.zombo').then(() => divFound = true);
await page.setContent(`<div class='notZombo'></div>`);
expect(divFound).toBe(false);
await page.evaluate(() => document.querySelector('div').className = 'zombo');
expect(await waitForSelector).toBe(true);
}));
});
describe('Page.waitFor', function() {
it('should wait for selector', SX(async function() {
let found = false;
const waitFor = page.waitFor('div').then(() => found = true);
await page.goto(EMPTY_PAGE);
expect(found).toBe(false);
await page.goto(PREFIX + '/grid.html');
await waitFor;
expect(found).toBe(true);
}));
it('should timeout', SX(async function() {
const startTime = Date.now();
const timeout = 42;
await page.waitFor(timeout);
expect(Date.now() - startTime).not.toBeLessThan(timeout / 2);
}));
it('should wait for predicate', SX(async function() {
const watchdog = page.waitFor(() => window.innerWidth < 100);
page.setViewport({width: 10, height: 10});
await watchdog;
}));
it('should throw when unknown type', SX(async function() {
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', SX(async function() {
await page.waitFor((arg1, arg2) => arg1 !== arg2, {}, 1, 2);
}));
});
describe('Page.Events.Console', function() {
it('should work', SX(async function() {
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', SX(async function() {
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', SX(async function() {
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.metrics', function() {
it('should get metrics from a page', SX(async function() {
await page.goto('about:blank');
const metrics = await page.metrics();
checkMetrics(metrics);
}));
it('metrics event fired on console.timeStamp', SX(async function() {
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', SX(async function() {
const response = await page.goto('about:blank');
expect(response).toBe(null);
}));
it('should navigate to empty page with domcontentloaded', SX(async function() {
const response = await page.goto(EMPTY_PAGE, {waitUntil: 'domcontentloaded'});
expect(response.status).toBe(200);
}));
it('should navigate to empty page with networkidle0', SX(async function() {
const response = await page.goto(EMPTY_PAGE, {waitUntil: 'networkidle0'});
expect(response.status).toBe(200);
}));
it('should navigate to empty page with networkidle2', SX(async function() {
const response = await page.goto(EMPTY_PAGE, {waitUntil: 'networkidle2'});
expect(response.status).toBe(200);
}));
it('should fail when navigating to bad url', SX(async function() {
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', SX(async function() {
// 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(HTTPS_PREFIX + '/empty.html').catch(e => error = e);
expect(error.message).toContain('net::ERR_INSECURE_RESPONSE');
}));
it('should fail when navigating to bad SSL after redirects', SX(async function() {
server.setRedirect('/redirect/1.html', '/redirect/2.html');
server.setRedirect('/redirect/2.html', '/empty.html');
let error = null;
await page.goto(HTTPS_PREFIX + '/redirect/1.html').catch(e => error = e);
expect(error.message).toContain('net::ERR_INSECURE_RESPONSE');
}));
it('should throw if networkidle is passed as an option', SX(async function() {
let error = null;
await page.goto(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', SX(async function() {
let error = null;
await page.goto('http://localhost:44123/non-existing-url').catch(e => error = e);
expect(error.message).toContain('Failed to navigate');
}));
it('should fail when exceeding maximum navigation timeout', SX(async function() {
let hasUnhandledRejection = false;
const unhandledRejectionHandler = () => hasUnhandledRejection = true;
process.on('unhandledRejection', unhandledRejectionHandler);
// Hang for request to the empty.html
server.setRoute('/empty.html', (req, res) => { });
let error = null;
await page.goto(PREFIX + '/empty.html', {timeout: 1}).catch(e => error = e);
expect(hasUnhandledRejection).toBe(false);
expect(error.message).toContain('Navigation Timeout Exceeded: 1ms');
process.removeListener('unhandledRejection', unhandledRejectionHandler);
}));
it('should disable timeout when its set to 0', SX(async function() {
let error = null;
await page.goto(PREFIX + '/grid.html', {timeout: 0}).catch(e => error = e);
expect(error).toBe(null);
}));
it('should work when navigating to valid url', SX(async function() {
const response = await page.goto(EMPTY_PAGE);
expect(response.ok).toBe(true);
}));
it('should work when navigating to data url', SX(async function() {
const response = await page.goto('data:text/html,hello');
expect(response.ok).toBe(true);