forked from puppeteer/puppeteer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.js
3962 lines (3757 loc) · 167 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 os = require('os');
const rm = require('rimraf').sync;
const path = require('path');
const {helper} = require('../lib/helper');
if (process.env.COVERAGE)
helper.recordPublicAPICoverage();
const mkdtempAsync = helper.promisify(fs.mkdtemp);
const readFileAsync = helper.promisify(fs.readFile);
const TMP_FOLDER = path.join(os.tmpdir(), 'pptr_tmp_folder-');
const PROJECT_ROOT = fs.existsSync(path.join(__dirname, '..', 'package.json')) ? path.join(__dirname, '..') : path.join(__dirname, '..', '..');
const puppeteer = require(PROJECT_ROOT);
const DeviceDescriptors = require(path.join(PROJECT_ROOT, 'DeviceDescriptors'));
const iPhone = DeviceDescriptors['iPhone 6'];
const iPhoneLandscape = DeviceDescriptors['iPhone 6 landscape'];
const SimpleServer = require('./server/SimpleServer');
const GoldenUtils = require('./golden-utils');
const FrameUtils = require('./frame-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 headless = (process.env.HEADLESS || 'true').trim().toLowerCase() === 'true';
const slowMo = parseInt((process.env.SLOW_MO || '0').trim(), 10);
const executablePath = process.env.CHROME;
console.log('Testing on Node', process.version);
if (executablePath)
console.warn(`${YELLOW_COLOR}WARN: running tests with ${executablePath}${RESET_COLOR}`);
// Make sure the `npm install` was run after the chromium roll.
console.assert(fs.existsSync(puppeteer.executablePath()), `Chromium is not Downloaded. Run 'npm install' and try to re-run tests`);
const defaultBrowserOptions = {
executablePath,
slowMo,
headless,
args: ['--no-sandbox', '--disable-dev-shm-usage']
};
const timeout = slowMo ? 0 : 10 * 1000;
let parallel = 1;
if (process.env.PPTR_PARALLEL_TESTS)
parallel = parseInt(process.env.PPTR_PARALLEL_TESTS.trim(), 10);
const parallelArgIndex = process.argv.indexOf('-j');
if (parallelArgIndex !== -1)
parallel = parseInt(process.argv[parallelArgIndex + 1], 10);
require('events').defaultMaxListeners *= parallel;
const {TestRunner, Reporter, Matchers} = require('../utils/testrunner/');
const runner = new TestRunner({timeout, parallel});
new Reporter(runner);
const {describe, xdescribe, fdescribe} = runner;
const {it, fit, xit} = runner;
const {beforeAll, beforeEach, afterAll, afterEach} = runner;
const {expect} = new Matchers({
toBeGolden: GoldenUtils.compare.bind(null, GOLDEN_DIR, OUTPUT_DIR)
});
if (fs.existsSync(OUTPUT_DIR))
rm(OUTPUT_DIR);
beforeAll(async state => {
const assetsPath = path.join(__dirname, 'assets');
const cachedPath = path.join(__dirname, 'assets', 'cached');
const port = 8907 + state.parallelIndex * 2;
state.server = await SimpleServer.create(assetsPath, port);
state.server.enableHTTPCache(cachedPath);
state.server.PREFIX = `http://localhost:${port}`;
state.server.CROSS_PROCESS_PREFIX = `http://127.0.0.1:${port}`;
state.server.EMPTY_PAGE = `http://localhost:${port}/empty.html`;
const httpsPort = port + 1;
state.httpsServer = await SimpleServer.createHTTPS(assetsPath, httpsPort);
state.httpsServer.enableHTTPCache(cachedPath);
state.httpsServer.PREFIX = `https://localhost:${httpsPort}`;
state.httpsServer.CROSS_PROCESS_PREFIX = `https://127.0.0.1:${httpsPort}`;
state.httpsServer.EMPTY_PAGE = `https://localhost:${httpsPort}/empty.html`;
});
beforeEach(async({server, httpsServer}) => {
server.reset();
httpsServer.reset();
});
afterAll(async({server, httpsServer}) => {
await Promise.all([
server.stop(),
httpsServer.stop(),
]);
});
describe('Puppeteer', function() {
describe('BrowserFetcher', function() {
it('should download and extract linux binary', async({server}) => {
const downloadsFolder = await mkdtempAsync(TMP_FOLDER);
const browserFetcher = puppeteer.createBrowserFetcher({
platform: 'linux',
path: downloadsFolder,
host: server.PREFIX
});
let revisionInfo = browserFetcher.revisionInfo('123456');
server.setRoute(revisionInfo.url.substring(server.PREFIX.length), (req, res) => {
server.serveFile(req, res, '/chromium-linux.zip');
});
expect(revisionInfo.local).toBe(false);
expect(browserFetcher.platform()).toBe('linux');
expect(await browserFetcher.canDownload('100000')).toBe(false);
expect(await browserFetcher.canDownload('123456')).toBe(true);
revisionInfo = await browserFetcher.download('123456');
expect(revisionInfo.local).toBe(true);
expect(await readFileAsync(revisionInfo.executablePath, 'utf8')).toBe('LINUX BINARY\n');
expect(await browserFetcher.localRevisions()).toEqual(['123456']);
await browserFetcher.remove('123456');
expect(await browserFetcher.localRevisions()).toEqual([]);
rm(downloadsFolder);
});
});
describe('Puppeteer.launch', function() {
it('should support ignoreHTTPSErrors option', async({httpsServer}) => {
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(httpsServer.EMPTY_PAGE).catch(e => error = e);
expect(error).toBe(null);
expect(response.ok()).toBe(true);
browser.close();
});
it('should reject all promises when browser is closed', async() => {
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', async({server}) => {
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', async({server}) => {
const userDataDir = await mkdtempAsync(TMP_FOLDER);
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', async({server}) => {
const userDataDir = await mkdtempAsync(TMP_FOLDER);
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', async({server}) => {
const userDataDir = await mkdtempAsync(TMP_FOLDER);
const options = Object.assign({userDataDir}, defaultBrowserOptions);
const browser = await puppeteer.launch(options);
const page = await browser.newPage();
await page.goto(server.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(server.EMPTY_PAGE);
expect(await page2.evaluate(() => localStorage.hey)).toBe('hello');
await browser2.close();
rm(userDataDir);
});
// @see https://github.com/GoogleChrome/puppeteer/issues/1537
xit('userDataDir option should restore cookies', async({server}) => {
const userDataDir = await mkdtempAsync(TMP_FOLDER);
const options = Object.assign({userDataDir}, defaultBrowserOptions);
const browser = await puppeteer.launch(options);
const page = await browser.newPage();
await page.goto(server.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(server.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', async({server}) => {
const userDataDir = await mkdtempAsync(TMP_FOLDER);
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(server.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(server.EMPTY_PAGE);
const cookie = await headlessPage.evaluate(() => document.cookie);
await headlessBrowser.close();
rm(userDataDir);
expect(cookie).toBe('foo=true');
});
it('should return the default chrome arguments', async() => {
const args = puppeteer.defaultArgs();
expect(args).toContain('--no-first-run');
});
});
describe('Puppeteer.connect', function() {
it('should be able to connect multiple times to the same browser', async({server}) => {
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', async({server}) => {
const originalBrowser = await puppeteer.launch(defaultBrowserOptions);
const browserWSEndpoint = originalBrowser.wsEndpoint();
const page = await originalBrowser.newPage();
await page.goto(server.PREFIX + '/frames/nested-frames.html');
originalBrowser.disconnect();
const browser = await puppeteer.connect({browserWSEndpoint});
const pages = await browser.pages();
const restoredPage = pages.find(page => page.url() === server.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', async({server}) => {
const executablePath = puppeteer.executablePath();
expect(fs.existsSync(executablePath)).toBe(true);
});
});
});
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;
});
describe('Browser.version', function() {
it('should return whether we are in headless', async({browser}) => {
const version = await browser.version();
expect(version.length).toBeGreaterThan(0);
expect(version.startsWith('Headless')).toBe(headless);
});
});
describe('Browser.userAgent', function() {
it('should include WebKit', async({browser}) => {
const userAgent = await browser.userAgent();
expect(userAgent.length).toBeGreaterThan(0);
expect(userAgent).toContain('WebKit');
});
});
describe('Browser.process', function() {
it('should return child_process instance', async function({browser}) {
const process = await browser.process();
expect(process.pid).toBeGreaterThan(0);
const browserWSEndpoint = browser.wsEndpoint();
const remoteBrowser = await puppeteer.connect({browserWSEndpoint});
expect(remoteBrowser.process()).toBe(null);
await remoteBrowser.disconnect();
});
});
describe('Browser.Events.disconnected', function() {
it('should emitted when: browser gets closed, disconnected or underlying websocket gets closed', async() => {
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', 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');
});
});
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 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 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 FrameUtils.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('JSHandle.getProperty', function() {
it('should work', async({page, server}) => {
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', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => ({foo: 'bar'}));
const json = await aHandle.jsonValue();
expect(json).toEqual({foo: 'bar'});
});
it('should not work with dates', async({page, server}) => {
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', async({page, server}) => {
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', async({page, server}) => {
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', async({page, server}) => {
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', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => document.body);
const element = aHandle.asElement();
expect(element).toBeTruthy();
});
it('should return null for non-elements', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => 2);
const element = aHandle.asElement();
expect(element).toBeFalsy();
});
it('should return ElementHandle for TextNodes', async({page, server}) => {
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', async({page, server}) => {
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', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => window);
expect(aHandle.toString()).toBe('JSHandle@object');
});
});
describe('Frame.context', function() {
it('should work', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await FrameUtils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
expect(page.frames().length).toBe(2);
const [frame1, frame2] = page.frames();
const context1 = await frame1.executionContext();
const context2 = await frame2.executionContext();
expect(context1).toBeTruthy();
expect(context2).toBeTruthy();
expect(context1 !== context2).toBeTruthy();
await Promise.all([
context1.evaluate(() => window.a = 1),
context2.evaluate(() => window.a = 2)
]);
const [a1, a2] = await Promise.all([
context1.evaluate(() => window.a),
context2.evaluate(() => window.a)
]);
expect(a1).toBe(1);
expect(a2).toBe(2);
});
});
describe('Frame.evaluateHandle', function() {
it('should work', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const mainFrame = page.mainFrame();
const windowHandle = await mainFrame.evaluateHandle(() => window);
expect(windowHandle).toBeTruthy();
});
});
describe('Frame.evaluate', function() {
it('should have different execution contexts', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await FrameUtils.attachFrame(page, 'frame1', server.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', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const mainFrame = page.mainFrame();
expect(await mainFrame.evaluate(() => window.location.href)).toContain('localhost');
await page.goto(server.CROSS_PROCESS_PREFIX + '/empty.html');
expect(await mainFrame.evaluate(() => window.location.href)).toContain('127');
});
});
describe('Frame.waitForFunction', function() {
it('should accept a string', async({page, server}) => {
const watchdog = page.waitForFunction('window.__FOO === 1');
await page.evaluate(() => window.__FOO = 1);
await watchdog;
});
it('should poll on interval', async({page, server}) => {
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', async({page, server}) => {
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', async({page, server}) => {
const watchdog = page.waitForFunction(() => window.__FOO === 'hit', {polling: 'raf'});
await page.evaluate(() => window.__FOO = 'hit');
await watchdog;
});
it('should throw on bad polling value', async({page, server}) => {
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', async({page, server}) => {
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');
});
it('should return the success value as a JSHandle', async({page}) => {
expect(await (await page.waitForFunction(() => 5)).jsonValue()).toBe(5);
});
it('should return the window as a success value', async({ page }) => {
expect(await page.waitForFunction(() => window)).toBeTruthy();
});
it('should accept ElementHandle arguments', async({page}) => {
await page.setContent('<div></div>');
const div = await page.$('div');
let resolved = false;
const waitForFunction = page.waitForFunction(element => !element.parentElement, {}, div).then(() => resolved = true);
expect(resolved).toBe(false);
await page.evaluate(element => element.remove(), div);
await waitForFunction;
});
});
describe('Frame.waitForSelector', function() {
const addElement = tag => document.body.appendChild(document.createElement(tag));
it('should immediately resolve promise if node exists', async({page, server}) => {
await page.goto(server.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', async({page, server}) => {
await page.goto(server.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', async({page, server}) => {
await page.goto(server.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', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await FrameUtils.attachFrame(page, 'frame1', server.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', async({page, server}) => {
await FrameUtils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await FrameUtils.attachFrame(page, 'frame2', server.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', async({page, server}) => {
await page.evaluateOnNewDocument(function() {
document.querySelector = null;
});
await page.goto(server.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', async({page, server}) => {
await FrameUtils.attachFrame(page, 'frame1', server.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('waitForFunction failed: frame got detached.');
});
it('should survive cross-process navigation', async({page, server}) => {
let boxFound = false;
const waitForSelector = page.waitForSelector('.box').then(() => boxFound = true);
await page.goto(server.EMPTY_PAGE);
expect(boxFound).toBe(false);
await page.reload();
expect(boxFound).toBe(false);
await page.goto(server.CROSS_PROCESS_PREFIX + '/grid.html');
await waitForSelector;
expect(boxFound).toBe(true);
});
it('should wait for visible', async({page, server}) => {
let divFound = false;
const waitForSelector = page.waitForSelector('div', {visible: true}).then(() => divFound = true);
await page.setContent(`<div style='display: none; visibility: hidden;'>1</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('should wait for visible recursively', async({page, server}) => {
let divVisible = false;
const waitForSelector = page.waitForSelector('div#inner', {visible: true}).then(() => divVisible = true);
await page.setContent(`<div style='display: none; visibility: hidden;'><div id="inner">hi</div></div>`);
expect(divVisible).toBe(false);
await page.evaluate(() => document.querySelector('div').style.removeProperty('display'));
expect(divVisible).toBe(false);
await page.evaluate(() => document.querySelector('div').style.removeProperty('visibility'));
expect(await waitForSelector).toBe(true);
expect(divVisible).toBe(true);
});
it('hidden should wait for visibility: hidden', async({page, server}) => {
let divHidden = false;
await page.setContent(`<div style='display: block;'></div>`);
const waitForSelector = page.waitForSelector('div', {hidden: true}).then(() => divHidden = true);
await page.waitForSelector('div'); // do a round trip
expect(divHidden).toBe(false);
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', async({page, server}) => {
let divHidden = false;
await page.setContent(`<div style='display: block;'></div>`);
const waitForSelector = page.waitForSelector('div', {hidden: true}).then(() => divHidden = true);
await page.waitForSelector('div'); // do a round trip
expect(divHidden).toBe(false);
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', async({page, server}) => {
await page.setContent(`<div></div>`);
let divRemoved = false;
const waitForSelector = page.waitForSelector('div', {hidden: true}).then(() => divRemoved = true);
await page.waitForSelector('div'); // do a round trip
expect(divRemoved).toBe(false);
await page.evaluate(() => document.querySelector('div').remove());
expect(await waitForSelector).toBe(true);
expect(divRemoved).toBe(true);
});
it('should respect timeout', async({page, server}) => {
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', async({page, server}) => {
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);
});
it('should return the element handle', async({page, server}) => {
const waitForSelector = page.waitForSelector('.zombo');
await page.setContent(`<div class='zombo'>anything</div>`);
expect(await page.evaluate(x => x.textContent, await waitForSelector)).toBe('anything');
});
});
describe('Frame.waitForXPath', function() {
const addElement = tag => document.body.appendChild(document.createElement(tag));
it('should support some fancy xpath', async({page, server}) => {
await page.setContent(`<p>red herring</p><p>hello world </p>`);
const waitForXPath = page.waitForXPath('//p[normalize-space(.)="hello world"]');
expect(await page.evaluate(x => x.textContent, await waitForXPath)).toBe('hello world ');
});
it('should run in specified frame', async({page, server}) => {
await FrameUtils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await FrameUtils.attachFrame(page, 'frame2', server.EMPTY_PAGE);
const frame1 = page.frames()[1];
const frame2 = page.frames()[2];
let added = false;
frame2.waitForXPath('//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', async({page, server}) => {
await page.evaluateOnNewDocument(function() {
document.evaluate = null;
});
await page.goto(server.EMPTY_PAGE);
let error = null;
await page.waitForXPath('*').catch(e => error = e);
expect(error.message).toContain('document.evaluate is not a function');
});
it('should throw when frame is detached', async({page, server}) => {
await FrameUtils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = page.frames()[1];
let waitError = null;
const waitPromise = frame.waitForXPath('//*[@class="box"]').catch(e => waitError = e);
await FrameUtils.detachFrame(page, 'frame1');
await waitPromise;
expect(waitError).toBeTruthy();
expect(waitError.message).toContain('waitForFunction failed: frame got detached.');
});
it('hidden should wait for display: none', async({page, server}) => {
let divHidden = false;
await page.setContent(`<div style='display: block;'></div>`);
const waitForXPath = page.waitForXPath('//div', {hidden: true}).then(() => divHidden = true);
await page.waitForXPath('//div'); // do a round trip
expect(divHidden).toBe(false);
await page.evaluate(() => document.querySelector('div').style.setProperty('display', 'none'));
expect(await waitForXPath).toBe(true);
expect(divHidden).toBe(true);
});
it('should return the element handle', async({page, server}) => {
const waitForXPath = page.waitForXPath('//*[@class="zombo"]');
await page.setContent(`<div class='zombo'>anything</div>`);
expect(await page.evaluate(x => x.textContent, await waitForXPath)).toBe('anything');
});
it('should allow you to select a text node', async({page, server}) => {
await page.setContent(`<div>some text</div>`);
const text = await page.waitForXPath('//div/text()');
expect(await (await text.getProperty('nodeType')).jsonValue()).toBe(3 /* Node.TEXT_NODE */);
});
it('should allow you to select an element with single slash', async({page, server}) => {
await page.setContent(`<div>some text</div>`);
const waitForXPath = page.waitForXPath('/html/body/div');
expect(await page.evaluate(x => x.textContent, await waitForXPath)).toBe('some text');
});
});
describe('Page.waitFor', function() {
it('should wait for selector', async({page, server}) => {
let found = false;