From ff8529696d3616d1a857ddc96d053ddd227eb053 Mon Sep 17 00:00:00 2001 From: Nikolay Vitkov <34244704+Lightning00Blade@users.noreply.github.com> Date: Wed, 21 Jun 2023 21:41:09 +0200 Subject: [PATCH] ci: remove before hooks (#10431) --- test/README.md | 4 +- test/TestExpectations.json | 12 +- test/src/CDPSession.spec.ts | 29 +- test/src/TargetManager.spec.ts | 4 +- test/src/accessibility.spec.ts | 49 ++- test/src/ariaqueryhandler.spec.ts | 97 +++--- test/src/browser.spec.ts | 16 +- test/src/browsercontext.spec.ts | 43 +-- test/src/chromiumonly.spec.ts | 51 +-- test/src/click.spec.ts | 64 ++-- test/src/cookies.spec.ts | 115 +++---- test/src/coverage.spec.ts | 66 ++-- test/src/defaultbrowsercontext.spec.ts | 21 +- test/src/dialog.spec.ts | 15 +- test/src/drag-and-drop.spec.ts | 22 +- test/src/elementhandle.spec.ts | 77 ++--- test/src/emulation.spec.ts | 45 ++- test/src/evaluation.spec.ts | 107 +++--- test/src/fixtures.spec.ts | 8 +- test/src/frame.spec.ts | 47 ++- test/src/headful.spec.ts | 23 +- test/src/idle_override.spec.ts | 36 +- test/src/ignorehttpserrors.spec.ts | 14 +- test/src/injected.spec.ts | 13 +- test/src/input.spec.ts | 49 ++- test/src/jshandle.spec.ts | 51 ++- test/src/keyboard.spec.ts | 47 ++- test/src/launcher.spec.ts | 202 +++++------ test/src/locator.spec.ts | 53 ++- test/src/mocha-utils.ts | 319 ++++++++++-------- test/src/mouse.spec.ts | 32 +- test/src/navigation.spec.ts | 111 +++--- test/src/network.spec.ts | 102 +++--- test/src/oopif.spec.ts | 36 +- test/src/page.spec.ts | 290 ++++++++-------- test/src/proxy.spec.ts | 36 +- test/src/queryhandler.spec.ts | 106 +++--- test/src/queryselector.spec.ts | 74 ++-- .../requestinterception-experimental.spec.ts | 98 +++--- test/src/requestinterception.spec.ts | 98 +++--- test/src/screenshot.spec.ts | 60 ++-- test/src/stacktrace.spec.ts | 37 +- test/src/target.spec.ts | 39 +-- test/src/touchscreen.spec.ts | 15 +- test/src/tracing.spec.ts | 5 +- test/src/waittask.spec.ts | 116 +++---- test/src/worker.spec.ts | 20 +- 47 files changed, 1364 insertions(+), 1610 deletions(-) diff --git a/test/README.md b/test/README.md index cc4fe3b5ae9..1513a1b2091 100644 --- a/test/README.md +++ b/test/README.md @@ -62,7 +62,7 @@ npm run build --workspace=@puppeteer-test/test && npm test ```ts ... it.only('should work', async function() { - const {server, page} = getTestState(); + const {server, page} = await getTestState(); const response = await page.goto(server.EMPTY_PAGE); expect(response.ok).toBe(true); }); @@ -73,7 +73,7 @@ npm run build --workspace=@puppeteer-test/test && npm test ```ts ... it.skip('should work', async function({server, page}) { - const {server, page} = getTestState(); + const {server, page} = await getTestState(); const response = await page.goto(server.EMPTY_PAGE); expect(response.ok).toBe(true); }); diff --git a/test/TestExpectations.json b/test/TestExpectations.json index 7df203c24ac..5a33a559031 100644 --- a/test/TestExpectations.json +++ b/test/TestExpectations.json @@ -1547,12 +1547,6 @@ "parameters": ["cdp", "firefox"], "expectations": ["FAIL"] }, - { - "testIdPattern": "[browsercontext.spec] BrowserContext should isolate localStorage and cookies", - "platforms": ["darwin", "linux", "win32"], - "parameters": ["cdp", "firefox"], - "expectations": ["FAIL"] - }, { "testIdPattern": "[browsercontext.spec] BrowserContext should provide a context id", "platforms": ["darwin", "linux", "win32"], @@ -1781,6 +1775,12 @@ "parameters": ["chrome", "webDriverBiDi"], "expectations": ["FAIL", "PASS"] }, + { + "testIdPattern": "[defaultbrowsercontext.spec] DefaultBrowserContext page.cookies() should work", + "platforms": ["darwin", "linux", "win32"], + "parameters": ["cdp", "firefox"], + "expectations": ["FAIL"] + }, { "testIdPattern": "[defaultbrowsercontext.spec] DefaultBrowserContext page.deleteCookie() should work", "platforms": ["darwin", "linux", "win32"], diff --git a/test/src/CDPSession.spec.ts b/test/src/CDPSession.spec.ts index b059e727237..c76d4e0009a 100644 --- a/test/src/CDPSession.spec.ts +++ b/test/src/CDPSession.spec.ts @@ -17,19 +17,12 @@ import expect from 'expect'; import {isErrorLike} from 'puppeteer-core/internal/util/ErrorLike.js'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; import {waitEvent} from './utils.js'; describe('Target.createCDPSession', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const client = await page.target().createCDPSession(); @@ -44,20 +37,22 @@ describe('Target.createCDPSession', function () { }); it('should not report created targets for custom CDP sessions', async () => { - const {browser} = getTestState(); + const {browser} = await getTestState(); let called = 0; - browser.browserContexts()[0]!.on('targetcreated', async target => { + const handler = async (target: any) => { called++; if (called > 1) { throw new Error('Too many targets created'); } await target.createCDPSession(); - }); + }; + browser.browserContexts()[0]!.on('targetcreated', handler); await browser.newPage(); + browser.browserContexts()[0]!.off('targetcreated', handler); }); it('should send events', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const client = await page.target().createCDPSession(); await client.send('Network.enable'); @@ -72,7 +67,7 @@ describe('Target.createCDPSession', function () { expect(events).toHaveLength(1); }); it('should enable and disable domains independently', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const client = await page.target().createCDPSession(); await client.send('Runtime.enable'); @@ -89,7 +84,7 @@ describe('Target.createCDPSession', function () { expect(event.url).toBe('foo.js'); }); it('should be able to detach session', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const client = await page.target().createCDPSession(); await client.send('Runtime.enable'); @@ -113,7 +108,7 @@ describe('Target.createCDPSession', function () { expect(error.message).toContain('Session closed.'); }); it('should throw nice errors', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const client = await page.target().createCDPSession(); const error = await theSourceOfTheProblems().catch(error => { @@ -131,7 +126,7 @@ describe('Target.createCDPSession', function () { }); it('should expose the underlying connection', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const client = await page.target().createCDPSession(); expect(client.connection()).toBeTruthy(); diff --git a/test/src/TargetManager.spec.ts b/test/src/TargetManager.spec.ts index 26c25467c76..2d3e97d948f 100644 --- a/test/src/TargetManager.spec.ts +++ b/test/src/TargetManager.spec.ts @@ -27,7 +27,9 @@ describe('TargetManager', () => { }; beforeEach(async () => { - const {defaultBrowserOptions} = getTestState(); + const {defaultBrowserOptions} = await getTestState({ + skipLaunch: true, + }); testState = (await launch( Object.assign({}, defaultBrowserOptions, { args: (defaultBrowserOptions.args || []).concat([ diff --git a/test/src/accessibility.spec.ts b/test/src/accessibility.spec.ts index 3ab518e7039..d9f7c661c69 100644 --- a/test/src/accessibility.spec.ts +++ b/test/src/accessibility.spec.ts @@ -19,18 +19,11 @@ import assert from 'assert'; import expect from 'expect'; import {SerializedAXNode} from 'puppeteer-core/internal/common/Accessibility.js'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; describe('Accessibility', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - it('should work', async () => { - const {page, isFirefox} = getTestState(); + const {page, isFirefox} = await getTestState(); await page.setContent(` @@ -122,7 +115,7 @@ describe('Accessibility', function () { expect(await page.accessibility.snapshot()).toEqual(golden); }); it('should report uninteresting nodes', async () => { - const {page, isFirefox} = getTestState(); + const {page, isFirefox} = await getTestState(); await page.setContent(``); await page.focus('textarea'); @@ -167,7 +160,7 @@ describe('Accessibility', function () { }); it('get snapshots while the tree is re-calculated', async () => { // see https://github.com/puppeteer/puppeteer/issues/9404 - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( ` @@ -211,7 +204,7 @@ describe('Accessibility', function () { await page.waitForSelector('aria/Hide'); }); it('roledescription', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
Hi
' @@ -224,7 +217,7 @@ describe('Accessibility', function () { expect(snapshot.children[0]!.roledescription).toBeUndefined(); }); it('orientation', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '11' @@ -236,7 +229,7 @@ describe('Accessibility', function () { expect(snapshot.children[0]!.orientation).toEqual('vertical'); }); it('autocomplete', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(''); const snapshot = await page.accessibility.snapshot(); @@ -246,7 +239,7 @@ describe('Accessibility', function () { expect(snapshot.children[0]!.autocomplete).toEqual('list'); }); it('multiselectable', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
hey
' @@ -258,7 +251,7 @@ describe('Accessibility', function () { expect(snapshot.children[0]!.multiselectable).toEqual(true); }); it('keyshortcuts', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
hey
' @@ -271,7 +264,7 @@ describe('Accessibility', function () { }); describe('filtering children of leaf nodes', function () { it('should not report text nodes inside controls', async () => { - const {page, isFirefox} = getTestState(); + const {page, isFirefox} = await getTestState(); await page.setContent(`
@@ -312,7 +305,7 @@ describe('Accessibility', function () { expect(await page.accessibility.snapshot()).toEqual(golden); }); it('rich text editable fields should have children', async () => { - const {page, isFirefox} = getTestState(); + const {page, isFirefox} = await getTestState(); await page.setContent(`
@@ -354,7 +347,7 @@ describe('Accessibility', function () { expect(snapshot.children[0]).toEqual(golden); }); it('rich text editable fields with role should have children', async () => { - const {page, isFirefox} = getTestState(); + const {page, isFirefox} = await getTestState(); await page.setContent(`
@@ -394,7 +387,7 @@ describe('Accessibility', function () { // Firefox does not support contenteditable="plaintext-only". describe('plaintext contenteditable', function () { it('plain text field with role should not have children', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(`
Edit this image:my fake image
`); @@ -410,7 +403,7 @@ describe('Accessibility', function () { }); }); it('non editable textbox with role and tabIndex and label should not have children', async () => { - const {page, isFirefox} = getTestState(); + const {page, isFirefox} = await getTestState(); await page.setContent(`
@@ -434,7 +427,7 @@ describe('Accessibility', function () { expect(snapshot.children[0]).toEqual(golden); }); it('checkbox with and tabIndex and label should not have children', async () => { - const {page, isFirefox} = getTestState(); + const {page, isFirefox} = await getTestState(); await page.setContent(`
@@ -458,7 +451,7 @@ describe('Accessibility', function () { expect(snapshot.children[0]).toEqual(golden); }); it('checkbox without label should not have children', async () => { - const {page, isFirefox} = getTestState(); + const {page, isFirefox} = await getTestState(); await page.setContent(`
@@ -484,7 +477,7 @@ describe('Accessibility', function () { describe('root option', function () { it('should work a button', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(``); @@ -495,7 +488,7 @@ describe('Accessibility', function () { }); }); it('should work an input', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(``); @@ -507,7 +500,7 @@ describe('Accessibility', function () { }); }); it('should work a menu', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(`
@@ -530,7 +523,7 @@ describe('Accessibility', function () { }); }); it('should return null when the element is no longer in DOM', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(``); const button = (await page.$('button'))!; @@ -540,7 +533,7 @@ describe('Accessibility', function () { expect(await page.accessibility.snapshot({root: button})).toEqual(null); }); it('should support the interestingOnly option', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(`
`); const div = (await page.$('div'))!; diff --git a/test/src/ariaqueryhandler.spec.ts b/test/src/ariaqueryhandler.spec.ts index 8197e0bec6e..46f65703f17 100644 --- a/test/src/ariaqueryhandler.spec.ts +++ b/test/src/ariaqueryhandler.spec.ts @@ -20,26 +20,16 @@ import expect from 'expect'; import {TimeoutError} from 'puppeteer'; import type {ElementHandle} from 'puppeteer-core/internal/api/ElementHandle.js'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; import {attachFrame, detachFrame} from './utils.js'; describe('AriaQueryHandler', () => { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - describe('parseAriaSelector', () => { - beforeEach(async () => { - const {page} = getTestState(); + it('should find button', async () => { + const {page} = await getTestState(); await page.setContent( '' ); - }); - it('should find button', async () => { - const {page} = getTestState(); const expectFound = async (button: ElementHandle | null) => { assert(button); const id = await button.evaluate((button: Element) => { @@ -95,7 +85,7 @@ describe('AriaQueryHandler', () => { describe('queryOne', () => { it('should find button by role', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
' ); @@ -109,7 +99,7 @@ describe('AriaQueryHandler', () => { }); it('should find button by name and role', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
' ); @@ -123,7 +113,7 @@ describe('AriaQueryHandler', () => { }); it('should find first matching element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( ` @@ -140,7 +130,7 @@ describe('AriaQueryHandler', () => { }); it('should find by name', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( ` @@ -157,7 +147,7 @@ describe('AriaQueryHandler', () => { }); it('should find by name', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( ` @@ -176,7 +166,7 @@ describe('AriaQueryHandler', () => { describe('queryAll', () => { it('should find menu by name', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( ` @@ -200,7 +190,7 @@ describe('AriaQueryHandler', () => { it('$$eval should handle many elements', async function () { this.timeout(25_000); - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(''); await page.evaluate( ` @@ -226,14 +216,14 @@ describe('AriaQueryHandler', () => { }; it('should immediately resolve promise if node exists', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.evaluate(addElement, 'button'); await page.waitForSelector('aria/[role="button"]'); }); it('should work for ElementHandle.waitForSelector', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.evaluate(() => { return (document.body.innerHTML = `
`); @@ -243,7 +233,7 @@ describe('AriaQueryHandler', () => { }); it('should persist query handler bindings across reloads', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.evaluate(addElement, 'button'); await page.waitForSelector('aria/[role="button"]'); @@ -253,7 +243,7 @@ describe('AriaQueryHandler', () => { }); it('should persist query handler bindings across navigations', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Reset page but make sure that execution context ids start with 1. await page.goto('data:text/html,'); @@ -269,7 +259,7 @@ describe('AriaQueryHandler', () => { }); it('should work independently of `exposeFunction`', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.exposeFunction('ariaQuerySelector', (a: number, b: number) => { return a + b; @@ -281,7 +271,7 @@ describe('AriaQueryHandler', () => { }); it('should work with removed MutationObserver', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.evaluate(() => { // @ts-expect-error This is the point of the test. @@ -300,7 +290,7 @@ describe('AriaQueryHandler', () => { }); it('should resolve promise when node is added', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const frame = page.mainFrame(); @@ -315,7 +305,7 @@ describe('AriaQueryHandler', () => { }); it('should work when node is added through innerHTML', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const watchdog = page.waitForSelector('aria/name'); @@ -328,7 +318,7 @@ describe('AriaQueryHandler', () => { }); it('Page.waitForSelector is shortcut for main frame', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await attachFrame(page, 'frame1', server.EMPTY_PAGE); @@ -341,7 +331,7 @@ describe('AriaQueryHandler', () => { }); it('should run in specified frame', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await attachFrame(page, 'frame1', server.EMPTY_PAGE); await attachFrame(page, 'frame2', server.EMPTY_PAGE); @@ -357,7 +347,7 @@ describe('AriaQueryHandler', () => { }); it('should throw when frame is detached', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await attachFrame(page, 'frame1', server.EMPTY_PAGE); const frame = page.frames()[1]; @@ -376,7 +366,7 @@ describe('AriaQueryHandler', () => { }); it('should survive cross-process navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let imgFound = false; const waitForSelector = page @@ -394,7 +384,7 @@ describe('AriaQueryHandler', () => { }); it('should wait for visible', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let divFound = false; const waitForSelector = page @@ -420,7 +410,7 @@ describe('AriaQueryHandler', () => { }); it('should wait for visible recursively', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let divVisible = false; const waitForSelector = page @@ -449,7 +439,7 @@ describe('AriaQueryHandler', () => { }); it('hidden should wait for visibility: hidden', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let divHidden = false; await page.setContent( @@ -475,7 +465,7 @@ describe('AriaQueryHandler', () => { }); it('hidden should wait for display: none', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let divHidden = false; await page.setContent( @@ -501,7 +491,7 @@ describe('AriaQueryHandler', () => { }); it('hidden should wait for removal', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(`
text
`); let divRemoved = false; @@ -523,7 +513,7 @@ describe('AriaQueryHandler', () => { }); it('should return null if waiting to hide non-existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const handle = await page.waitForSelector('aria/non-existing', { hidden: true, @@ -532,7 +522,7 @@ describe('AriaQueryHandler', () => { }); it('should respect timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const error = await page .waitForSelector('aria/[role="button"]', { @@ -548,7 +538,7 @@ describe('AriaQueryHandler', () => { }); it('should have an error message specifically for awaiting an element to be hidden', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(`
text
`); const promise = page.waitForSelector('aria/[role="main"]', { @@ -562,7 +552,7 @@ describe('AriaQueryHandler', () => { }); it('should respond to node attribute mutation', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let divFound = false; const waitForSelector = page @@ -584,7 +574,7 @@ describe('AriaQueryHandler', () => { }); it('should return the element handle', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const waitForSelector = page.waitForSelector('aria/zombo').catch(err => { return err; @@ -598,7 +588,7 @@ describe('AriaQueryHandler', () => { }); it('should have correct stack trace for timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page.waitForSelector('aria/zombo', {timeout: 10}).catch(error_ => { @@ -611,9 +601,9 @@ describe('AriaQueryHandler', () => { }); describe('queryOne (Chromium web test)', () => { - beforeEach(async () => { - const {page} = getTestState(); - await page.setContent( + async function setupPage(): ReturnType { + const state = await getTestState(); + await state.page.setContent( `

title

@@ -658,7 +648,8 @@ describe('AriaQueryHandler', () => {
` ); - }); + return state; + } const getIds = async (elements: ElementHandle[]) => { return Promise.all( elements.map(element => { @@ -669,25 +660,25 @@ describe('AriaQueryHandler', () => { ); }; it('should find by name "foo"', async () => { - const {page} = getTestState(); + const {page} = await setupPage(); const found = await page.$$('aria/foo'); const ids = await getIds(found); expect(ids).toEqual(['node3', 'node5', 'node6']); }); it('should find by name "bar"', async () => { - const {page} = getTestState(); + const {page} = await setupPage(); const found = await page.$$('aria/bar'); const ids = await getIds(found); expect(ids).toEqual(['node1', 'node2', 'node8']); }); it('should find treeitem by name', async () => { - const {page} = getTestState(); + const {page} = await setupPage(); const found = await page.$$('aria/item1 item2 item3'); const ids = await getIds(found); expect(ids).toEqual(['node30']); }); it('should find by role "button"', async () => { - const {page} = getTestState(); + const {page} = await setupPage(); const found = (await page.$$('aria/[role="button"]')) as Array< ElementHandle >; @@ -702,13 +693,13 @@ describe('AriaQueryHandler', () => { ]); }); it('should find by role "heading"', async () => { - const {page} = getTestState(); + const {page} = await setupPage(); const found = await page.$$('aria/[role="heading"]'); const ids = await getIds(found); expect(ids).toEqual(['shown', 'hidden', 'node11', 'node13']); }); it('should find both ignored and unignored', async () => { - const {page} = getTestState(); + const {page} = await setupPage(); const found = await page.$$('aria/title'); const ids = await getIds(found); expect(ids).toEqual(['shown']); diff --git a/test/src/browser.spec.ts b/test/src/browser.spec.ts index dd9700bfe5a..26b445b243c 100644 --- a/test/src/browser.spec.ts +++ b/test/src/browser.spec.ts @@ -16,14 +16,12 @@ import expect from 'expect'; -import {getTestState, setupTestBrowserHooks} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; describe('Browser specs', function () { - setupTestBrowserHooks(); - describe('Browser.version', function () { it('should return version', async () => { - const {browser} = getTestState(); + const {browser} = await getTestState(); const version = await browser.version(); expect(version.length).toBeGreaterThan(0); @@ -33,7 +31,7 @@ describe('Browser specs', function () { describe('Browser.userAgent', function () { it('should include WebKit', async () => { - const {browser, isChrome} = getTestState(); + const {browser, isChrome} = await getTestState(); const userAgent = await browser.userAgent(); expect(userAgent.length).toBeGreaterThan(0); @@ -47,7 +45,7 @@ describe('Browser specs', function () { describe('Browser.target', function () { it('should return browser target', async () => { - const {browser} = getTestState(); + const {browser} = await getTestState(); const target = browser.target(); expect(target.type()).toBe('browser'); @@ -56,13 +54,13 @@ describe('Browser specs', function () { describe('Browser.process', function () { it('should return child_process instance', async () => { - const {browser} = getTestState(); + const {browser} = await getTestState(); const process = await browser.process(); expect(process!.pid).toBeGreaterThan(0); }); it('should not return child_process for remote browser', async () => { - const {browser, puppeteer} = getTestState(); + const {browser, puppeteer} = await getTestState(); const browserWSEndpoint = browser.wsEndpoint(); const remoteBrowser = await puppeteer.connect({ @@ -75,7 +73,7 @@ describe('Browser specs', function () { describe('Browser.isConnected', () => { it('should set the browser connected state', async () => { - const {browser, puppeteer} = getTestState(); + const {browser, puppeteer} = await getTestState(); const browserWSEndpoint = browser.wsEndpoint(); const newBrowser = await puppeteer.connect({ diff --git a/test/src/browsercontext.spec.ts b/test/src/browsercontext.spec.ts index d17d77457eb..fb4e79ef29d 100644 --- a/test/src/browsercontext.spec.ts +++ b/test/src/browsercontext.spec.ts @@ -17,13 +17,14 @@ import expect from 'expect'; import {TimeoutError} from 'puppeteer'; -import {getTestState, setupTestBrowserHooks} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; import {waitEvent} from './utils.js'; describe('BrowserContext', function () { - setupTestBrowserHooks(); it('should have default context', async () => { - const {browser} = getTestState(); + const {browser} = await getTestState({ + skipContextCreation: true, + }); expect(browser.browserContexts()).toHaveLength(1); const defaultContext = browser.browserContexts()[0]!; expect(defaultContext!.isIncognito()).toBe(false); @@ -35,7 +36,9 @@ describe('BrowserContext', function () { expect(error.message).toContain('cannot be closed'); }); it('should create new incognito context', async () => { - const {browser} = getTestState(); + const {browser} = await getTestState({ + skipContextCreation: true, + }); expect(browser.browserContexts()).toHaveLength(1); const context = await browser.createIncognitoBrowserContext(); @@ -46,7 +49,9 @@ describe('BrowserContext', function () { expect(browser.browserContexts()).toHaveLength(1); }); it('should close all belonging targets once closing context', async () => { - const {browser} = getTestState(); + const {browser} = await getTestState({ + skipContextCreation: true, + }); expect(await browser.pages()).toHaveLength(1); @@ -59,10 +64,8 @@ describe('BrowserContext', function () { expect(await browser.pages()).toHaveLength(1); }); it('window.open should use parent tab context', async () => { - const {browser, server} = getTestState(); + const {browser, server, page, context} = await getTestState(); - const context = await browser.createIncognitoBrowserContext(); - const page = await context.newPage(); await page.goto(server.EMPTY_PAGE); const [popupTarget] = await Promise.all([ waitEvent(browser, 'targetcreated'), @@ -71,12 +74,10 @@ describe('BrowserContext', function () { }, server.EMPTY_PAGE), ]); expect(popupTarget.browserContext()).toBe(context); - await context.close(); }); it('should fire target events', async () => { - const {browser, server} = getTestState(); + const {server, context} = await getTestState(); - const context = await browser.createIncognitoBrowserContext(); const events: any[] = []; context.on('targetcreated', target => { return events.push('CREATED: ' + target.url()); @@ -95,12 +96,10 @@ describe('BrowserContext', function () { `CHANGED: ${server.EMPTY_PAGE}`, `DESTROYED: ${server.EMPTY_PAGE}`, ]); - await context.close(); }); it('should wait for a target', async () => { - const {browser, server} = getTestState(); + const {server, context} = await getTestState(); - const context = await browser.createIncognitoBrowserContext(); let resolved = false; const targetPromise = context.waitForTarget(target => { @@ -131,11 +130,10 @@ describe('BrowserContext', function () { throw error; } } - await context.close(); }); it('should timeout waiting for a non-existent target', async () => { - const {browser, server} = getTestState(); + const {browser, server} = await getTestState(); const context = await browser.createIncognitoBrowserContext(); const error = await context @@ -155,7 +153,9 @@ describe('BrowserContext', function () { }); it('should isolate localStorage and cookies', async () => { - const {browser, server} = getTestState(); + const {browser, server} = await getTestState({ + skipContextCreation: true, + }); // Create two incognito contexts. const context1 = await browser.createIncognitoBrowserContext(); @@ -215,7 +215,9 @@ describe('BrowserContext', function () { }); it('should work across sessions', async () => { - const {browser, puppeteer} = getTestState(); + const {browser, puppeteer} = await getTestState({ + skipContextCreation: true, + }); expect(browser.browserContexts()).toHaveLength(1); const context = await browser.createIncognitoBrowserContext(); @@ -230,12 +232,15 @@ describe('BrowserContext', function () { }); it('should provide a context id', async () => { - const {browser} = getTestState(); + const {browser} = await getTestState({ + skipContextCreation: true, + }); expect(browser.browserContexts()).toHaveLength(1); expect(browser.browserContexts()[0]!.id).toBeUndefined(); const context = await browser.createIncognitoBrowserContext(); + console.log('2'); expect(browser.browserContexts()).toHaveLength(2); expect(browser.browserContexts()[1]!.id).toBeDefined(); await context.close(); diff --git a/test/src/chromiumonly.spec.ts b/test/src/chromiumonly.spec.ts index 3831bd727fc..caeecf51fce 100644 --- a/test/src/chromiumonly.spec.ts +++ b/test/src/chromiumonly.spec.ts @@ -17,12 +17,7 @@ import {IncomingMessage} from 'http'; import expect from 'expect'; -import { - getTestState, - launch, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState, launch} from './mocha-utils.js'; import {waitEvent} from './utils.js'; // TODO: rename this test suite to launch/connect test suite as it actually @@ -30,13 +25,9 @@ import {waitEvent} from './utils.js'; describe('Chromium-Specific Launcher tests', function () { describe('Puppeteer.launch |browserURL| option', function () { it('should be able to connect using browserUrl, with and without trailing slash', async () => { - const {defaultBrowserOptions, puppeteer} = getTestState(); - - const {close} = await launch( - Object.assign({}, defaultBrowserOptions, { - args: ['--remote-debugging-port=21222'], - }) - ); + const {close, puppeteer} = await launch({ + args: ['--remote-debugging-port=21222'], + }); try { const browserURL = 'http://127.0.0.1:21222'; @@ -64,13 +55,9 @@ describe('Chromium-Specific Launcher tests', function () { } }); it('should throw when using both browserWSEndpoint and browserURL', async () => { - const {defaultBrowserOptions, puppeteer} = getTestState(); - - const {browser, close} = await launch( - Object.assign({}, defaultBrowserOptions, { - args: ['--remote-debugging-port=21222'], - }) - ); + const {browser, close, puppeteer} = await launch({ + args: ['--remote-debugging-port=21222'], + }); try { const browserURL = 'http://127.0.0.1:21222'; @@ -91,13 +78,9 @@ describe('Chromium-Specific Launcher tests', function () { } }); it('should throw when trying to connect to non-existing browser', async () => { - const {defaultBrowserOptions, puppeteer} = getTestState(); - - const {close} = await launch( - Object.assign({}, defaultBrowserOptions, { - args: ['--remote-debugging-port=21222'], - }) - ); + const {close, puppeteer} = await launch({ + args: ['--remote-debugging-port=21222'], + }); try { const browserURL = 'http://127.0.0.1:32333'; @@ -116,9 +99,7 @@ describe('Chromium-Specific Launcher tests', function () { describe('Puppeteer.launch |pipe| option', function () { it('should support the pipe option', async () => { - const {defaultBrowserOptions} = getTestState(); - const options = Object.assign({pipe: true}, defaultBrowserOptions); - const {browser, close} = await launch(options, {createPage: false}); + const {browser, close} = await launch({pipe: true}, {createPage: false}); try { expect(await browser.pages()).toHaveLength(1); expect(browser.wsEndpoint()).toBe(''); @@ -130,7 +111,7 @@ describe('Chromium-Specific Launcher tests', function () { } }); it('should support the pipe argument', async () => { - const {defaultBrowserOptions} = getTestState(); + const {defaultBrowserOptions} = await getTestState({skipLaunch: true}); const options = Object.assign({}, defaultBrowserOptions); options.args = ['--remote-debugging-pipe'].concat(options.args || []); const {browser, close} = await launch(options); @@ -144,9 +125,7 @@ describe('Chromium-Specific Launcher tests', function () { } }); it('should fire "disconnected" when closing with pipe', async () => { - const {defaultBrowserOptions} = getTestState(); - const options = Object.assign({pipe: true}, defaultBrowserOptions); - const {browser, close} = await launch(options); + const {browser, close} = await launch({pipe: true}); try { const disconnectedEventPromise = waitEvent(browser, 'disconnected'); // Emulate user exiting browser. @@ -160,10 +139,8 @@ describe('Chromium-Specific Launcher tests', function () { }); describe('Chromium-Specific Page Tests', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); it('Page.setRequestInterception should work with intervention headers', async () => { - const {server, page} = getTestState(); + const {server, page} = await getTestState(); server.setRoute('/intervention', (_req, res) => { return res.end(` diff --git a/test/src/click.spec.ts b/test/src/click.spec.ts index 8e253f30857..fead209e8d2 100644 --- a/test/src/click.spec.ts +++ b/test/src/click.spec.ts @@ -17,18 +17,12 @@ import expect from 'expect'; import {KnownDevices} from 'puppeteer'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; import {attachFrame} from './utils.js'; describe('Page.click', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); it('should click the button', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/button.html'); await page.click('button'); @@ -39,7 +33,7 @@ describe('Page.click', function () { ).toBe('Clicked'); }); it('should click svg', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(` @@ -54,7 +48,7 @@ describe('Page.click', function () { ).toBe(42); }); it('should click the button if window.Node is removed', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/button.html'); await page.evaluate(() => { @@ -70,7 +64,7 @@ describe('Page.click', function () { }); // @see https://github.com/puppeteer/puppeteer/issues/4281 it('should click on a span with an inline element inside', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(`
spacer
'); @@ -442,7 +436,7 @@ describe('Page.click', function () { }); // @see https://github.com/puppeteer/puppeteer/issues/4110 it('should click the button with fixed position inside an iframe', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setViewport({width: 500, height: 500}); @@ -466,7 +460,7 @@ describe('Page.click', function () { ).toBe('Clicked'); }); it('should click the button with deviceScaleFactor set', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 400, height: 400, deviceScaleFactor: 5}); expect( diff --git a/test/src/cookies.spec.ts b/test/src/cookies.spec.ts index 2e57f2451c0..55a61809c56 100644 --- a/test/src/cookies.spec.ts +++ b/test/src/cookies.spec.ts @@ -15,32 +15,23 @@ */ import expect from 'expect'; -import { - expectCookieEquals, - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, - launch, -} from './mocha-utils.js'; +import {expectCookieEquals, getTestState, launch} from './mocha-utils.js'; describe('Cookie specs', () => { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - describe('Page.cookies', function () { it('should return no cookies in pristine browser context', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); - expectCookieEquals(await page.cookies(), []); + await expectCookieEquals(await page.cookies(), []); }); it('should get a cookie', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.evaluate(() => { document.cookie = 'username=John Doe'; }); - expectCookieEquals(await page.cookies(), [ + await expectCookieEquals(await page.cookies(), [ { name: 'username', value: 'John Doe', @@ -57,7 +48,7 @@ describe('Cookie specs', () => { ]); }); it('should properly report httpOnly cookie', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRoute('/empty.html', (_req, res) => { res.setHeader('Set-Cookie', 'a=b; HttpOnly; Path=/'); res.end(); @@ -68,7 +59,7 @@ describe('Cookie specs', () => { expect(cookies[0]!.httpOnly).toBe(true); }); it('should properly report "Strict" sameSite cookie', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRoute('/empty.html', (_req, res) => { res.setHeader('Set-Cookie', 'a=b; SameSite=Strict'); res.end(); @@ -79,7 +70,7 @@ describe('Cookie specs', () => { expect(cookies[0]!.sameSite).toBe('Strict'); }); it('should properly report "Lax" sameSite cookie', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRoute('/empty.html', (_req, res) => { res.setHeader('Set-Cookie', 'a=b; SameSite=Lax'); res.end(); @@ -90,7 +81,7 @@ describe('Cookie specs', () => { expect(cookies[0]!.sameSite).toBe('Lax'); }); it('should get multiple cookies', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.evaluate(() => { document.cookie = 'username=John Doe'; @@ -100,7 +91,7 @@ describe('Cookie specs', () => { cookies.sort((a, b) => { return a.name.localeCompare(b.name); }); - expectCookieEquals(cookies, [ + await expectCookieEquals(cookies, [ { name: 'password', value: '1234', @@ -130,7 +121,7 @@ describe('Cookie specs', () => { ]); }); it('should get cookies from multiple urls', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setCookie( { url: 'https://foo.com', @@ -152,7 +143,7 @@ describe('Cookie specs', () => { cookies.sort((a, b) => { return a.name.localeCompare(b.name); }); - expectCookieEquals(cookies, [ + await expectCookieEquals(cookies, [ { name: 'birdo', value: 'tweets', @@ -186,7 +177,7 @@ describe('Cookie specs', () => { }); describe('Page.setCookie', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setCookie({ @@ -200,7 +191,7 @@ describe('Cookie specs', () => { ).toEqual('password=123456'); }); it('should isolate cookies in browser contexts', async () => { - const {page, server, browser} = getTestState(); + const {page, server, browser} = await getTestState(); const anotherContext = await browser.createIncognitoBrowserContext(); const anotherPage = await anotherContext.newPage(); @@ -222,7 +213,7 @@ describe('Cookie specs', () => { await anotherContext.close(); }); it('should set multiple cookies', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setCookie( @@ -247,7 +238,7 @@ describe('Cookie specs', () => { expect(cookieStrings).toEqual(['foo=bar', 'password=123456']); }); it('should have |expires| set to |-1| for session cookies', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setCookie({ @@ -259,7 +250,7 @@ describe('Cookie specs', () => { expect(cookies[0]!.expires).toBe(-1); }); it('should set cookie with reasonable defaults', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setCookie({ @@ -267,7 +258,7 @@ describe('Cookie specs', () => { value: '123456', }); const cookies = await page.cookies(); - expectCookieEquals( + await expectCookieEquals( cookies.sort((a, b) => { return a.name.localeCompare(b.name); }), @@ -290,7 +281,7 @@ describe('Cookie specs', () => { ); }); it('should set a cookie with a path', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/grid.html'); await page.setCookie({ @@ -298,7 +289,7 @@ describe('Cookie specs', () => { value: 'GRID', path: '/grid.html', }); - expectCookieEquals(await page.cookies(), [ + await expectCookieEquals(await page.cookies(), [ { name: 'gridcookie', value: 'GRID', @@ -316,13 +307,13 @@ describe('Cookie specs', () => { ]); expect(await page.evaluate('document.cookie')).toBe('gridcookie=GRID'); await page.goto(server.EMPTY_PAGE); - expectCookieEquals(await page.cookies(), []); + await expectCookieEquals(await page.cookies(), []); expect(await page.evaluate('document.cookie')).toBe(''); await page.goto(server.PREFIX + '/grid.html'); expect(await page.evaluate('document.cookie')).toBe('gridcookie=GRID'); }); it('should not set a cookie on a blank page', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.goto('about:blank'); let error!: Error; @@ -336,7 +327,7 @@ describe('Cookie specs', () => { ); }); it('should not set a cookie with blank page URL', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let error!: Error; await page.goto(server.EMPTY_PAGE); @@ -353,7 +344,7 @@ describe('Cookie specs', () => { ); }); it('should not set a cookie on a data URL page', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page.goto('data:,Hello%2C%20World!'); @@ -367,7 +358,7 @@ describe('Cookie specs', () => { ); }); it('should default to setting secure cookie for HTTPS websites', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const SECURE_URL = 'https://example.com'; @@ -380,7 +371,7 @@ describe('Cookie specs', () => { expect(cookie!.secure).toBe(true); }); it('should be able to set insecure cookie for HTTP website', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const HTTP_URL = 'http://example.com'; @@ -393,7 +384,7 @@ describe('Cookie specs', () => { expect(cookie!.secure).toBe(false); }); it('should set a cookie on a different domain', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setCookie({ @@ -402,8 +393,8 @@ describe('Cookie specs', () => { value: 'best', }); expect(await page.evaluate('document.cookie')).toBe(''); - expectCookieEquals(await page.cookies(), []); - expectCookieEquals(await page.cookies('https://www.example.com'), [ + await expectCookieEquals(await page.cookies(), []); + await expectCookieEquals(await page.cookies('https://www.example.com'), [ { name: 'example-cookie', value: 'best', @@ -421,7 +412,7 @@ describe('Cookie specs', () => { ]); }); it('should set cookies from a frame', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/grid.html'); await page.setCookie({name: 'localhost-cookie', value: 'best'}); @@ -446,7 +437,7 @@ describe('Cookie specs', () => { ); expect(await page.frames()[1]!.evaluate('document.cookie')).toBe(''); - expectCookieEquals(await page.cookies(), [ + await expectCookieEquals(await page.cookies(), [ { name: 'localhost-cookie', value: 'best', @@ -463,28 +454,28 @@ describe('Cookie specs', () => { }, ]); - expectCookieEquals(await page.cookies(server.CROSS_PROCESS_PREFIX), [ - { - name: '127-cookie', - value: 'worst', - domain: '127.0.0.1', - path: '/', - sameParty: false, - expires: -1, - size: 15, - httpOnly: false, - secure: false, - session: true, - sourcePort: 80, - sourceScheme: 'NonSecure', - }, - ]); + await expectCookieEquals( + await page.cookies(server.CROSS_PROCESS_PREFIX), + [ + { + name: '127-cookie', + value: 'worst', + domain: '127.0.0.1', + path: '/', + sameParty: false, + expires: -1, + size: 15, + httpOnly: false, + secure: false, + session: true, + sourcePort: 80, + sourceScheme: 'NonSecure', + }, + ] + ); }); it('should set secure same-site cookies from a frame', async () => { - const {httpsServer, defaultBrowserOptions} = getTestState(); - - const {browser, close} = await launch({ - ...defaultBrowserOptions, + const {httpsServer, browser, close} = await launch({ ignoreHTTPSErrors: true, }); @@ -512,7 +503,7 @@ describe('Cookie specs', () => { expect(await page.frames()[1]!.evaluate('document.cookie')).toBe( '127-same-site-cookie=best' ); - expectCookieEquals( + await expectCookieEquals( await page.cookies(httpsServer.CROSS_PROCESS_PREFIX), [ { @@ -540,7 +531,7 @@ describe('Cookie specs', () => { describe('Page.deleteCookie', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setCookie( diff --git a/test/src/coverage.spec.ts b/test/src/coverage.spec.ts index 7c93fc73bac..a8bcb7d6fe2 100644 --- a/test/src/coverage.spec.ts +++ b/test/src/coverage.spec.ts @@ -16,19 +16,12 @@ import expect from 'expect'; -import { - getTestState, - setupTestPageAndContextHooks, - setupTestBrowserHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; describe('Coverage specs', function () { describe('JSCoverage', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startJSCoverage(); await page.goto(server.PREFIX + '/jscoverage/simple.html', { waitUntil: 'networkidle0', @@ -42,7 +35,7 @@ describe('Coverage specs', function () { ]); }); it('should report sourceURLs', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startJSCoverage(); await page.goto(server.PREFIX + '/jscoverage/sourceurl.html'); @@ -51,7 +44,7 @@ describe('Coverage specs', function () { expect(coverage[0]!.url).toBe('nicename.js'); }); it('should ignore eval() scripts by default', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startJSCoverage(); await page.goto(server.PREFIX + '/jscoverage/eval.html'); @@ -59,7 +52,7 @@ describe('Coverage specs', function () { expect(coverage).toHaveLength(1); }); it("shouldn't ignore eval() scripts if reportAnonymousScripts is true", async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startJSCoverage({reportAnonymousScripts: true}); await page.goto(server.PREFIX + '/jscoverage/eval.html'); @@ -72,7 +65,7 @@ describe('Coverage specs', function () { expect(coverage).toHaveLength(2); }); it('should ignore pptr internal scripts if reportAnonymousScripts is true', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startJSCoverage({reportAnonymousScripts: true}); await page.goto(server.EMPTY_PAGE); @@ -84,7 +77,7 @@ describe('Coverage specs', function () { expect(coverage).toHaveLength(0); }); it('should report multiple scripts', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startJSCoverage(); await page.goto(server.PREFIX + '/jscoverage/multiple.html'); @@ -97,7 +90,7 @@ describe('Coverage specs', function () { expect(coverage[1]!.url).toContain('/jscoverage/script2.js'); }); it('should report right ranges', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startJSCoverage(); await page.goto(server.PREFIX + '/jscoverage/ranges.html'); @@ -113,7 +106,7 @@ describe('Coverage specs', function () { ); }); it('should report right ranges for "per function" scope', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const coverageOptions = { useBlockCoverage: false, @@ -133,7 +126,7 @@ describe('Coverage specs', function () { ); }); it('should report scripts that have no coverage', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startJSCoverage(); await page.goto(server.PREFIX + '/jscoverage/unused.html'); @@ -144,7 +137,7 @@ describe('Coverage specs', function () { expect(entry.ranges).toHaveLength(0); }); it('should work with conditionals', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startJSCoverage(); await page.goto(server.PREFIX + '/jscoverage/involved.html'); @@ -155,7 +148,7 @@ describe('Coverage specs', function () { }); // @see https://crbug.com/990945 it.skip('should not hang when there is a debugger statement', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startJSCoverage(); await page.goto(server.EMPTY_PAGE); @@ -166,7 +159,7 @@ describe('Coverage specs', function () { }); describe('resetOnNavigation', function () { it('should report scripts across navigations when disabled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startJSCoverage({resetOnNavigation: false}); await page.goto(server.PREFIX + '/jscoverage/multiple.html'); @@ -176,7 +169,7 @@ describe('Coverage specs', function () { }); it('should NOT report scripts across navigations when enabled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startJSCoverage(); // Enabled by default. await page.goto(server.PREFIX + '/jscoverage/multiple.html'); @@ -187,7 +180,7 @@ describe('Coverage specs', function () { }); describe('includeRawScriptCoverage', function () { it('should not include rawScriptCoverage field when disabled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startJSCoverage(); await page.goto(server.PREFIX + '/jscoverage/simple.html', { waitUntil: 'networkidle0', @@ -197,7 +190,7 @@ describe('Coverage specs', function () { expect(coverage[0]!.rawScriptCoverage).toBeUndefined(); }); it('should include rawScriptCoverage field when enabled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startJSCoverage({ includeRawScriptCoverage: true, }); @@ -211,7 +204,7 @@ describe('Coverage specs', function () { }); // @see https://crbug.com/990945 it.skip('should not hang when there is a debugger statement', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startJSCoverage(); await page.goto(server.EMPTY_PAGE); @@ -223,11 +216,8 @@ describe('Coverage specs', function () { }); describe('CSSCoverage', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startCSSCoverage(); await page.goto(server.PREFIX + '/csscoverage/simple.html'); @@ -241,7 +231,7 @@ describe('Coverage specs', function () { ); }); it('should report sourceURLs', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startCSSCoverage(); await page.goto(server.PREFIX + '/csscoverage/sourceurl.html'); @@ -250,7 +240,7 @@ describe('Coverage specs', function () { expect(coverage[0]!.url).toBe('nicename.css'); }); it('should report multiple stylesheets', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startCSSCoverage(); await page.goto(server.PREFIX + '/csscoverage/multiple.html'); @@ -263,7 +253,7 @@ describe('Coverage specs', function () { expect(coverage[1]!.url).toContain('/csscoverage/stylesheet2.css'); }); it('should report stylesheets that have no coverage', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startCSSCoverage(); await page.goto(server.PREFIX + '/csscoverage/unused.html'); @@ -273,7 +263,7 @@ describe('Coverage specs', function () { expect(coverage[0]!.ranges).toHaveLength(0); }); it('should work with media queries', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startCSSCoverage(); await page.goto(server.PREFIX + '/csscoverage/media.html'); @@ -283,7 +273,7 @@ describe('Coverage specs', function () { expect(coverage[0]!.ranges).toEqual([{start: 8, end: 40}]); }); it('should work with complicated usecases', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startCSSCoverage(); await page.goto(server.PREFIX + '/csscoverage/involved.html'); @@ -293,7 +283,7 @@ describe('Coverage specs', function () { ).toBeGolden('csscoverage-involved.txt'); }); it('should work with empty stylesheets', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startCSSCoverage(); await page.goto(server.PREFIX + '/csscoverage/empty.html'); @@ -302,7 +292,7 @@ describe('Coverage specs', function () { expect(coverage[0]!.text).toEqual(''); }); it('should ignore injected stylesheets', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.coverage.startCSSCoverage(); await page.addStyleTag({content: 'body { margin: 10px;}'}); @@ -315,7 +305,7 @@ describe('Coverage specs', function () { expect(coverage).toHaveLength(0); }); it('should work with a recently loaded stylesheet', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startCSSCoverage(); await page.evaluate(async url => { @@ -334,7 +324,7 @@ describe('Coverage specs', function () { }); describe('resetOnNavigation', function () { it('should report stylesheets across navigations', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startCSSCoverage({resetOnNavigation: false}); await page.goto(server.PREFIX + '/csscoverage/multiple.html'); @@ -343,7 +333,7 @@ describe('Coverage specs', function () { expect(coverage).toHaveLength(2); }); it('should NOT report scripts across navigations', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.coverage.startCSSCoverage(); // Enabled by default. await page.goto(server.PREFIX + '/csscoverage/multiple.html'); diff --git a/test/src/defaultbrowsercontext.spec.ts b/test/src/defaultbrowsercontext.spec.ts index 73c31d73c44..1b3e14a9341 100644 --- a/test/src/defaultbrowsercontext.spec.ts +++ b/test/src/defaultbrowsercontext.spec.ts @@ -15,24 +15,17 @@ */ import expect from 'expect'; -import { - expectCookieEquals, - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {expectCookieEquals, getTestState} from './mocha-utils.js'; describe('DefaultBrowserContext', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); it('page.cookies() should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.evaluate(() => { document.cookie = 'username=John Doe'; }); - expectCookieEquals(await page.cookies(), [ + await expectCookieEquals(await page.cookies(), [ { name: 'username', value: 'John Doe', @@ -49,7 +42,7 @@ describe('DefaultBrowserContext', function () { ]); }); it('page.setCookie() should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setCookie({ @@ -61,7 +54,7 @@ describe('DefaultBrowserContext', function () { return document.cookie; }) ).toBe('username=John Doe'); - expectCookieEquals(await page.cookies(), [ + await expectCookieEquals(await page.cookies(), [ { name: 'username', value: 'John Doe', @@ -79,7 +72,7 @@ describe('DefaultBrowserContext', function () { ]); }); it('page.deleteCookie() should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setCookie( @@ -95,7 +88,7 @@ describe('DefaultBrowserContext', function () { expect(await page.evaluate('document.cookie')).toBe('cookie1=1; cookie2=2'); await page.deleteCookie({name: 'cookie2'}); expect(await page.evaluate('document.cookie')).toBe('cookie1=1'); - expectCookieEquals(await page.cookies(), [ + await expectCookieEquals(await page.cookies(), [ { name: 'cookie1', value: '1', diff --git a/test/src/dialog.spec.ts b/test/src/dialog.spec.ts index e4489004cdb..025fba1ff3f 100644 --- a/test/src/dialog.spec.ts +++ b/test/src/dialog.spec.ts @@ -16,18 +16,11 @@ import expect from 'expect'; import sinon from 'sinon'; -import { - getTestState, - setupTestPageAndContextHooks, - setupTestBrowserHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; describe('Page.Events.Dialog', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - it('should fire', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const onDialog = sinon.stub().callsFake(dialog => { dialog.accept(); @@ -46,7 +39,7 @@ describe('Page.Events.Dialog', function () { }); it('should allow accepting prompts', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const onDialog = sinon.stub().callsFake(dialog => { dialog.accept('answer!'); @@ -66,7 +59,7 @@ describe('Page.Events.Dialog', function () { expect(result).toBe('answer!'); }); it('should dismiss the prompt', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); page.on('dialog', dialog => { dialog.dismiss(); diff --git a/test/src/drag-and-drop.spec.ts b/test/src/drag-and-drop.spec.ts index cb46b5e60ca..55a2ea3d1b3 100644 --- a/test/src/drag-and-drop.spec.ts +++ b/test/src/drag-and-drop.spec.ts @@ -16,17 +16,11 @@ import expect from 'expect'; -import { - getTestState, - setupTestPageAndContextHooks, - setupTestBrowserHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; describe('Input.drag', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); it('should throw an exception if not enabled before usage', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/drag-and-drop.html'); const draggable = (await page.$('#drag'))!; @@ -40,7 +34,7 @@ describe('Input.drag', function () { } }); it('should emit a dragIntercepted event when dragged', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/drag-and-drop.html'); expect(page.isDragInterceptionEnabled()).toBe(false); @@ -57,7 +51,7 @@ describe('Input.drag', function () { ).toBe(true); }); it('should emit a dragEnter', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/drag-and-drop.html'); expect(page.isDragInterceptionEnabled()).toBe(false); @@ -80,7 +74,7 @@ describe('Input.drag', function () { ).toBe(true); }); it('should emit a dragOver event', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/drag-and-drop.html'); expect(page.isDragInterceptionEnabled()).toBe(false); @@ -109,7 +103,7 @@ describe('Input.drag', function () { ).toBe(true); }); it('can be dropped', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/drag-and-drop.html'); expect(page.isDragInterceptionEnabled()).toBe(false); @@ -144,7 +138,7 @@ describe('Input.drag', function () { ).toBe(true); }); it('can be dragged and dropped with a single function', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/drag-and-drop.html'); expect(page.isDragInterceptionEnabled()).toBe(false); @@ -176,7 +170,7 @@ describe('Input.drag', function () { ).toBe(true); }); it('can be disabled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/drag-and-drop.html'); expect(page.isDragInterceptionEnabled()).toBe(false); diff --git a/test/src/elementhandle.spec.ts b/test/src/elementhandle.spec.ts index 2dabe781f6f..a6de3589e8c 100644 --- a/test/src/elementhandle.spec.ts +++ b/test/src/elementhandle.spec.ts @@ -21,19 +21,14 @@ import sinon from 'sinon'; import { getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, shortWaitForArrayToHaveAtLeastNElements, } from './mocha-utils.js'; import {attachFrame} from './utils.js'; describe('ElementHandle specs', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - describe('ElementHandle.boundingBox', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.goto(server.PREFIX + '/grid.html'); @@ -42,7 +37,7 @@ describe('ElementHandle specs', function () { expect(box).toEqual({x: 100, y: 50, width: 50, height: 50}); }); it('should handle nested frames', async () => { - const {page, server, isChrome} = getTestState(); + const {page, server, isChrome} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.goto(server.PREFIX + '/frames/nested-frames.html'); @@ -56,14 +51,14 @@ describe('ElementHandle specs', function () { } }); it('should return null for invisible elements', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
hi
'); const element = (await page.$('div'))!; expect(await element.boundingBox()).toBe(null); }); it('should force a layout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.setContent( @@ -77,7 +72,7 @@ describe('ElementHandle specs', function () { expect(box).toEqual({x: 8, y: 8, width: 100, height: 200}); }); it('should work with SVG nodes', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(` @@ -98,7 +93,7 @@ describe('ElementHandle specs', function () { describe('ElementHandle.boxModel', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/resetcss.html'); @@ -153,7 +148,7 @@ describe('ElementHandle specs', function () { }); it('should return null for invisible elements', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
hi
'); const element = (await page.$('div'))!; @@ -163,7 +158,7 @@ describe('ElementHandle specs', function () { describe('ElementHandle.contentFrame', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await attachFrame(page, 'frame1', server.EMPTY_PAGE); @@ -175,7 +170,7 @@ describe('ElementHandle specs', function () { describe('ElementHandle.isVisible and ElementHandle.isHidden', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
text
'); const element = (await page.waitForSelector('div'))!; await expect(element.isVisible()).resolves.toBeFalsy(); @@ -190,7 +185,7 @@ describe('ElementHandle specs', function () { describe('ElementHandle.click', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/button.html'); const button = (await page.$('button'))!; @@ -202,7 +197,7 @@ describe('ElementHandle specs', function () { ).toBe('Clicked'); }); it('should return Point data', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const clicks: Array<[x: number, y: number]> = []; @@ -236,7 +231,7 @@ describe('ElementHandle specs', function () { ]); }); it('should work for Shadow DOM v1', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/shadow.html'); const buttonHandle = await page.evaluateHandle(() => { @@ -252,7 +247,7 @@ describe('ElementHandle specs', function () { ).toBe(true); }); it('should not work for TextNodes', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/button.html'); const buttonTextNode = await page.evaluateHandle(() => { @@ -268,7 +263,7 @@ describe('ElementHandle specs', function () { ]); }); it('should throw for detached nodes', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/button.html'); const button = (await page.$('button'))!; @@ -285,7 +280,7 @@ describe('ElementHandle specs', function () { ]); }); it('should throw for hidden nodes', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/button.html'); const button = (await page.$('button'))!; @@ -301,7 +296,7 @@ describe('ElementHandle specs', function () { ]); }); it('should throw for recursively hidden nodes', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/button.html'); const button = (await page.$('button'))!; @@ -317,7 +312,7 @@ describe('ElementHandle specs', function () { ]); }); it('should throw for
elements', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('hello
goodbye'); const br = (await page.$('br'))!; @@ -333,7 +328,7 @@ describe('ElementHandle specs', function () { describe('ElementHandle.clickablePoint', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.evaluate(() => { document.body.style.padding = '0'; @@ -364,7 +359,7 @@ describe('ElementHandle specs', function () { }); it('should work for iframes', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.evaluate(() => { document.body.style.padding = '10px'; document.body.style.margin = '10px'; @@ -397,7 +392,7 @@ describe('ElementHandle specs', function () { describe('Element.waitForSelector', () => { it('should wait correctly with waitForSelector on an element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const waitFor = page.waitForSelector('.foo').catch(err => { return err; }) as Promise>; @@ -432,7 +427,7 @@ describe('ElementHandle specs', function () { describe('Element.waitForXPath', () => { it('should wait correctly with waitForXPath on an element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); // Set the page content after the waitFor has been started. await page.setContent( `
@@ -465,7 +460,7 @@ describe('ElementHandle specs', function () { describe('ElementHandle.hover', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/scrollable.html'); const button = (await page.$('#button-6'))!; @@ -480,7 +475,7 @@ describe('ElementHandle specs', function () { describe('ElementHandle.isIntersectingViewport', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); async function getVisibilityForButton(selector: string) { const button = (await page.$(selector))!; @@ -502,7 +497,7 @@ describe('ElementHandle specs', function () { } }); it('should work with threshold', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/offscreenbuttons.html'); // a button almost cannot be seen @@ -515,7 +510,7 @@ describe('ElementHandle specs', function () { ).toBe(false); }); it('should work with threshold of 1', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/offscreenbuttons.html'); // a button almost cannot be seen @@ -528,7 +523,7 @@ describe('ElementHandle specs', function () { ).toBe(true); }); it('should work with svg elements', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/inline-svg.html'); const [visibleCircle, visibleSvg] = await Promise.all([ @@ -602,7 +597,7 @@ describe('ElementHandle specs', function () { Puppeteer.clearCustomQueryHandlers(); }); it('should register and unregister', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
'); // Register. @@ -653,7 +648,7 @@ describe('ElementHandle specs', function () { } }); it('should work for multiple elements', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
Foo1
Foo2
' ); @@ -676,7 +671,7 @@ describe('ElementHandle specs', function () { expect(classNames).toStrictEqual(['foo', 'foo baz']); }); it('should eval correctly', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
Foo1
Foo2
' ); @@ -692,7 +687,7 @@ describe('ElementHandle specs', function () { expect(elements).toBe(2); }); it('should wait correctly with waitForSelector', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); Puppeteer.registerCustomQueryHandler('getByClass', { queryOne: (element, selector) => { return (element as Element).querySelector(`.${selector}`); @@ -716,7 +711,7 @@ describe('ElementHandle specs', function () { }); it('should wait correctly with waitForSelector on an element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); Puppeteer.registerCustomQueryHandler('getByClass', { queryOne: (element, selector) => { return (element as Element).querySelector(`.${selector}`); @@ -761,7 +756,7 @@ describe('ElementHandle specs', function () { it('should wait correctly with waitFor', async () => { /* page.waitFor is deprecated so we silence the warning to avoid test noise */ sinon.stub(console, 'warn').callsFake(() => {}); - const {page} = getTestState(); + const {page} = await getTestState(); Puppeteer.registerCustomQueryHandler('getByClass', { queryOne: (element, selector) => { return (element as Element).querySelector(`.${selector}`); @@ -784,7 +779,7 @@ describe('ElementHandle specs', function () { expect(element).toBeDefined(); }); it('should work when both queryOne and queryAll are registered', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
Foo2
' ); @@ -804,7 +799,7 @@ describe('ElementHandle specs', function () { expect(elements).toHaveLength(3); }); it('should eval when both queryOne and queryAll are registered', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
text
content
' ); @@ -833,7 +828,7 @@ describe('ElementHandle specs', function () { }); it('should work with function shorthands', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
'); Puppeteer.registerCustomQueryHandler('getById', { @@ -856,7 +851,7 @@ describe('ElementHandle specs', function () { describe('Element.toElement', () => { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
Foo1
'); const element = await page.$('.foo'); const div = await element?.toElement('div'); diff --git a/test/src/emulation.spec.ts b/test/src/emulation.spec.ts index 43ea9bf59cf..0205abbc110 100644 --- a/test/src/emulation.spec.ts +++ b/test/src/emulation.spec.ts @@ -17,29 +17,22 @@ import expect from 'expect'; import {KnownDevices, PredefinedNetworkConditions} from 'puppeteer'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; const iPhone = KnownDevices['iPhone 6']; const iPhoneLandscape = KnownDevices['iPhone 6 landscape']; describe('Emulation', () => { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - describe('Page.viewport', function () { it('should get the proper viewport size', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); expect(page.viewport()).toEqual({width: 800, height: 600}); await page.setViewport({width: 123, height: 456}); expect(page.viewport()).toEqual({width: 123, height: 456}); }); it('should support mobile emulation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/mobile.html'); expect( @@ -61,7 +54,7 @@ describe('Emulation', () => { ).toBe(400); }); it('should support touch emulation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/mobile.html'); expect( @@ -99,7 +92,7 @@ describe('Emulation', () => { } }); it('should be detectable by Modernizr', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/detect-touch.html'); expect( @@ -116,7 +109,7 @@ describe('Emulation', () => { ).toBe('YES'); }); it('should detect touch when applying viewport with touches', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 800, height: 600, hasTouch: true}); await page.addScriptTag({url: server.PREFIX + '/modernizr.js'}); @@ -127,7 +120,7 @@ describe('Emulation', () => { ).toBe(true); }); it('should support landscape emulation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/mobile.html'); expect( @@ -152,7 +145,7 @@ describe('Emulation', () => { describe('Page.emulate', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/mobile.html'); await page.emulate(iPhone); @@ -168,7 +161,7 @@ describe('Emulation', () => { ).toContain('iPhone'); }); it('should support clicking', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.emulate(iPhone); await page.goto(server.PREFIX + '/input/button.html'); @@ -187,7 +180,7 @@ describe('Emulation', () => { describe('Page.emulateMediaType', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); expect( await page.evaluate(() => { @@ -223,7 +216,7 @@ describe('Emulation', () => { ).toBe(false); }); it('should throw in case of bad argument', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page.emulateMediaType('bad').catch(error_ => { @@ -235,7 +228,7 @@ describe('Emulation', () => { describe('Page.emulateMediaFeatures', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.emulateMediaFeatures([ {name: 'prefers-reduced-motion', value: 'reduce'}, @@ -352,7 +345,7 @@ describe('Emulation', () => { ).toBe(true); }); it('should throw in case of bad argument', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page @@ -366,7 +359,7 @@ describe('Emulation', () => { describe('Page.emulateTimezone', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.evaluate(() => { (globalThis as any).date = new Date(1479579154987); @@ -405,7 +398,7 @@ describe('Emulation', () => { }); it('should throw for invalid timezone IDs', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page.emulateTimezone('Foo/Bar').catch(error_ => { @@ -421,7 +414,7 @@ describe('Emulation', () => { describe('Page.emulateVisionDeficiency', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.goto(server.PREFIX + '/grid.html'); @@ -470,7 +463,7 @@ describe('Emulation', () => { }); it('should throw for invalid vision deficiencies', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page @@ -485,7 +478,7 @@ describe('Emulation', () => { describe('Page.emulateNetworkConditions', function () { it('should change navigator.connection.effectiveType', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const slow3G = PredefinedNetworkConditions['Slow 3G']!; const fast3G = PredefinedNetworkConditions['Fast 3G']!; @@ -507,7 +500,7 @@ describe('Emulation', () => { describe('Page.emulateCPUThrottling', function () { it('should change the CPU throttling rate successfully', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.emulateCPUThrottling(100); await page.emulateCPUThrottling(null); diff --git a/test/src/evaluation.spec.ts b/test/src/evaluation.spec.ts index 7c683db569f..313e4703156 100644 --- a/test/src/evaluation.spec.ts +++ b/test/src/evaluation.spec.ts @@ -16,20 +16,13 @@ import expect from 'expect'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; import {attachFrame} from './utils.js'; describe('Evaluation specs', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - describe('Page.evaluate', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate(() => { return 7 * 3; @@ -37,7 +30,7 @@ describe('Evaluation specs', function () { expect(result).toBe(21); }); it('should transfer BigInt', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate((a: bigint) => { return a; @@ -45,7 +38,7 @@ describe('Evaluation specs', function () { expect(result).toBe(BigInt(42)); }); it('should transfer NaN', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate(a => { return a; @@ -53,7 +46,7 @@ describe('Evaluation specs', function () { expect(Object.is(result, NaN)).toBe(true); }); it('should transfer -0', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate(a => { return a; @@ -61,7 +54,7 @@ describe('Evaluation specs', function () { expect(Object.is(result, -0)).toBe(true); }); it('should transfer Infinity', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate(a => { return a; @@ -69,7 +62,7 @@ describe('Evaluation specs', function () { expect(Object.is(result, Infinity)).toBe(true); }); it('should transfer -Infinity', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate(a => { return a; @@ -77,7 +70,7 @@ describe('Evaluation specs', function () { expect(Object.is(result, -Infinity)).toBe(true); }); it('should transfer arrays', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate( a => { @@ -88,7 +81,7 @@ describe('Evaluation specs', function () { expect(result).toEqual([1, 2, 3]); }); it('should transfer arrays as arrays, not objects', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate( a => { @@ -99,7 +92,7 @@ describe('Evaluation specs', function () { expect(result).toBe(true); }); it('should modify global environment', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.evaluate(() => { return ((globalThis as any).globalVar = 123); @@ -107,13 +100,13 @@ describe('Evaluation specs', function () { expect(await page.evaluate('globalVar')).toBe(123); }); it('should evaluate in the page context', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/global-var.html'); expect(await page.evaluate('globalVar')).toBe(123); }); it('should return undefined for objects with symbols', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); expect( await page.evaluate(() => { @@ -122,7 +115,7 @@ describe('Evaluation specs', function () { ).toBe(undefined); }); it('should work with function shorthands', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const a = { sum(a: number, b: number) { @@ -137,7 +130,7 @@ describe('Evaluation specs', function () { expect(await page.evaluate(a.mult, 2, 4)).toBe(8); }); it('should work with unicode chars', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate( a => { @@ -150,7 +143,7 @@ describe('Evaluation specs', function () { expect(result).toBe(42); }); it('should throw when evaluation triggers reload', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page @@ -164,7 +157,7 @@ describe('Evaluation specs', function () { expect(error.message).toContain('Protocol error'); }); it('should await promise', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate(() => { return Promise.resolve(8 * 7); @@ -172,7 +165,7 @@ describe('Evaluation specs', function () { expect(result).toBe(56); }); it('should work right after framenavigated', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let frameEvaluation = null; page.on('framenavigated', async frame => { @@ -184,7 +177,7 @@ describe('Evaluation specs', function () { expect(await frameEvaluation).toBe(42); }); it('should work from-inside an exposed function', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); // Setup inpage callback, which calls Page.evaluate await page.exposeFunction( @@ -205,7 +198,7 @@ describe('Evaluation specs', function () { expect(result).toBe(27); }); it('should reject promise with exception', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page @@ -220,7 +213,7 @@ describe('Evaluation specs', function () { expect(error.message).toContain('notExistingObject'); }); it('should support thrown strings as error messages', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page @@ -233,7 +226,7 @@ describe('Evaluation specs', function () { expect(error).toEqual('qwerty'); }); it('should support thrown numbers as error messages', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page @@ -246,7 +239,7 @@ describe('Evaluation specs', function () { expect(error).toEqual(100500); }); it('should return complex objects', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const object = {foo: 'bar!'}; const result = await page.evaluate(a => { @@ -256,7 +249,7 @@ describe('Evaluation specs', function () { expect(result).toEqual(object); }); it('should return BigInt', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate(() => { return BigInt(42); @@ -264,7 +257,7 @@ describe('Evaluation specs', function () { expect(result).toBe(BigInt(42)); }); it('should return NaN', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate(() => { return NaN; @@ -272,7 +265,7 @@ describe('Evaluation specs', function () { expect(Object.is(result, NaN)).toBe(true); }); it('should return -0', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate(() => { return -0; @@ -280,7 +273,7 @@ describe('Evaluation specs', function () { expect(Object.is(result, -0)).toBe(true); }); it('should return Infinity', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate(() => { return Infinity; @@ -288,7 +281,7 @@ describe('Evaluation specs', function () { expect(Object.is(result, Infinity)).toBe(true); }); it('should return -Infinity', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate(() => { return -Infinity; @@ -296,7 +289,7 @@ describe('Evaluation specs', function () { expect(Object.is(result, -Infinity)).toBe(true); }); it('should accept "null" as one of multiple parameters', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate( (a, b) => { @@ -308,7 +301,7 @@ describe('Evaluation specs', function () { expect(result).toBe(true); }); it('should properly serialize null fields', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); expect( await page.evaluate(() => { @@ -317,7 +310,7 @@ describe('Evaluation specs', function () { ).toEqual({}); }); it('should return undefined for non-serializable objects', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); expect( await page.evaluate(() => { @@ -326,7 +319,7 @@ describe('Evaluation specs', function () { ).toBe(undefined); }); it('should return promise as empty object', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate(() => { return { @@ -340,7 +333,7 @@ describe('Evaluation specs', function () { }); }); it('should fail for circular object', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate(() => { const a: {[x: string]: any} = {}; @@ -351,7 +344,7 @@ describe('Evaluation specs', function () { expect(result).toBe(undefined); }); it('should be able to throw a tricky error', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const windowHandle = await page.evaluateHandle(() => { return window; @@ -369,25 +362,25 @@ describe('Evaluation specs', function () { expect(error.message).toContain(errorText); }); it('should accept a string', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate('1 + 2'); expect(result).toBe(3); }); it('should accept a string with semi colons', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate('1 + 5;'); expect(result).toBe(6); }); it('should accept a string with comments', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate('2 + 5;\n// do some math!'); expect(result).toBe(7); }); it('should accept element handle as an argument', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
42
'); const element = (await page.$('section'))!; @@ -397,7 +390,7 @@ describe('Evaluation specs', function () { expect(text).toBe('42'); }); it('should throw if underlying element was disposed', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
39
'); const element = (await page.$('section'))!; @@ -414,7 +407,7 @@ describe('Evaluation specs', function () { expect(error.message).toContain('JSHandle is disposed'); }); it('should throw if elementHandles are from other frames', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await attachFrame(page, 'frame1', server.EMPTY_PAGE); const bodyHandle = await page.frames()[1]!.$('body'); @@ -432,7 +425,7 @@ describe('Evaluation specs', function () { ); }); it('should simulate a user gesture', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const result = await page.evaluate(() => { document.body.appendChild(document.createTextNode('test')); @@ -442,7 +435,7 @@ describe('Evaluation specs', function () { expect(result).toBe(true); }); it('should throw a nice error after a navigation', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const executionContext = await page.mainFrame().executionContext(); @@ -462,7 +455,7 @@ describe('Evaluation specs', function () { expect((error as Error).message).toContain('navigation'); }); it('should not throw an error when evaluation does a navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/one-style.html'); const result = await page.evaluate(() => { @@ -473,7 +466,7 @@ describe('Evaluation specs', function () { }); it('should transfer 100Mb of data from page to node.js', async function () { this.timeout(25_000); - const {page} = getTestState(); + const {page} = await getTestState(); const a = await page.evaluate(() => { return Array(100 * 1024 * 1024 + 1).join('a'); @@ -481,7 +474,7 @@ describe('Evaluation specs', function () { expect(a.length).toBe(100 * 1024 * 1024); }); it('should throw error with detailed information on exception inside promise', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page @@ -499,7 +492,7 @@ describe('Evaluation specs', function () { describe('Page.evaluateOnNewDocument', function () { it('should evaluate before anything else on the page', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.evaluateOnNewDocument(function () { (globalThis as any).injected = 123; @@ -512,7 +505,7 @@ describe('Evaluation specs', function () { ).toBe(123); }); it('should work with CSP', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setCSP('/empty.html', 'script-src ' + server.PREFIX); await page.evaluateOnNewDocument(function () { @@ -539,7 +532,7 @@ describe('Evaluation specs', function () { describe('Page.removeScriptToEvaluateOnNewDocument', function () { it('should remove new document script', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const {identifier} = await page.evaluateOnNewDocument(function () { (globalThis as any).injected = 123; @@ -563,7 +556,7 @@ describe('Evaluation specs', function () { describe('Frame.evaluate', function () { it('should have different execution contexts', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await attachFrame(page, 'frame1', server.EMPTY_PAGE); @@ -586,7 +579,7 @@ describe('Evaluation specs', function () { ).toBe('bar'); }); it('should have correct execution contexts', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/frames/one-frame.html'); expect(page.frames()).toHaveLength(2); @@ -602,7 +595,7 @@ describe('Evaluation specs', function () { ).toBe(`Hi, I'm frame`); }); it('should execute after cross-site navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const mainFrame = page.mainFrame(); diff --git a/test/src/fixtures.spec.ts b/test/src/fixtures.spec.ts index 1547e13016b..991194e69fd 100644 --- a/test/src/fixtures.spec.ts +++ b/test/src/fixtures.spec.ts @@ -25,7 +25,8 @@ import {waitEvent} from './utils.js'; describe('Fixtures', function () { it('dumpio option should work with pipe option', async () => { - const {defaultBrowserOptions, puppeteerPath, headless} = getTestState(); + const {defaultBrowserOptions, puppeteerPath, headless} = + await getTestState(); if (headless === 'new') { // This test only works in the old headless mode. return; @@ -52,7 +53,7 @@ describe('Fixtures', function () { expect(dumpioData).toContain('message from dumpio'); }); it('should dump browser process stderr', async () => { - const {defaultBrowserOptions, puppeteerPath} = getTestState(); + const {defaultBrowserOptions, puppeteerPath} = await getTestState(); let dumpioData = ''; const {spawn} = await import('child_process'); @@ -71,7 +72,8 @@ describe('Fixtures', function () { expect(dumpioData).toContain('DevTools listening on ws://'); }); it('should close the browser when the node process closes', async () => { - const {defaultBrowserOptions, puppeteerPath, puppeteer} = getTestState(); + const {defaultBrowserOptions, puppeteerPath, puppeteer} = + await getTestState(); const {spawn, execSync} = await import('child_process'); const options = Object.assign({}, defaultBrowserOptions, { diff --git a/test/src/frame.spec.ts b/test/src/frame.spec.ts index 29b3cc1f2f0..85bcd049282 100644 --- a/test/src/frame.spec.ts +++ b/test/src/frame.spec.ts @@ -18,11 +18,7 @@ import expect from 'expect'; import {Frame} from 'puppeteer-core/internal/api/Frame.js'; import {CDPSession} from 'puppeteer-core/internal/common/Connection.js'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; import { attachFrame, detachFrame, @@ -32,12 +28,9 @@ import { } from './utils.js'; describe('Frame specs', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - describe('Frame.executionContext', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await attachFrame(page, 'frame1', server.EMPTY_PAGE); @@ -74,7 +67,7 @@ describe('Frame specs', function () { describe('Frame.evaluateHandle', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const mainFrame = page.mainFrame(); @@ -87,7 +80,7 @@ describe('Frame specs', function () { describe('Frame.evaluate', function () { it('should throw for detached frames', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const frame1 = (await attachFrame(page, 'frame1', server.EMPTY_PAGE))!; await detachFrame(page, 'frame1'); @@ -105,7 +98,7 @@ describe('Frame specs', function () { }); it('allows readonly array to be an argument', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const mainFrame = page.mainFrame(); @@ -120,7 +113,7 @@ describe('Frame specs', function () { describe('Frame.page', function () { it('should retrieve the page from a frame', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const mainFrame = page.mainFrame(); expect(mainFrame.page()).toEqual(page); @@ -129,7 +122,7 @@ describe('Frame specs', function () { describe('Frame Management', function () { it('should handle nested frames', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/frames/nested-frames.html'); expect(dumpFrames(page.mainFrame())).toEqual([ @@ -141,7 +134,7 @@ describe('Frame specs', function () { ]); }); it('should send events when frames are manipulated dynamically', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); // validate frameattached events @@ -172,7 +165,7 @@ describe('Frame specs', function () { expect(detachedFrames[0]!.isDetached()).toBe(true); }); it('should send "framenavigated" when navigating on anchor URLs', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await Promise.all([ @@ -182,7 +175,7 @@ describe('Frame specs', function () { expect(page.url()).toBe(server.EMPTY_PAGE + '#foo'); }); it('should persist mainFrame on cross-process navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const mainFrame = page.mainFrame(); @@ -190,7 +183,7 @@ describe('Frame specs', function () { expect(page.mainFrame() === mainFrame).toBeTruthy(); }); it('should not send attach/detach events for main frame', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let hasEvents = false; page.on('frameattached', () => { @@ -203,7 +196,7 @@ describe('Frame specs', function () { expect(hasEvents).toBe(false); }); it('should detach child frames on navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let attachedFrames: Frame[] = []; let detachedFrames: Frame[] = []; @@ -231,7 +224,7 @@ describe('Frame specs', function () { expect(navigatedFrames).toHaveLength(1); }); it('should support framesets', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let attachedFrames: Frame[] = []; let detachedFrames: Frame[] = []; @@ -259,7 +252,7 @@ describe('Frame specs', function () { expect(navigatedFrames).toHaveLength(1); }); it('should report frame from-inside shadow DOM', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/shadow.html'); await page.evaluate(async (url: string) => { @@ -274,7 +267,7 @@ describe('Frame specs', function () { expect(page.frames()[1]!.url()).toBe(server.EMPTY_PAGE); }); it('should report frame.name()', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await attachFrame(page, 'theFrameId', server.EMPTY_PAGE); await page.evaluate((url: string) => { @@ -291,7 +284,7 @@ describe('Frame specs', function () { expect(page.frames()[2]!.name()).toBe('theFrameName'); }); it('should report frame.parent()', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await attachFrame(page, 'frame1', server.EMPTY_PAGE); await attachFrame(page, 'frame2', server.EMPTY_PAGE); @@ -300,7 +293,7 @@ describe('Frame specs', function () { expect(page.frames()[2]!.parentFrame()).toBe(page.mainFrame()); }); it('should report different frame instance when frame re-attaches', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const frame1 = await attachFrame(page, 'frame1', server.EMPTY_PAGE); await page.evaluate(() => { @@ -318,7 +311,7 @@ describe('Frame specs', function () { expect(frame1).not.toBe(frame2); }); it('should support url fragment', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/frames/one-frame-url-fragment.html'); @@ -328,7 +321,7 @@ describe('Frame specs', function () { ); }); it('should support lazy frames', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 1000, height: 1000}); await page.goto(server.PREFIX + '/frames/lazy-frame.html'); @@ -343,7 +336,7 @@ describe('Frame specs', function () { describe('Frame.client', function () { it('should return the client instance', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); expect(page.mainFrame()._client()).toBeInstanceOf(CDPSession); }); }); diff --git a/test/src/headful.spec.ts b/test/src/headful.spec.ts index deb645703d4..06cb8fb34f4 100644 --- a/test/src/headful.spec.ts +++ b/test/src/headful.spec.ts @@ -58,8 +58,10 @@ describe('headful tests', function () { }; const browsers: Array<() => Promise> = []; - beforeEach(() => { - const {server, defaultBrowserOptions} = getTestState(); + beforeEach(async () => { + const {server, defaultBrowserOptions} = await getTestState({ + skipLaunch: true, + }); headfulOptions = Object.assign({}, defaultBrowserOptions, { headless: false, }); @@ -122,9 +124,7 @@ describe('headful tests', function () { expect(backgroundPageTarget).toBeTruthy(); }); it('service_worker target type should be available', async () => { - const {defaultBrowserOptions} = getTestState(); const browserWithExtension = await launchBrowser({ - ...defaultBrowserOptions, headless: false, args: [ `--disable-extensions-except=${serviceWorkerExtensionPath}`, @@ -162,7 +162,7 @@ describe('headful tests', function () { await browserWithExtension.close(); }); it('target.page() should return a DevTools page if custom isPageTarget is provided', async function () { - const {puppeteer} = getTestState(); + const {puppeteer} = await getTestState({skipLaunch: true}); const originalBrowser = await launchBrowser(devtoolsOptions); const browserWSEndpoint = originalBrowser.wsEndpoint(); @@ -195,7 +195,7 @@ describe('headful tests', function () { }); it('headless should be able to read cookies written by headful', async () => { /* Needs investigation into why but this fails consistently on Windows CI. */ - const {server} = getTestState(); + const {server} = await getTestState({skipLaunch: true}); const userDataDir = await mkdtemp(TMP_FOLDER); // Write a cookie in headful chrome @@ -227,7 +227,7 @@ describe('headful tests', function () { }); // TODO: Support OOOPIF. @see https://github.com/puppeteer/puppeteer/issues/2548 it.skip('OOPIF: should report google.com frame', async () => { - const {server} = getTestState(); + const {server} = await getTestState({skipLaunch: true}); // https://google.com is isolated by default in Chromium embedder. const browser = await launchBrowser(headfulOptions); @@ -255,8 +255,7 @@ describe('headful tests', function () { expect(urls).toEqual([server.EMPTY_PAGE, 'https://google.com/']); }); it('OOPIF: should expose events within OOPIFs', async () => { - const {server} = getTestState(); - + const {server} = await getTestState({skipLaunch: true}); const browser = await launchBrowser(forcedOopifOptions); const page = await browser.newPage(); @@ -315,10 +314,10 @@ describe('headful tests', function () { expect(requests).toContain(`http://oopifdomain:${server.PORT}/fetch`); }); it('should close browser with beforeunload page', async () => { - const {server} = getTestState(); - + const {server} = await getTestState({skipLaunch: true}); const browser = await launchBrowser(headfulOptions); const page = await browser.newPage(); + await page.goto(server.PREFIX + '/beforeunload.html'); // We have to interact with a page so that 'beforeunload' handlers // fire. @@ -378,7 +377,7 @@ describe('headful tests', function () { describe('Page.screenshot', function () { it('should run in parallel in multiple pages', async () => { - const {server} = getTestState(); + const {server} = await getTestState({skipLaunch: true}); const browser = await launchBrowser(headfulOptions); const context = await browser.createIncognitoBrowserContext(); diff --git a/test/src/idle_override.spec.ts b/test/src/idle_override.spec.ts index 1b2dbb894a0..0fb411c5ec3 100644 --- a/test/src/idle_override.spec.ts +++ b/test/src/idle_override.spec.ts @@ -16,33 +16,25 @@ import expect from 'expect'; import {ElementHandle} from 'puppeteer-core/internal/api/ElementHandle.js'; +import {Page} from 'puppeteer-core/internal/api/Page.js'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; describe('Emulate idle state', () => { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - - async function getIdleState() { - const {page} = getTestState(); - + async function getIdleState(page: Page) { const stateElement = (await page.$('#state')) as ElementHandle; return await page.evaluate(element => { return element.innerText; }, stateElement); } - async function verifyState(expectedState: string) { - const actualState = await getIdleState(); + async function verifyState(page: Page, expectedState: string) { + const actualState = await getIdleState(page); expect(actualState).toEqual(expectedState); } it('changing idle state emulation causes change of the IdleDetector state', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); await context.overridePermissions(server.PREFIX + '/idle-detector.html', [ 'idle-detection', ]); @@ -50,46 +42,46 @@ describe('Emulate idle state', () => { await page.goto(server.PREFIX + '/idle-detector.html'); // Store initial state, as soon as it is not guaranteed to be `active, unlocked`. - const initialState = await getIdleState(); + const initialState = await getIdleState(page); // Emulate Idle states and verify IdleDetector updates state accordingly. await page.emulateIdleState({ isUserActive: false, isScreenUnlocked: false, }); - await verifyState('Idle state: idle, locked.'); + await verifyState(page, 'Idle state: idle, locked.'); await page.emulateIdleState({ isUserActive: true, isScreenUnlocked: false, }); - await verifyState('Idle state: active, locked.'); + await verifyState(page, 'Idle state: active, locked.'); await page.emulateIdleState({ isUserActive: true, isScreenUnlocked: true, }); - await verifyState('Idle state: active, unlocked.'); + await verifyState(page, 'Idle state: active, unlocked.'); await page.emulateIdleState({ isUserActive: false, isScreenUnlocked: true, }); - await verifyState('Idle state: idle, unlocked.'); + await verifyState(page, 'Idle state: idle, unlocked.'); // Remove Idle emulation and verify IdleDetector is in initial state. await page.emulateIdleState(); - await verifyState(initialState); + await verifyState(page, initialState); // Emulate idle state again after removing emulation. await page.emulateIdleState({ isUserActive: false, isScreenUnlocked: false, }); - await verifyState('Idle state: idle, locked.'); + await verifyState(page, 'Idle state: idle, locked.'); // Remove emulation second time. await page.emulateIdleState(); - await verifyState(initialState); + await verifyState(page, initialState); }); }); diff --git a/test/src/ignorehttpserrors.spec.ts b/test/src/ignorehttpserrors.spec.ts index 0ca8f18a7db..c8116330a27 100644 --- a/test/src/ignorehttpserrors.spec.ts +++ b/test/src/ignorehttpserrors.spec.ts @@ -34,7 +34,7 @@ describe('ignoreHTTPSErrors', function () { let page!: Page; before(async () => { - const {defaultBrowserOptions, puppeteer} = getTestState(); + const {defaultBrowserOptions, puppeteer} = await getTestState(); const options = Object.assign( {ignoreHTTPSErrors: true}, defaultBrowserOptions @@ -58,7 +58,7 @@ describe('ignoreHTTPSErrors', function () { describe('Response.securityDetails', function () { it('should work', async () => { - const {httpsServer} = getTestState(); + const {httpsServer} = await getTestState(); const [serverRequest, response] = await Promise.all([ httpsServer.waitForRequest('/empty.html'), @@ -79,13 +79,13 @@ describe('ignoreHTTPSErrors', function () { ]); }); it('should be |null| for non-secure requests', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); const response = (await page.goto(server.EMPTY_PAGE))!; expect(response.securityDetails()).toBe(null); }); it('Network redirects should report SecurityDetails', async () => { - const {httpsServer} = getTestState(); + const {httpsServer} = await getTestState(); httpsServer.setRedirect('/plzredirect', '/empty.html'); const responses: HTTPResponse[] = []; @@ -107,7 +107,7 @@ describe('ignoreHTTPSErrors', function () { }); it('should work', async () => { - const {httpsServer} = getTestState(); + const {httpsServer} = await getTestState(); let error!: Error; const response = await page.goto(httpsServer.EMPTY_PAGE).catch(error_ => { @@ -117,7 +117,7 @@ describe('ignoreHTTPSErrors', function () { expect(response.ok()).toBe(true); }); it('should work with request interception', async () => { - const {httpsServer} = getTestState(); + const {httpsServer} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -127,7 +127,7 @@ describe('ignoreHTTPSErrors', function () { expect(response.status()).toBe(200); }); it('should work with mixed content', async () => { - const {server, httpsServer} = getTestState(); + const {server, httpsServer} = await getTestState(); httpsServer.setRoute('/mixedcontent.html', (_req, res) => { res.end(``); diff --git a/test/src/injected.spec.ts b/test/src/injected.spec.ts index 836ee479a19..6731501bbbe 100644 --- a/test/src/injected.spec.ts +++ b/test/src/injected.spec.ts @@ -18,18 +18,11 @@ import expect from 'expect'; import {PUPPETEER_WORLD} from 'puppeteer-core/internal/common/IsolatedWorlds.js'; import {LazyArg} from 'puppeteer-core/internal/common/LazyArg.js'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; describe('PuppeteerUtil tests', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const world = page.mainFrame().worlds[PUPPETEER_WORLD]; const value = await world.evaluate( @@ -45,7 +38,7 @@ describe('PuppeteerUtil tests', function () { describe('createFunction tests', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const world = page.mainFrame().worlds[PUPPETEER_WORLD]; const value = await world.evaluate( diff --git a/test/src/input.spec.ts b/test/src/input.spec.ts index 5519fca4c10..536b3cc3ecf 100644 --- a/test/src/input.spec.ts +++ b/test/src/input.spec.ts @@ -19,22 +19,15 @@ import path from 'path'; import expect from 'expect'; import {TimeoutError} from 'puppeteer'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; import {waitEvent} from './utils.js'; const FILE_TO_UPLOAD = path.join(__dirname, '/../assets/file-to-upload.txt'); describe('input tests', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - describe('input', function () { it('should upload the file', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/fileupload.html'); const filePath = path.relative(process.cwd(), FILE_TO_UPLOAD); @@ -81,7 +74,7 @@ describe('input tests', function () { describe('Page.waitForFileChooser', function () { it('should work when file input is attached to DOM', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(``); const [chooser] = await Promise.all([ @@ -91,7 +84,7 @@ describe('input tests', function () { expect(chooser).toBeTruthy(); }); it('should work when file input is not attached to DOM', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const [chooser] = await Promise.all([ page.waitForFileChooser(), @@ -104,7 +97,7 @@ describe('input tests', function () { expect(chooser).toBeTruthy(); }); it('should respect timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page.waitForFileChooser({timeout: 1}).catch(error_ => { @@ -113,7 +106,7 @@ describe('input tests', function () { expect(error).toBeInstanceOf(TimeoutError); }); it('should respect default timeout when there is no custom timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); page.setDefaultTimeout(1); let error!: Error; @@ -123,7 +116,7 @@ describe('input tests', function () { expect(error).toBeInstanceOf(TimeoutError); }); it('should prioritize exact timeout over default timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); page.setDefaultTimeout(0); let error!: Error; @@ -133,7 +126,7 @@ describe('input tests', function () { expect(error).toBeInstanceOf(TimeoutError); }); it('should work with no timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const [chooser] = await Promise.all([ page.waitForFileChooser({timeout: 0}), @@ -148,7 +141,7 @@ describe('input tests', function () { expect(chooser).toBeTruthy(); }); it('should return the same file chooser when there are many watchdogs simultaneously', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(``); const [fileChooser1, fileChooser2] = await Promise.all([ @@ -164,7 +157,7 @@ describe('input tests', function () { describe('FileChooser.accept', function () { it('should accept single file', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( `` @@ -189,7 +182,7 @@ describe('input tests', function () { ).toBe('file-to-upload.txt'); }); it('should be able to read selected file', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(``); page.waitForFileChooser().then(chooser => { @@ -214,7 +207,7 @@ describe('input tests', function () { ).toBe('contents of the file'); }); it('should be able to reset selected files with empty file list', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(``); page.waitForFileChooser().then(chooser => { @@ -245,7 +238,7 @@ describe('input tests', function () { ).toBe(0); }); it('should not accept multiple files for single-file input', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(``); const [chooser] = await Promise.all([ @@ -267,7 +260,7 @@ describe('input tests', function () { expect(error).not.toBe(null); }); it('should succeed even for non-existent files', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(``); const [chooser] = await Promise.all([ @@ -281,7 +274,7 @@ describe('input tests', function () { expect(error).toBeUndefined(); }); it('should error on read of non-existent files', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(``); page.waitForFileChooser().then(chooser => { @@ -306,7 +299,7 @@ describe('input tests', function () { ).toBeFalsy(); }); it('should fail when accepting file chooser twice', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(``); const [fileChooser] = await Promise.all([ @@ -328,7 +321,7 @@ describe('input tests', function () { describe('FileChooser.cancel', function () { it('should cancel dialog', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); // Consider file chooser canceled if we can summon another one. // There's no reliable way in WebPlatform to see that FileChooser was @@ -350,7 +343,7 @@ describe('input tests', function () { ]); }); it('should fail when canceling file chooser twice', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(``); const [fileChooser] = await Promise.all([ @@ -376,7 +369,7 @@ describe('input tests', function () { describe('FileChooser.isMultiple', () => { it('should work for single file pick', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(``); const [chooser] = await Promise.all([ @@ -386,7 +379,7 @@ describe('input tests', function () { expect(chooser.isMultiple()).toBe(false); }); it('should work for "multiple"', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(``); const [chooser] = await Promise.all([ @@ -396,7 +389,7 @@ describe('input tests', function () { expect(chooser.isMultiple()).toBe(true); }); it('should work for "webkitdirectory"', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(``); const [chooser] = await Promise.all([ diff --git a/test/src/jshandle.spec.ts b/test/src/jshandle.spec.ts index 30ef17bed02..2bf26b49299 100644 --- a/test/src/jshandle.spec.ts +++ b/test/src/jshandle.spec.ts @@ -16,19 +16,12 @@ import expect from 'expect'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; describe('JSHandle', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - describe('Page.evaluateHandle', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const windowHandle = await page.evaluateHandle(() => { return window; @@ -36,7 +29,7 @@ describe('JSHandle', function () { expect(windowHandle).toBeTruthy(); }); it('should return the RemoteObject', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const windowHandle = await page.evaluateHandle(() => { return window; @@ -44,7 +37,7 @@ describe('JSHandle', function () { expect(windowHandle.remoteObject()).toBeTruthy(); }); it('should accept object handle as an argument', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const navigatorHandle = await page.evaluateHandle(() => { return navigator; @@ -55,7 +48,7 @@ describe('JSHandle', function () { expect(text).toContain('Mozilla'); }); it('should accept object handle to primitive types', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const aHandle = await page.evaluateHandle(() => { return 5; @@ -66,7 +59,7 @@ describe('JSHandle', function () { expect(isFive).toBeTruthy(); }); it('should warn about recursive objects', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const test: {obj?: unknown} = {}; test.obj = test; @@ -81,7 +74,7 @@ describe('JSHandle', function () { expect(error.message).toContain('Recursive objects are not allowed.'); }); it('should accept object handle to unserializable value', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const aHandle = await page.evaluateHandle(() => { return Infinity; @@ -93,7 +86,7 @@ describe('JSHandle', function () { ).toBe(true); }); it('should use the same JS wrappers', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const aHandle = await page.evaluateHandle(() => { (globalThis as any).FOO = 123; @@ -109,7 +102,7 @@ describe('JSHandle', function () { describe('JSHandle.getProperty', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const aHandle = await page.evaluateHandle(() => { return { @@ -125,7 +118,7 @@ describe('JSHandle', function () { describe('JSHandle.jsonValue', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const aHandle = await page.evaluateHandle(() => { return {foo: 'bar'}; @@ -135,7 +128,7 @@ describe('JSHandle', function () { }); it('works with jsonValues that are not objects', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const aHandle = await page.evaluateHandle(() => { return ['a', 'b']; @@ -145,7 +138,7 @@ describe('JSHandle', function () { }); it('works with jsonValues that are primitives', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const aHandle = await page.evaluateHandle(() => { return 'foo'; @@ -159,7 +152,7 @@ describe('JSHandle', function () { }); it('should work with dates', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const dateHandle = await page.evaluateHandle(() => { return new Date('2017-09-26T00:00:00.000Z'); @@ -168,7 +161,7 @@ describe('JSHandle', function () { expect(date.toISOString()).toEqual('2017-09-26T00:00:00.000Z'); }); it('should throw for circular objects', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const handle = await page.evaluateHandle(() => { const t: {t?: unknown; g: number} = {g: 1}; @@ -185,7 +178,7 @@ describe('JSHandle', function () { describe('JSHandle.getProperties', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const aHandle = await page.evaluateHandle(() => { return { @@ -198,7 +191,7 @@ describe('JSHandle', function () { expect(await foo.jsonValue()).toBe('bar'); }); it('should return even non-own properties', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const aHandle = await page.evaluateHandle(() => { class A { @@ -224,7 +217,7 @@ describe('JSHandle', function () { describe('JSHandle.asElement', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const aHandle = await page.evaluateHandle(() => { return document.body; @@ -233,7 +226,7 @@ describe('JSHandle', function () { expect(element).toBeTruthy(); }); it('should return null for non-elements', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const aHandle = await page.evaluateHandle(() => { return 2; @@ -242,7 +235,7 @@ describe('JSHandle', function () { expect(element).toBeFalsy(); }); it('should return ElementHandle for TextNodes', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
ee!
'); const aHandle = await page.evaluateHandle(() => { @@ -260,7 +253,7 @@ describe('JSHandle', function () { describe('JSHandle.toString', function () { it('should work for primitives', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const numberHandle = await page.evaluateHandle(() => { return 2; @@ -272,7 +265,7 @@ describe('JSHandle', function () { expect(stringHandle.toString()).toBe('JSHandle:a'); }); it('should work for complicated objects', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const aHandle = await page.evaluateHandle(() => { return window; @@ -283,7 +276,7 @@ describe('JSHandle', function () { ]); }); it('should work with different subtypes', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); expect((await page.evaluateHandle('(function(){})')).toString()).toBe( 'JSHandle@function' diff --git a/test/src/keyboard.spec.ts b/test/src/keyboard.spec.ts index 1ae6db22ddc..6a4ddfe2c22 100644 --- a/test/src/keyboard.spec.ts +++ b/test/src/keyboard.spec.ts @@ -19,19 +19,12 @@ import os from 'os'; import expect from 'expect'; import {KeyInput} from 'puppeteer-core/internal/common/USKeyboardLayout.js'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; import {attachFrame} from './utils.js'; describe('Keyboard', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - it('should type into a textarea', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.evaluate(() => { const textarea = document.createElement('textarea'); @@ -47,7 +40,7 @@ describe('Keyboard', function () { ).toBe(text); }); it('should press the metaKey', async () => { - const {page, isFirefox} = getTestState(); + const {page, isFirefox} = await getTestState(); await page.evaluate(() => { (window as any).keyPromise = new Promise(resolve => { @@ -62,7 +55,7 @@ describe('Keyboard', function () { ); }); it('should move with the arrow keys', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/textarea.html'); await page.type('textarea', 'Hello World!'); @@ -94,7 +87,7 @@ describe('Keyboard', function () { }); // @see https://github.com/puppeteer/puppeteer/issues/1313 it('should trigger commands of keyboard shortcuts', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const cmdKey = os.platform() !== 'darwin' ? 'Meta' : 'Control'; await page.goto(server.PREFIX + '/input/textarea.html'); @@ -123,7 +116,7 @@ describe('Keyboard', function () { ).toBe('hellohello'); }); it('should send a character with ElementHandle.press', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/textarea.html'); const textarea = (await page.$('textarea'))!; @@ -152,7 +145,7 @@ describe('Keyboard', function () { ).toBe('a'); }); it('ElementHandle.press should support |text| option', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/textarea.html'); const textarea = (await page.$('textarea'))!; @@ -164,7 +157,7 @@ describe('Keyboard', function () { ).toBe('ё'); }); it('should send a character with sendCharacter', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/textarea.html'); await page.focus('textarea'); @@ -191,7 +184,7 @@ describe('Keyboard', function () { ).toBe('嗨a'); }); it('should report shiftKey', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/keyboard.html'); const keyboard = page.keyboard; @@ -262,7 +255,7 @@ describe('Keyboard', function () { } }); it('should report multiple modifiers', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/keyboard.html'); const keyboard = page.keyboard; @@ -304,7 +297,7 @@ describe('Keyboard', function () { ).toBe('Keyup: Alt AltLeft 18 []'); }); it('should send proper codes while typing', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/keyboard.html'); await page.keyboard.type('!'); @@ -333,7 +326,7 @@ describe('Keyboard', function () { ); }); it('should send proper codes while typing with shift', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/keyboard.html'); const keyboard = page.keyboard; @@ -354,7 +347,7 @@ describe('Keyboard', function () { await keyboard.up('Shift'); }); it('should not type canceled events', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/textarea.html'); await page.focus('textarea'); @@ -382,7 +375,7 @@ describe('Keyboard', function () { ).toBe('He Wrd!'); }); it('should specify repeat property', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/textarea.html'); await page.focus('textarea'); @@ -430,7 +423,7 @@ describe('Keyboard', function () { ).toBe(false); }); it('should type all kinds of characters', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/textarea.html'); await page.focus('textarea'); @@ -439,7 +432,7 @@ describe('Keyboard', function () { expect(await page.evaluate('result')).toBe(text); }); it('should specify location', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/textarea.html'); await page.evaluate(() => { @@ -466,7 +459,7 @@ describe('Keyboard', function () { expect(await page.evaluate('keyLocation')).toBe(3); }); it('should throw on unknown keys', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error = await page.keyboard // @ts-expect-error bad input @@ -489,7 +482,7 @@ describe('Keyboard', function () { expect(error && error.message).toBe('Unknown key: "😊"'); }); it('should type emoji', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/textarea.html'); await page.type('textarea', '👹 Tokyo street Japan 🇯🇵'); @@ -500,7 +493,7 @@ describe('Keyboard', function () { ).toBe('👹 Tokyo street Japan 🇯🇵'); }); it('should type emoji into an iframe', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await attachFrame( @@ -518,7 +511,7 @@ describe('Keyboard', function () { ).toBe('👹 Tokyo street Japan 🇯🇵'); }); it('should press the meta key', async () => { - const {page, isFirefox} = getTestState(); + const {page, isFirefox} = await getTestState(); await page.evaluate(() => { (globalThis as any).result = null; diff --git a/test/src/launcher.spec.ts b/test/src/launcher.spec.ts index 2acb7284c2c..c2bdb4ae466 100644 --- a/test/src/launcher.spec.ts +++ b/test/src/launcher.spec.ts @@ -26,30 +26,20 @@ import {Page} from 'puppeteer-core/internal/api/Page.js'; import {rmSync} from 'puppeteer-core/internal/node/util/fs.js'; import sinon from 'sinon'; -import { - getTestState, - itOnlyRegularInstall, - launch, - setupTestBrowserHooks, -} from './mocha-utils.js'; +import {getTestState, itOnlyRegularInstall, launch} from './mocha-utils.js'; import {dumpFrames, waitEvent} from './utils.js'; const TMP_FOLDER = path.join(os.tmpdir(), 'pptr_tmp_folder-'); const FIREFOX_TIMEOUT = 30_000; describe('Launcher specs', function () { - setupTestBrowserHooks(); - - if (getTestState().isFirefox) { - this.timeout(FIREFOX_TIMEOUT); - } + this.timeout(FIREFOX_TIMEOUT); describe('Puppeteer', function () { describe('Browser.disconnect', function () { it('should reject navigation when browser closes', async () => { - const {server, puppeteer, defaultBrowserOptions} = getTestState(); + const {browser, close, puppeteer, server} = await launch({}); server.setRoute('/one-style.css', () => {}); - const {browser, close} = await launch(defaultBrowserOptions); try { const remote = await puppeteer.connect({ browserWSEndpoint: browser.wsEndpoint(), @@ -74,9 +64,8 @@ describe('Launcher specs', function () { } }); it('should reject waitForSelector when browser closes', async () => { - const {server, puppeteer, defaultBrowserOptions} = getTestState(); + const {browser, close, server, puppeteer} = await launch({}); server.setRoute('/empty.html', () => {}); - const {browser, close} = await launch(defaultBrowserOptions); try { const remote = await puppeteer.connect({ browserWSEndpoint: browser.wsEndpoint(), @@ -97,8 +86,7 @@ describe('Launcher specs', function () { }); describe('Browser.close', function () { it('should terminate network waiters', async () => { - const {server, puppeteer, defaultBrowserOptions} = getTestState(); - const {browser, close} = await launch(defaultBrowserOptions); + const {browser, close, server, puppeteer} = await launch({}); try { const remote = await puppeteer.connect({ browserWSEndpoint: browser.wsEndpoint(), @@ -125,13 +113,11 @@ describe('Launcher specs', function () { }); describe('Puppeteer.launch', function () { it('can launch and close the browser', async () => { - const {defaultBrowserOptions} = getTestState(); - const {close} = await launch(defaultBrowserOptions); + const {close} = await launch({}); await close(); }); it('should reject all promises when browser is closed', async () => { - const {defaultBrowserOptions} = getTestState(); - const {page, close} = await launch(defaultBrowserOptions); + const {page, close} = await launch({}); let error!: Error; const neverResolves = page .evaluate(() => { @@ -145,23 +131,17 @@ describe('Launcher specs', function () { expect(error.message).toContain('Protocol error'); }); it('should reject if executable path is invalid', async () => { - const {defaultBrowserOptions} = getTestState(); - let waitError!: Error; - const options = Object.assign({}, defaultBrowserOptions, { + await launch({ executablePath: 'random-invalid-path', - }); - await launch(options).catch(error => { + }).catch(error => { return (waitError = error); }); expect(waitError.message).toContain('Failed to launch'); }); it('userDataDir option', async () => { - const {defaultBrowserOptions} = getTestState(); - const userDataDir = await mkdtemp(TMP_FOLDER); - const options = Object.assign({userDataDir}, defaultBrowserOptions); - const {context, close} = await launch(options); + const {context, close} = await launch({userDataDir}); // Open a page to make sure its functional. try { await context.newPage(); @@ -177,7 +157,7 @@ describe('Launcher specs', function () { } catch {} }); it('tmp profile should be cleaned up', async () => { - const {defaultBrowserOptions, puppeteer} = getTestState(); + const {puppeteer} = await getTestState({skipLaunch: true}); // Set a custom test tmp dir so that we can validate that // the profile dir is created and then cleaned up. @@ -189,7 +169,7 @@ describe('Launcher specs', function () { // Path should be empty before starting the browser. expect(fs.readdirSync(testTmpDir)).toHaveLength(0); - const {context, close} = await launch(defaultBrowserOptions); + const {context, close} = await launch({}); try { // One profile folder should have been created at this moment. const profiles = fs.readdirSync(testTmpDir); @@ -211,16 +191,13 @@ describe('Launcher specs', function () { puppeteer.configuration.temporaryDirectory = oldTmpDir; }); it('userDataDir option restores preferences', async () => { - const {defaultBrowserOptions} = getTestState(); - const userDataDir = await mkdtemp(TMP_FOLDER); const prefsJSPath = path.join(userDataDir, 'prefs.js'); const prefsJSContent = 'user_pref("browser.warnOnQuit", true)'; await writeFile(prefsJSPath, prefsJSContent); - const options = Object.assign({userDataDir}, defaultBrowserOptions); - const {context, close} = await launch(options); + const {context, close} = await launch({userDataDir}); try { // Open a page to make sure its functional. await context.newPage(); @@ -239,21 +216,18 @@ describe('Launcher specs', function () { } catch {} }); it('userDataDir argument', async () => { - const {isChrome, defaultBrowserOptions} = getTestState(); + const {isChrome, defaultBrowserOptions: options} = await getTestState({ + skipLaunch: true, + }); const userDataDir = await mkdtemp(TMP_FOLDER); - const options = Object.assign({}, defaultBrowserOptions); if (isChrome) { options.args = [ - ...(defaultBrowserOptions.args || []), + ...(options.args || []), `--user-data-dir=${userDataDir}`, ]; } else { - options.args = [ - ...(defaultBrowserOptions.args || []), - '-profile', - userDataDir, - ]; + options.args = [...(options.args || []), '-profile', userDataDir]; } const {close} = await launch(options); expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0); @@ -265,7 +239,9 @@ describe('Launcher specs', function () { } catch {} }); it('userDataDir argument with non-existent dir', async () => { - const {isChrome, defaultBrowserOptions} = getTestState(); + const {isChrome, defaultBrowserOptions} = await getTestState({ + skipLaunch: true, + }); const userDataDir = await mkdtemp(TMP_FOLDER); rmSync(userDataDir); @@ -292,10 +268,8 @@ describe('Launcher specs', function () { } catch {} }); it('userDataDir option should restore state', async () => { - const {server, defaultBrowserOptions} = getTestState(); const userDataDir = await mkdtemp(TMP_FOLDER); - const options = Object.assign({userDataDir}, defaultBrowserOptions); - const {browser, close} = await launch(options); + const {server, browser, close} = await launch({userDataDir}); try { const page = await browser.newPage(); await page.goto(server.EMPTY_PAGE); @@ -306,7 +280,7 @@ describe('Launcher specs', function () { await close(); } - const {browser: browser2, close: close2} = await launch(options); + const {browser: browser2, close: close2} = await launch({userDataDir}); try { const page2 = await browser2.newPage(); @@ -326,11 +300,8 @@ describe('Launcher specs', function () { } catch {} }); it('userDataDir option should restore cookies', async () => { - const {server, defaultBrowserOptions} = getTestState(); - const userDataDir = await mkdtemp(TMP_FOLDER); - const options = Object.assign({userDataDir}, defaultBrowserOptions); - const {browser, close} = await launch(options); + const {server, browser, close} = await launch({userDataDir}); try { const page = await browser.newPage(); await page.goto(server.EMPTY_PAGE); @@ -342,7 +313,7 @@ describe('Launcher specs', function () { await close(); } - const {browser: browser2, close: close2} = await launch(options); + const {browser: browser2, close: close2} = await launch({userDataDir}); try { const page2 = await browser2.newPage(); await page2.goto(server.EMPTY_PAGE); @@ -361,7 +332,7 @@ describe('Launcher specs', function () { } catch {} }); it('should return the default arguments', async () => { - const {isChrome, isFirefox, puppeteer} = getTestState(); + const {isChrome, isFirefox, puppeteer} = await getTestState(); if (isChrome) { expect(puppeteer.defaultArgs()).toContain('--no-first-run'); @@ -401,7 +372,7 @@ describe('Launcher specs', function () { } }); it('should report the correct product', async () => { - const {isChrome, isFirefox, puppeteer} = getTestState(); + const {isChrome, isFirefox, puppeteer} = await getTestState(); if (isChrome) { expect(puppeteer.product).toBe('chrome'); } else if (isFirefox) { @@ -409,10 +380,9 @@ describe('Launcher specs', function () { } }); it('should work with no default arguments', async () => { - const {defaultBrowserOptions} = getTestState(); - const options = Object.assign({}, defaultBrowserOptions); - options.ignoreDefaultArgs = true; - const {context, close} = await launch(options); + const {context, close} = await launch({ + ignoreDefaultArgs: true, + }); try { const page = await context.newPage(); expect(await page.evaluate('11 * 11')).toBe(121); @@ -422,7 +392,9 @@ describe('Launcher specs', function () { } }); it('should filter out ignored default arguments in Chrome', async () => { - const {defaultBrowserOptions, puppeteer} = getTestState(); + const {defaultBrowserOptions, puppeteer} = await getTestState({ + skipLaunch: true, + }); // Make sure we launch with `--enable-automation` by default. const defaultArgs = puppeteer.defaultArgs(); const {browser, close} = await launch( @@ -444,7 +416,9 @@ describe('Launcher specs', function () { } }); it('should filter out ignored default argument in Firefox', async () => { - const {defaultBrowserOptions, puppeteer} = getTestState(); + const {defaultBrowserOptions, puppeteer} = await getTestState({ + skipLaunch: true, + }); const defaultArgs = puppeteer.defaultArgs(); const {browser, close} = await launch( @@ -465,10 +439,12 @@ describe('Launcher specs', function () { } }); it('should have default URL when launching browser', async function () { - const {defaultBrowserOptions} = getTestState(); - const {browser, close} = await launch(defaultBrowserOptions, { - createContext: false, - }); + const {browser, close} = await launch( + {}, + { + createContext: false, + } + ); try { const pages = (await browser.pages()).map(page => { return page.url(); @@ -479,11 +455,15 @@ describe('Launcher specs', function () { } }); it('should have custom URL when launching browser', async () => { - const {server, defaultBrowserOptions} = getTestState(); + const {server, defaultBrowserOptions} = await getTestState({ + skipLaunch: true, + }); const options = Object.assign({}, defaultBrowserOptions); options.args = [server.EMPTY_PAGE].concat(options.args || []); - const {browser, close} = await launch(options, {createContext: false}); + const {browser, close} = await launch(options, { + createContext: false, + }); try { const pages = await browser.pages(); expect(pages).toHaveLength(1); @@ -497,7 +477,7 @@ describe('Launcher specs', function () { } }); it('should pass the timeout parameter to browser.waitForTarget', async () => { - const {defaultBrowserOptions} = getTestState(); + const {defaultBrowserOptions} = await getTestState(); const options = Object.assign({}, defaultBrowserOptions, { timeout: 1, }); @@ -508,22 +488,18 @@ describe('Launcher specs', function () { expect(error).toBeInstanceOf(TimeoutError); }); it('should work with timeout = 0', async () => { - const {defaultBrowserOptions} = getTestState(); - const options = Object.assign({}, defaultBrowserOptions, { + const {close} = await launch({ timeout: 0, }); - const {close} = await launch(options); await close(); }); it('should set the default viewport', async () => { - const {defaultBrowserOptions} = getTestState(); - const options = Object.assign({}, defaultBrowserOptions, { + const {context, close} = await launch({ defaultViewport: { width: 456, height: 789, }, }); - const {context, close} = await launch(options); try { const page = await context.newPage(); @@ -534,11 +510,9 @@ describe('Launcher specs', function () { } }); it('should disable the default viewport', async () => { - const {defaultBrowserOptions} = getTestState(); - const options = Object.assign({}, defaultBrowserOptions, { + const {context, close} = await launch({ defaultViewport: null, }); - const {context, close} = await launch(options); try { const page = await context.newPage(); expect(page.viewport()).toBe(null); @@ -547,12 +521,9 @@ describe('Launcher specs', function () { } }); it('should take fullPage screenshots when defaultViewport is null', async () => { - const {server, defaultBrowserOptions} = getTestState(); - - const options = Object.assign({}, defaultBrowserOptions, { + const {server, context, close} = await launch({ defaultViewport: null, }); - const {context, close} = await launch(options); try { const page = await context.newPage(); await page.goto(server.PREFIX + '/grid.html'); @@ -565,13 +536,10 @@ describe('Launcher specs', function () { } }); it('should set the debugging port', async () => { - const {defaultBrowserOptions} = getTestState(); - - const options = Object.assign({}, defaultBrowserOptions, { + const {browser, close} = await launch({ defaultViewport: null, debuggingPort: 9999, }); - const {browser, close} = await launch(options); try { const url = new URL(browser.wsEndpoint()); expect(url.port).toBe('9999'); @@ -580,7 +548,7 @@ describe('Launcher specs', function () { } }); it('should not allow setting debuggingPort and pipe', async () => { - const {defaultBrowserOptions} = getTestState(); + const {defaultBrowserOptions} = await getTestState(); const options = Object.assign({}, defaultBrowserOptions, { defaultViewport: null, @@ -595,7 +563,9 @@ describe('Launcher specs', function () { expect(error.message).toContain('either pipe or debugging port'); }); it('should launch Chrome properly with --no-startup-window and waitForInitialPage=false', async () => { - const {defaultBrowserOptions} = getTestState(); + const {defaultBrowserOptions} = await getTestState({ + skipLaunch: true, + }); const options = { waitForInitialPage: false, // This is needed to prevent Puppeteer from adding an initial blank page. @@ -639,8 +609,7 @@ describe('Launcher specs', function () { describe('Puppeteer.connect', function () { it('should be able to connect multiple times to the same browser', async () => { - const {puppeteer, defaultBrowserOptions} = getTestState(); - const {browser, close} = await launch(defaultBrowserOptions); + const {puppeteer, browser, close} = await launch({}); try { const otherBrowser = await puppeteer.connect({ browserWSEndpoint: browser.wsEndpoint(), @@ -664,8 +633,7 @@ describe('Launcher specs', function () { } }); it('should be able to close remote browser', async () => { - const {defaultBrowserOptions, puppeteer} = getTestState(); - const {browser, close} = await launch(defaultBrowserOptions); + const {puppeteer, browser, close} = await launch({}); try { const remoteBrowser = await puppeteer.connect({ browserWSEndpoint: browser.wsEndpoint(), @@ -679,8 +647,7 @@ describe('Launcher specs', function () { } }); it('should be able to connect to a browser with no page targets', async () => { - const {defaultBrowserOptions, puppeteer} = getTestState(); - const {browser, close} = await launch(defaultBrowserOptions); + const {puppeteer, browser, close} = await launch({}); try { const pages = await browser.pages(); @@ -701,9 +668,8 @@ describe('Launcher specs', function () { } }); it('should support ignoreHTTPSErrors option', async () => { - const {puppeteer, defaultBrowserOptions} = getTestState(); - const {httpsServer, browser, close} = await launch( - defaultBrowserOptions, + const {puppeteer, httpsServer, browser, close} = await launch( + {}, { createContext: false, } @@ -738,10 +704,8 @@ describe('Launcher specs', function () { }); it('should support targetFilter option in puppeteer.launch', async () => { - const {defaultBrowserOptions} = getTestState(); const {browser, close} = await launch( { - ...defaultBrowserOptions, targetFilter: target => { return target.type !== 'page'; }, @@ -764,10 +728,12 @@ describe('Launcher specs', function () { // @see https://github.com/puppeteer/puppeteer/issues/4197 it('should support targetFilter option', async () => { - const {puppeteer, defaultBrowserOptions} = getTestState(); - const {server, browser, close} = await launch(defaultBrowserOptions, { - createContext: false, - }); + const {puppeteer, server, browser, close} = await launch( + {}, + { + createContext: false, + } + ); try { const browserWSEndpoint = browser.wsEndpoint(); const page1 = await browser.newPage(); @@ -802,8 +768,7 @@ describe('Launcher specs', function () { } }); it('should be able to reconnect to a disconnected browser', async () => { - const {puppeteer, defaultBrowserOptions} = getTestState(); - const {server, browser, close} = await launch(defaultBrowserOptions); + const {puppeteer, server, browser, close} = await launch({}); try { const browserWSEndpoint = browser.wsEndpoint(); const page = await browser.newPage(); @@ -834,10 +799,7 @@ describe('Launcher specs', function () { }); // @see https://github.com/puppeteer/puppeteer/issues/4197#issuecomment-481793410 it('should be able to connect to the same page simultaneously', async () => { - const {puppeteer, defaultBrowserOptions} = getTestState(); - const {browser: browserOne, close} = await launch( - defaultBrowserOptions - ); + const {puppeteer, browser: browserOne, close} = await launch({}); try { const browserTwo = await puppeteer.connect({ @@ -866,12 +828,12 @@ describe('Launcher specs', function () { } }); it('should be able to reconnect', async () => { - const {puppeteer, defaultBrowserOptions} = getTestState(); const { + puppeteer, server, browser: browserOne, close, - } = await launch(defaultBrowserOptions); + } = await launch({}); try { const browserWSEndpoint = browserOne.wsEndpoint(); const pageOne = await browserOne.newPage(); @@ -898,14 +860,14 @@ describe('Launcher specs', function () { }); describe('Puppeteer.executablePath', function () { itOnlyRegularInstall('should work', async () => { - const {puppeteer} = getTestState(); + const {puppeteer} = await getTestState(); const executablePath = puppeteer.executablePath(); expect(fs.existsSync(executablePath)).toBe(true); expect(fs.realpathSync(executablePath)).toBe(executablePath); }); - it('returns executablePath for channel', () => { - const {puppeteer} = getTestState(); + it('returns executablePath for channel', async () => { + const {puppeteer} = await getTestState(); const executablePath = puppeteer.executablePath('chrome'); expect(executablePath).toBeTruthy(); @@ -913,8 +875,8 @@ describe('Launcher specs', function () { describe('when executable path is configured', () => { const sandbox = sinon.createSandbox(); - beforeEach(() => { - const {puppeteer} = getTestState(); + beforeEach(async () => { + const {puppeteer} = await getTestState(); sandbox .stub(puppeteer.configuration, 'executablePath') .value('SOME_CUSTOM_EXECUTABLE'); @@ -925,7 +887,7 @@ describe('Launcher specs', function () { }); it('its value is used', async () => { - const {puppeteer} = getTestState(); + const {puppeteer} = await getTestState(); try { puppeteer.executablePath(); } catch (error) { @@ -940,8 +902,7 @@ describe('Launcher specs', function () { describe('Browser target events', function () { it('should work', async () => { - const {defaultBrowserOptions} = getTestState(); - const {browser, server, close} = await launch(defaultBrowserOptions); + const {browser, server, close} = await launch({}); try { const events: string[] = []; @@ -966,8 +927,7 @@ describe('Launcher specs', function () { describe('Browser.Events.disconnected', function () { it('should be emitted when: browser gets closed, disconnected or underlying websocket gets closed', async () => { - const {puppeteer, defaultBrowserOptions} = getTestState(); - const {browser, close} = await launch(defaultBrowserOptions); + const {puppeteer, browser, close} = await launch({}); try { const browserWSEndpoint = browser.wsEndpoint(); const remoteBrowser1 = await puppeteer.connect({ diff --git a/test/src/locator.spec.ts b/test/src/locator.spec.ts index a13df428ffc..859b81def36 100644 --- a/test/src/locator.spec.ts +++ b/test/src/locator.spec.ts @@ -22,18 +22,11 @@ import { } from 'puppeteer-core/internal/api/Locator.js'; import sinon from 'sinon'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; describe('Locator', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - it('should work with a frame', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.setContent(` @@ -56,7 +49,7 @@ describe('Locator', function () { }); it('should work without preconditions', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.setContent(` @@ -84,7 +77,7 @@ describe('Locator', function () { describe('Locator.click', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.setContent(` @@ -106,7 +99,7 @@ describe('Locator', function () { }); it('should work for multiple selectors', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.setContent(` @@ -128,7 +121,7 @@ describe('Locator', function () { }); it('should work if the element is out of viewport', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.setContent(` @@ -143,7 +136,7 @@ describe('Locator', function () { }); it('should work if the element becomes visible later', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.setContent(` @@ -176,7 +169,7 @@ describe('Locator', function () { }); it('should work if the element becomes enabled later', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.setContent(` @@ -201,7 +194,7 @@ describe('Locator', function () { }); it('should work if multiple conditions are satisfied later', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.setContent(` @@ -229,7 +222,7 @@ describe('Locator', function () { it('should time out', async () => { const clock = sinon.useFakeTimers(); try { - const {page} = getTestState(); + const {page} = await getTestState(); page.setDefaultTimeout(5000); await page.setViewport({width: 500, height: 500}); @@ -247,7 +240,7 @@ describe('Locator', function () { }); it('should retry clicks on errors', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const clock = sinon.useFakeTimers(); try { page.setDefaultTimeout(5000); @@ -266,7 +259,7 @@ describe('Locator', function () { }); it('can be aborted', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const clock = sinon.useFakeTimers(); try { page.setDefaultTimeout(5000); @@ -290,7 +283,7 @@ describe('Locator', function () { describe('Locator.hover', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.setContent(` @@ -314,7 +307,7 @@ describe('Locator', function () { describe('Locator.scroll', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.setContent(` @@ -343,7 +336,7 @@ describe('Locator', function () { describe('Locator.change', function () { it('should work for selects', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(` `); @@ -380,7 +373,7 @@ describe('Locator', function () { }); it('should work if the input becomes enabled later', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(` @@ -404,7 +397,7 @@ describe('Locator', function () { }); it('should work for contenteditable', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(`
`); @@ -417,7 +410,7 @@ describe('Locator', function () { }); it('should work for pre-filled inputs', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(` `); @@ -430,7 +423,7 @@ describe('Locator', function () { }); it('should override pre-filled inputs', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(` `); @@ -443,7 +436,7 @@ describe('Locator', function () { }); it('should work for non-text inputs', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(` `); @@ -458,7 +451,7 @@ describe('Locator', function () { describe('Locator.race', () => { it('races multiple locators', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.setContent(` @@ -480,7 +473,7 @@ describe('Locator', function () { }); it('can be aborted', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const clock = sinon.useFakeTimers(); try { await page.setViewport({width: 500, height: 500}); diff --git a/test/src/mocha-utils.ts b/test/src/mocha-utils.ts index 0db93b00238..b33a636288e 100644 --- a/test/src/mocha-utils.ts +++ b/test/src/mocha-utils.ts @@ -39,6 +39,87 @@ import sinon from 'sinon'; import {extendExpectWithToBeGolden} from './utils.js'; +let processVariables!: { + product: string; + alternativeInstall: string | boolean; + headless: 'true' | 'false' | 'new'; + isHeadless: boolean; + isFirefox: boolean; + isChrome: boolean; + protocol: 'cdp' | 'webDriverBiDi'; + defaultBrowserOptions: PuppeteerLaunchOptions; +}; +async function setUpProcessVariables() { + const product = + process.env['PRODUCT'] || process.env['PUPPETEER_PRODUCT'] || 'chrome'; + + const alternativeInstall = process.env['PUPPETEER_ALT_INSTALL'] || false; + + const headless = (process.env['HEADLESS'] || 'true').trim().toLowerCase() as + | 'true' + | 'false' + | 'new'; + const isHeadless = headless === 'true' || headless === 'new'; + const isFirefox = product === 'firefox'; + const isChrome = product === 'chrome'; + const protocol = (process.env['PUPPETEER_PROTOCOL'] || 'cdp') as + | 'cdp' + | 'webDriverBiDi'; + + let extraLaunchOptions = {}; + try { + extraLaunchOptions = JSON.parse( + process.env['EXTRA_LAUNCH_OPTIONS'] || '{}' + ); + } catch (error) { + if (isErrorLike(error)) { + console.warn( + `Error parsing EXTRA_LAUNCH_OPTIONS: ${error.message}. Skipping.` + ); + } else { + throw error; + } + } + + const defaultBrowserOptions = Object.assign( + { + handleSIGINT: true, + executablePath: process.env['BINARY'], + headless: headless === 'new' ? ('new' as const) : isHeadless, + dumpio: !!process.env['DUMPIO'], + protocol, + }, + extraLaunchOptions + ); + + if (defaultBrowserOptions.executablePath) { + console.warn( + `WARN: running ${product} tests with ${defaultBrowserOptions.executablePath}` + ); + } else { + const executablePath = puppeteer.executablePath(); + if (!fs.existsSync(executablePath)) { + throw new Error( + `Browser is not downloaded at ${executablePath}. Run 'npm install' and try to re-run tests` + ); + } + } + + processVariables = { + product, + alternativeInstall, + headless, + isHeadless, + isFirefox, + isChrome, + protocol, + defaultBrowserOptions, + }; +} +(async (): Promise => { + await setUpProcessVariables(); +})(); + const setupServer = async () => { const assetsPath = path.join(__dirname, '../assets'); const cachedPath = path.join(__dirname, '../assets', 'cached'); @@ -62,65 +143,58 @@ const setupServer = async () => { return {server, httpsServer}; }; -export const getTestState = (): PuppeteerTestState => { +export const getTestState = async ( + options: { + skipLaunch?: boolean; + skipContextCreation?: boolean; + } = {} +): Promise => { + const {skipLaunch = false, skipContextCreation = false} = options; + + state.defaultBrowserOptions = JSON.parse( + JSON.stringify(processVariables.defaultBrowserOptions) + ); + + if (!state.puppeteer) { + const {server, httpsServer} = await setupServer(); + + state.puppeteer = puppeteer; + state.server = server; + state.httpsServer = httpsServer; + state.isFirefox = processVariables.isFirefox; + state.isChrome = processVariables.isChrome; + state.isHeadless = processVariables.isHeadless; + state.headless = processVariables.headless; + state.puppeteerPath = path.resolve( + path.join(__dirname, '..', '..', 'packages', 'puppeteer') + ); + } + + if (!state.browser && !skipLaunch) { + state.browser = await puppeteer.launch( + processVariables.defaultBrowserOptions + ); + } + + if (state.context) { + await state.context.close(); + state.context = undefined; + state.page = undefined; + } + + if (!skipLaunch && !skipContextCreation) { + state.context = await state.browser!.createIncognitoBrowserContext(); + state.page = await state.context.newPage(); + } + + state.server?.reset(); + state.httpsServer?.reset(); + return state as PuppeteerTestState; }; -const product = - process.env['PRODUCT'] || process.env['PUPPETEER_PRODUCT'] || 'chrome'; - -const alternativeInstall = process.env['PUPPETEER_ALT_INSTALL'] || false; - -const headless = (process.env['HEADLESS'] || 'true').trim().toLowerCase() as - | 'true' - | 'false' - | 'new'; -const isHeadless = headless === 'true' || headless === 'new'; -const isFirefox = product === 'firefox'; -const isChrome = product === 'chrome'; -const protocol = process.env['PUPPETEER_PROTOCOL'] || 'cdp'; - -let extraLaunchOptions = {}; -try { - extraLaunchOptions = JSON.parse(process.env['EXTRA_LAUNCH_OPTIONS'] || '{}'); -} catch (error) { - if (isErrorLike(error)) { - console.warn( - `Error parsing EXTRA_LAUNCH_OPTIONS: ${error.message}. Skipping.` - ); - } else { - throw error; - } -} - -const defaultBrowserOptions = Object.assign( - { - handleSIGINT: true, - executablePath: process.env['BINARY'], - headless: headless === 'new' ? ('new' as const) : isHeadless, - dumpio: !!process.env['DUMPIO'], - protocol: protocol as 'cdp' | 'webDriverBiDi', - }, - extraLaunchOptions -); - -(async (): Promise => { - if (defaultBrowserOptions.executablePath) { - console.warn( - `WARN: running ${product} tests with ${defaultBrowserOptions.executablePath}` - ); - } else { - const executablePath = puppeteer.executablePath(); - if (!fs.existsSync(executablePath)) { - throw new Error( - `Browser is not downloaded at ${executablePath}. Run 'npm install' and try to re-run tests` - ); - } - } -})(); - const setupGoldenAssertions = (): void => { - const suffix = product.toLowerCase(); + const suffix = processVariables.product.toLowerCase(); const GOLDEN_DIR = path.join(__dirname, `../golden-${suffix}`); const OUTPUT_DIR = path.join(__dirname, `../output-${suffix}`); if (fs.existsSync(OUTPUT_DIR)) { @@ -151,7 +225,7 @@ export const itOnlyRegularInstall = ( description: string, body: Mocha.AsyncFunc ): Mocha.Test => { - if (alternativeInstall || process.env['BINARY']) { + if (processVariables.alternativeInstall || process.env['BINARY']) { return it.skip(description, body); } else { return it(description, body); @@ -164,14 +238,14 @@ if ( ) { console.log( `Running unit tests with: - -> product: ${product} + -> product: ${processVariables.product} -> binary: ${ - defaultBrowserOptions.executablePath || + processVariables.defaultBrowserOptions.executablePath || path.relative(process.cwd(), puppeteer.executablePath()) } -> mode: ${ - isHeadless - ? headless === 'new' + processVariables.isHeadless + ? processVariables.headless === 'new' ? '--headless=new' : '--headless' : 'headful' @@ -183,69 +257,21 @@ process.on('unhandledRejection', reason => { throw reason; }); -export const setupTestBrowserHooks = (): void => { - before(async () => { - const browser = await puppeteer.launch(defaultBrowserOptions); - state.browser = browser; - }); - - after(async () => { - await state.browser?.close(); - state.browser = undefined; - }); -}; - -export const setupTestPageAndContextHooks = (): void => { - beforeEach(async () => { - state.context = await state.browser!.createIncognitoBrowserContext(); - state.page = await state.context.newPage(); - }); - - afterEach(async () => { - await state.context?.close(); - state.context = undefined; - state.page = undefined; - }); -}; - +const browserNotClosedError = new Error( + 'A manually launched browser was not closed!' +); export const mochaHooks = { - beforeAll: [ - async (): Promise => { - const {server, httpsServer} = await setupServer(); - - state.puppeteer = puppeteer; - state.defaultBrowserOptions = defaultBrowserOptions; - state.server = server; - state.httpsServer = httpsServer; - state.isFirefox = isFirefox; - state.isChrome = isChrome; - state.isHeadless = isHeadless; - state.headless = headless; - state.puppeteerPath = path.resolve( - path.join(__dirname, '..', '..', 'packages', 'puppeteer') - ); - }, - ], - - beforeEach: async (): Promise => { - state.server!.reset(); - state.httpsServer!.reset(); + async afterAll(): Promise { + await state.browser?.close(); + await state.server?.stop(); + await state.httpsServer?.stop(); }, - afterAll: [ - async (): Promise => { - await state.server!.stop(); - state.server = undefined; - await state.httpsServer!.stop(); - state.httpsServer = undefined; - }, - ], - - afterEach: (): void => { + async afterEach(): Promise { if (browserCleanups.length > 0) { - throw new Error('A manually launched browser was not closed!'); + await closeLaunched(); + (this as any).test.error(browserNotClosedError); } - sinon.restore(); }, }; @@ -281,12 +307,11 @@ expect.extend({ }, }); -export const expectCookieEquals = ( +export const expectCookieEquals = async ( cookies: Protocol.Network.Cookie[], expectedCookies: Array> -): void => { - const {isChrome} = getTestState(); - if (!isChrome) { +): Promise => { + if (!processVariables.isChrome) { // Only keep standard properties when testing on a browser other than Chrome. expectedCookies = expectedCookies.map(cookie => { return { @@ -303,7 +328,7 @@ export const expectCookieEquals = ( }); } - expect(cookies.length).toBe(expectedCookies.length); + expect(cookies).toHaveLength(expectedCookies.length); for (let i = 0; i < cookies.length; i++) { expect(cookies[i]).toMatchObject(expectedCookies[i]!); } @@ -366,6 +391,25 @@ export const createTimeout = ( let browserCleanups: Array<() => Promise> = []; +const closeLaunched = async () => { + let cleanup = browserCleanups.pop(); + try { + while (cleanup) { + await cleanup(); + cleanup = browserCleanups.pop(); + } + } catch (error) { + // If the browser was closed by other mean swallow the error + // and mark he browser as closed + if ((error as any)?.message.includes('Connection closed')) { + browserCleanups = []; + return; + } + + throw error; + } +}; + export const launch = async ( launchOptions: PuppeteerLaunchOptions, options: { @@ -378,28 +422,13 @@ export const launch = async ( } > => { const {createContext = true, createPage = true} = options; - const close = async () => { - let cleanup = browserCleanups.pop(); - try { - while (cleanup) { - await cleanup(); - cleanup = browserCleanups.pop(); - } - } catch (error) { - // If the browser was closed by other mean swallow the error - // and mark he browser as closed - if ((error as any)?.message.includes('Connection closed')) { - browserCleanups = []; - return; - } - - throw error; - } - }; + const initState = await getTestState({ + skipLaunch: true, + }); try { const browser = await puppeteer.launch({ - ...defaultBrowserOptions, + ...initState.defaultBrowserOptions, ...launchOptions, }); browserCleanups.push(() => { @@ -423,14 +452,14 @@ export const launch = async ( } return { - ...getTestState(), + ...initState, browser, context: context!, page: page!, - close, + close: closeLaunched, }; } catch (error) { - await close(); + await closeLaunched(); throw error; } diff --git a/test/src/mouse.spec.ts b/test/src/mouse.spec.ts index df19dfd08b8..f593e457596 100644 --- a/test/src/mouse.spec.ts +++ b/test/src/mouse.spec.ts @@ -20,11 +20,7 @@ import {MouseButton} from 'puppeteer-core/internal/api/Input.js'; import {Page} from 'puppeteer-core/internal/api/Page.js'; import {KeyInput} from 'puppeteer-core/internal/common/USKeyboardLayout.js'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; interface ClickData { type: string; @@ -54,10 +50,8 @@ function dimensions(): Dimensions { } describe('Mouse', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); it('should click the document', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.evaluate(() => { (globalThis as any).clickPromise = new Promise(resolve => { @@ -85,7 +79,7 @@ describe('Mouse', function () { expect(event.button).toBe(0); }); it('should resize the textarea', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/textarea.html'); const {x, y, width, height} = await page.evaluate(dimensions); @@ -99,7 +93,7 @@ describe('Mouse', function () { expect(newDimensions.height).toBe(Math.round(height + 104)); }); it('should select the text with mouse', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/textarea.html'); await page.focus('textarea'); @@ -129,7 +123,7 @@ describe('Mouse', function () { ).toBe(text); }); it('should trigger hover state', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/scrollable.html'); await page.hover('#button-6'); @@ -152,7 +146,7 @@ describe('Mouse', function () { ).toBe('button-91'); }); it('should trigger hover state with removed window.Node', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/scrollable.html'); await page.evaluate(() => { @@ -167,7 +161,7 @@ describe('Mouse', function () { ).toBe('button-6'); }); it('should set modifier keys on click', async () => { - const {page, server, isFirefox} = getTestState(); + const {page, server, isFirefox} = await getTestState(); await page.goto(server.PREFIX + '/input/scrollable.html'); await page.evaluate(() => { @@ -213,7 +207,7 @@ describe('Mouse', function () { } }); it('should send mouse wheel events', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/wheel.html'); const elem = (await page.$('div'))!; @@ -236,7 +230,7 @@ describe('Mouse', function () { }); }); it('should tween mouse movement', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.mouse.move(100, 100); await page.evaluate(() => { @@ -256,7 +250,7 @@ describe('Mouse', function () { }); // @see https://crbug.com/929806 it('should work with mobile viewports and cross process navigations', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setViewport({width: 360, height: 640, isMobile: true}); @@ -272,7 +266,7 @@ describe('Mouse', function () { expect(await page.evaluate('result')).toEqual({x: 30, y: 40}); }); it('should throw if buttons are pressed incorrectly', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); @@ -312,7 +306,7 @@ describe('Mouse', function () { }; it('should not throw if clicking in parallel', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await addMouseDataListeners(page); @@ -370,7 +364,7 @@ describe('Mouse', function () { }); it('should reset properly', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); diff --git a/test/src/navigation.spec.ts b/test/src/navigation.spec.ts index 3c0271a39bd..c4e9c860446 100644 --- a/test/src/navigation.spec.ts +++ b/test/src/navigation.spec.ts @@ -20,26 +20,19 @@ import expect from 'expect'; import {Frame, TimeoutError} from 'puppeteer'; import {HTTPRequest} from 'puppeteer-core/internal/api/HTTPRequest.js'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; import {attachFrame, isFavicon, waitEvent} from './utils.js'; describe('navigation', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - describe('Page.goto', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); expect(page.url()).toBe(server.EMPTY_PAGE); }); it('should work with anchor navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); expect(page.url()).toBe(server.EMPTY_PAGE); @@ -49,7 +42,7 @@ describe('navigation', function () { expect(page.url()).toBe(server.EMPTY_PAGE + '#bar'); }); it('should work with redirects', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRedirect('/redirect/1.html', '/redirect/2.html'); server.setRedirect('/redirect/2.html', '/empty.html'); @@ -57,19 +50,19 @@ describe('navigation', function () { expect(page.url()).toBe(server.EMPTY_PAGE); }); it('should navigate to about:blank', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const response = await page.goto('about:blank'); expect(response).toBe(null); }); it('should return response when page changes its URL after load', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const response = await page.goto(server.PREFIX + '/historyapi.html'); expect(response!.status()).toBe(200); }); it('should work with subframes return 204', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRoute('/frames/frame.html', (_req, res) => { res.statusCode = 204; @@ -84,7 +77,7 @@ describe('navigation', function () { expect(error).toBeUndefined(); }); it('should fail when server returns 204', async () => { - const {page, server, isChrome} = getTestState(); + const {page, server, isChrome} = await getTestState(); server.setRoute('/empty.html', (_req, res) => { res.statusCode = 204; @@ -102,7 +95,7 @@ describe('navigation', function () { } }); it('should navigate to empty page with domcontentloaded', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const response = await page.goto(server.EMPTY_PAGE, { waitUntil: 'domcontentloaded', @@ -110,7 +103,7 @@ describe('navigation', function () { expect(response!.status()).toBe(200); }); it('should work when page calls history API in beforeunload', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.evaluate(() => { @@ -126,7 +119,7 @@ describe('navigation', function () { expect(response!.status()).toBe(200); }); it('should navigate to empty page with networkidle0', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const response = await page.goto(server.EMPTY_PAGE, { waitUntil: 'networkidle0', @@ -134,7 +127,7 @@ describe('navigation', function () { expect(response!.status()).toBe(200); }); it('should navigate to empty page with networkidle2', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const response = await page.goto(server.EMPTY_PAGE, { waitUntil: 'networkidle2', @@ -142,7 +135,7 @@ describe('navigation', function () { expect(response!.status()).toBe(200); }); it('should fail when navigating to bad url', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page.goto('asdfasdf').catch(error_ => { @@ -159,7 +152,7 @@ describe('navigation', function () { /net::ERR_CERT_INVALID|net::ERR_CERT_AUTHORITY_INVALID/; it('should fail when navigating to bad SSL', async () => { - const {page, httpsServer, isChrome} = getTestState(); + const {page, httpsServer, isChrome} = await getTestState(); // Make sure that network events do not emit 'undefined'. // @see https://crbug.com/750469 @@ -189,7 +182,7 @@ describe('navigation', function () { expect(requests[1]).toBe('requestfailed'); }); it('should fail when navigating to bad SSL after redirects', async () => { - const {page, server, httpsServer, isChrome} = getTestState(); + const {page, server, httpsServer, isChrome} = await getTestState(); server.setRedirect('/redirect/1.html', '/redirect/2.html'); server.setRedirect('/redirect/2.html', '/empty.html'); @@ -207,7 +200,7 @@ describe('navigation', function () { } }); it('should fail when main resources failed to load', async () => { - const {page, isChrome} = getTestState(); + const {page, isChrome} = await getTestState(); let error!: Error; await page @@ -222,7 +215,7 @@ describe('navigation', function () { } }); it('should fail when exceeding maximum navigation timeout', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Hang for request to the empty.html server.setRoute('/empty.html', () => {}); @@ -236,7 +229,7 @@ describe('navigation', function () { expect(error).toBeInstanceOf(TimeoutError); }); it('should fail when exceeding default maximum navigation timeout', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Hang for request to the empty.html server.setRoute('/empty.html', () => {}); @@ -249,7 +242,7 @@ describe('navigation', function () { expect(error).toBeInstanceOf(TimeoutError); }); it('should fail when exceeding default maximum timeout', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Hang for request to the empty.html server.setRoute('/empty.html', () => {}); @@ -262,7 +255,7 @@ describe('navigation', function () { expect(error).toBeInstanceOf(TimeoutError); }); it('should prioritize default navigation timeout over default timeout', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Hang for request to the empty.html server.setRoute('/empty.html', () => {}); @@ -276,7 +269,7 @@ describe('navigation', function () { expect(error).toBeInstanceOf(TimeoutError); }); it('should disable timeout when its set to 0', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let error!: Error; let loaded = false; @@ -292,26 +285,26 @@ describe('navigation', function () { expect(loaded).toBe(true); }); it('should work when navigating to valid url', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const response = (await page.goto(server.EMPTY_PAGE))!; expect(response.ok()).toBe(true); }); it('should work when navigating to data url', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const response = (await page.goto('data:text/html,hello'))!; expect(response.ok()).toBe(true); }); it('should work when navigating to 404', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const response = (await page.goto(server.PREFIX + '/not-found'))!; expect(response.ok()).toBe(false); expect(response.status()).toBe(404); }); it('should not throw an error for a 404 response with an empty body', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRoute('/404-error', (_, res) => { res.statusCode = 404; @@ -323,7 +316,7 @@ describe('navigation', function () { expect(response.status()).toBe(404); }); it('should not throw an error for a 500 response with an empty body', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRoute('/500-error', (_, res) => { res.statusCode = 500; @@ -335,7 +328,7 @@ describe('navigation', function () { expect(response.status()).toBe(500); }); it('should return last response in redirect chain', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRedirect('/redirect/1.html', '/redirect/2.html'); server.setRedirect('/redirect/2.html', '/redirect/3.html'); @@ -345,7 +338,7 @@ describe('navigation', function () { expect(response.url()).toBe(server.EMPTY_PAGE); }); it('should wait for network idle to succeed navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let responses: ServerResponse[] = []; // Hold on to a bunch of requests without answering. @@ -442,7 +435,7 @@ describe('navigation', function () { it('should not leak listeners during navigation', async function () { this.timeout(25_000); - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let warning = null; const warningHandler: NodeJS.WarningListener = w => { @@ -458,7 +451,7 @@ describe('navigation', function () { it('should not leak listeners during bad navigation', async function () { this.timeout(25_000); - const {page} = getTestState(); + const {page} = await getTestState(); let warning = null; const warningHandler: NodeJS.WarningListener = w => { @@ -476,7 +469,7 @@ describe('navigation', function () { it('should not leak listeners during navigation of 11 pages', async function () { this.timeout(25_000); - const {context, server} = getTestState(); + const {context, server} = await getTestState(); let warning = null; const warningHandler: NodeJS.WarningListener = w => { @@ -494,7 +487,7 @@ describe('navigation', function () { expect(warning).toBe(null); }); it('should navigate to dataURL and fire dataURL requests', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const requests: HTTPRequest[] = []; page.on('request', request => { @@ -507,7 +500,7 @@ describe('navigation', function () { expect(requests[0]!.url()).toBe(dataURL); }); it('should navigate to URL with hash and fire requests without hash', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const requests: HTTPRequest[] = []; page.on('request', request => { @@ -520,14 +513,14 @@ describe('navigation', function () { expect(requests[0]!.url()).toBe(server.EMPTY_PAGE); }); it('should work with self requesting page', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); 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 () => { - const {page, httpsServer} = getTestState(); + const {page, httpsServer} = await getTestState(); const url = httpsServer.PREFIX + '/redirect/1.html'; let error!: Error; @@ -539,7 +532,7 @@ describe('navigation', function () { expect(error.message).toContain(url); }); it('should send referer', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const requests = Promise.all([ server.waitForRequest('/grid.html'), @@ -558,7 +551,7 @@ describe('navigation', function () { }); it('should send referer policy', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const [request1, request2] = await Promise.all([ server.waitForRequest('/grid.html'), @@ -576,7 +569,7 @@ describe('navigation', function () { describe('Page.waitForNavigation', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const [response] = await Promise.all([ @@ -589,7 +582,7 @@ describe('navigation', function () { expect(response!.url()).toContain('grid.html'); }); it('should work with both domcontentloaded and load', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let response!: ServerResponse; server.setRoute('/one-style.css', (_req, res) => { @@ -630,7 +623,7 @@ describe('navigation', function () { expect(error).toBeUndefined(); }); it('should work with clicking on anchor links', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setContent(`foobar`); @@ -642,7 +635,7 @@ describe('navigation', function () { expect(page.url()).toBe(server.EMPTY_PAGE + '#foobar'); }); it('should work with history.pushState()', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setContent(` @@ -659,7 +652,7 @@ describe('navigation', function () { expect(page.url()).toBe(server.PREFIX + '/wow.html'); }); it('should work with history.replaceState()', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setContent(` @@ -676,7 +669,7 @@ describe('navigation', function () { expect(page.url()).toBe(server.PREFIX + '/replaced.html'); }); it('should work with DOM history.back()/history.forward()', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setContent(` @@ -704,7 +697,7 @@ describe('navigation', function () { expect(page.url()).toBe(server.PREFIX + '/second.html'); }); it('should work when subframe issues window.stop()', async function () { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRoute('/frames/style.css', () => {}); let frame: Frame | undefined; @@ -745,7 +738,7 @@ describe('navigation', function () { describe('Page.goBack', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.goto(server.PREFIX + '/grid.html'); @@ -762,7 +755,7 @@ describe('navigation', function () { expect(response).toBe(null); }); it('should work with HistoryAPI', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.evaluate(() => { @@ -782,7 +775,7 @@ describe('navigation', function () { describe('Frame.goto', function () { it('should navigate subframes', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/frames/one-frame.html'); expect(page.frames()[0]!.url()).toContain('/frames/one-frame.html'); @@ -793,7 +786,7 @@ describe('navigation', function () { expect(response.frame()).toBe(page.frames()[1]); }); it('should reject when frame detaches', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/frames/one-frame.html'); @@ -813,7 +806,7 @@ describe('navigation', function () { expect(error.message).toBe('Navigating frame was detached'); }); it('should return matching responses', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Disable cache: otherwise, the browser will cache similar requests. await page.setCacheEnabled(false); @@ -847,7 +840,7 @@ describe('navigation', function () { describe('Frame.waitForNavigation', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/frames/one-frame.html'); const frame = page.frames()[1]!; @@ -863,7 +856,7 @@ describe('navigation', function () { expect(page.url()).toContain('/frames/one-frame.html'); }); it('should fail when frame detaches', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/frames/one-frame.html'); const frame = page.frames()[1]!; @@ -892,7 +885,7 @@ describe('navigation', function () { describe('Page.reload', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.evaluate(() => { diff --git a/test/src/network.spec.ts b/test/src/network.spec.ts index 02f9782a269..ad1a317665e 100644 --- a/test/src/network.spec.ts +++ b/test/src/network.spec.ts @@ -22,21 +22,13 @@ import expect from 'expect'; import {HTTPRequest} from 'puppeteer-core/internal/api/HTTPRequest.js'; import {HTTPResponse} from 'puppeteer-core/internal/api/HTTPResponse.js'; -import { - getTestState, - launch, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState, launch} from './mocha-utils.js'; import {attachFrame, isFavicon, waitEvent} from './utils.js'; describe('network', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - describe('Page.Events.Request', function () { it('should fire for navigation requests', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const requests: HTTPRequest[] = []; page.on('request', request => { @@ -46,7 +38,7 @@ describe('network', function () { expect(requests).toHaveLength(1); }); it('should fire for iframes', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const requests: HTTPRequest[] = []; page.on('request', request => { @@ -57,7 +49,7 @@ describe('network', function () { expect(requests).toHaveLength(2); }); it('should fire for fetches', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const requests: HTTPRequest[] = []; page.on('request', request => { @@ -72,7 +64,7 @@ describe('network', function () { }); describe('Request.frame', function () { it('should work for main frame navigation request', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const requests: HTTPRequest[] = []; page.on('request', request => { @@ -83,7 +75,7 @@ describe('network', function () { expect(requests[0]!.frame()).toBe(page.mainFrame()); }); it('should work for subframe navigation request', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const requests: HTTPRequest[] = []; @@ -95,7 +87,7 @@ describe('network', function () { expect(requests[0]!.frame()).toBe(page.frames()[1]); }); it('should work for fetch requests', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); let requests: HTTPRequest[] = []; @@ -115,13 +107,13 @@ describe('network', function () { describe('Request.headers', function () { it('should define Chrome as user agent header', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const response = (await page.goto(server.EMPTY_PAGE))!; expect(response.request().headers()['user-agent']).toContain('Chrome'); }); it('should define Firefox as user agent header', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const response = (await page.goto(server.EMPTY_PAGE))!; expect(response.request().headers()['user-agent']).toContain('Firefox'); @@ -130,7 +122,7 @@ describe('network', function () { describe('Response.headers', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRoute('/empty.html', (_req, res) => { res.setHeader('foo', 'bar'); @@ -143,7 +135,7 @@ describe('network', function () { describe('Request.initiator', () => { it('should return the initiator', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const initiators = new Map(); page.on('request', request => { @@ -188,14 +180,14 @@ describe('network', function () { describe('Response.fromCache', function () { it('should return |false| for non-cached content', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const response = (await page.goto(server.EMPTY_PAGE))!; expect(response.fromCache()).toBe(false); }); it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const responses = new Map(); page.on('response', r => { @@ -218,14 +210,14 @@ describe('network', function () { describe('Response.fromServiceWorker', function () { it('should return |false| for non-service-worker content', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const response = (await page.goto(server.EMPTY_PAGE))!; expect(response.fromServiceWorker()).toBe(false); }); it('Response.fromServiceWorker', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const responses = new Map(); page.on('response', r => { @@ -251,7 +243,7 @@ describe('network', function () { describe('Request.postData', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); server.setRoute('/post', (_req, res) => { @@ -274,7 +266,7 @@ describe('network', function () { expect(request.postData()).toBe('{"foo":"bar"}'); }); it('should be |undefined| when there is no post data', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const response = (await page.goto(server.EMPTY_PAGE))!; expect(response.request().postData()).toBe(undefined); @@ -283,14 +275,14 @@ describe('network', function () { describe('Response.text', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const response = (await page.goto(server.PREFIX + '/simple.json'))!; const responseText = (await response.text()).trimEnd(); expect(responseText).toBe('{"foo": "bar"}'); }); it('should return uncompressed text', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.enableGzip('/simple.json'); const response = (await page.goto(server.PREFIX + '/simple.json'))!; @@ -299,7 +291,7 @@ describe('network', function () { expect(responseText).toBe('{"foo": "bar"}'); }); it('should throw when requesting body of redirected response', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRedirect('/foo.html', '/empty.html'); const response = (await page.goto(server.PREFIX + '/foo.html'))!; @@ -316,7 +308,7 @@ describe('network', function () { ); }); it('should wait until response completes', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); // Setup server to trap request. @@ -366,7 +358,7 @@ describe('network', function () { describe('Response.json', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const response = (await page.goto(server.PREFIX + '/simple.json'))!; expect(await response.json()).toEqual({foo: 'bar'}); @@ -375,7 +367,7 @@ describe('network', function () { describe('Response.buffer', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const response = (await page.goto(server.PREFIX + '/pptr.png'))!; const imageBuffer = fs.readFileSync( @@ -385,7 +377,7 @@ describe('network', function () { expect(responseBuffer.equals(imageBuffer)).toBe(true); }); it('should work with compression', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.enableGzip('/pptr.png'); const response = (await page.goto(server.PREFIX + '/pptr.png'))!; @@ -396,7 +388,7 @@ describe('network', function () { expect(responseBuffer.equals(imageBuffer)).toBe(true); }); it('should throw if the response does not have a body', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/empty.html'); @@ -435,7 +427,7 @@ describe('network', function () { describe('Response.statusText', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRoute('/cool', (_req, res) => { res.writeHead(200, 'cool!'); @@ -446,7 +438,7 @@ describe('network', function () { }); it('handles missing status text', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRoute('/nostatus', (_req, res) => { res.writeHead(200, ''); @@ -459,7 +451,7 @@ describe('network', function () { describe('Response.timing', function () { it('returns timing information', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const responses: HTTPResponse[] = []; page.on('response', response => { return responses.push(response); @@ -472,7 +464,7 @@ describe('network', function () { describe('Network Events', function () { it('Page.Events.Request', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const requests: HTTPRequest[] = []; page.on('request', request => { @@ -488,7 +480,7 @@ describe('network', function () { expect(requests[0]!.frame()!.url()).toBe(server.EMPTY_PAGE); }); it('Page.Events.RequestServedFromCache', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const cached: string[] = []; page.on('requestservedfromcache', r => { @@ -502,7 +494,7 @@ describe('network', function () { expect(cached).toEqual(['one-style.css']); }); it('Page.Events.Response', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const responses: HTTPResponse[] = []; page.on('response', response => { @@ -523,7 +515,7 @@ describe('network', function () { }); it('Page.Events.RequestFailed', async () => { - const {page, server, isChrome} = getTestState(); + const {page, server, isChrome} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -552,7 +544,7 @@ describe('network', function () { expect(failedRequests[0]!.frame()).toBeTruthy(); }); it('Page.Events.RequestFinished', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const requests: HTTPRequest[] = []; page.on('requestfinished', request => { @@ -567,7 +559,7 @@ describe('network', function () { expect(request.frame()!.url()).toBe(server.EMPTY_PAGE); }); it('should fire events in proper order', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const events: string[] = []; page.on('request', () => { @@ -588,7 +580,7 @@ describe('network', function () { ]); }); it('should support redirects', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const events: string[] = []; page.on('request', request => { @@ -627,7 +619,7 @@ describe('network', function () { describe('Request.isNavigationRequest', () => { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const requests = new Map(); page.on('request', request => { @@ -642,7 +634,7 @@ describe('network', function () { expect(requests.get('style.css').isNavigationRequest()).toBe(false); }); it('should work with request interception', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const requests = new Map(); page.on('request', request => { @@ -659,7 +651,7 @@ describe('network', function () { expect(requests.get('style.css').isNavigationRequest()).toBe(false); }); it('should work when navigating to image', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const [request] = await Promise.all([ waitEvent(page, 'request'), @@ -671,7 +663,7 @@ describe('network', function () { describe('Page.setExtraHTTPHeaders', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setExtraHTTPHeaders({ foo: 'bar', @@ -683,7 +675,7 @@ describe('network', function () { expect(request.headers['foo']).toBe('bar'); }); it('should throw for non-string header values', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; try { @@ -700,7 +692,7 @@ describe('network', function () { describe('Page.authenticate', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setAuth('/empty.html', 'user', 'pass'); let response; @@ -725,7 +717,7 @@ describe('network', function () { expect(response.status()).toBe(200); }); it('should fail if wrong credentials', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Use unique user/password since Chrome caches credentials per origin. server.setAuth('/empty.html', 'user2', 'pass2'); @@ -737,7 +729,7 @@ describe('network', function () { expect(response.status()).toBe(401); }); it('should allow disable authentication', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Use unique user/password since Chrome caches credentials per origin. server.setAuth('/empty.html', 'user3', 'pass3'); @@ -769,7 +761,7 @@ describe('network', function () { } }); it('should not disable caching', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Use unique user/password since Chrome caches credentials per origin. server.setAuth('/cached/one-style.css', 'user4', 'pass4'); @@ -797,7 +789,7 @@ describe('network', function () { describe('raw network headers', () => { it('Same-origin set-cookie navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const setCookieString = 'foo=bar'; server.setRoute('/empty.html', (_req, res) => { @@ -809,7 +801,7 @@ describe('network', function () { }); it('Same-origin set-cookie subresource', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const setCookieString = 'foo=bar'; @@ -865,7 +857,7 @@ describe('network', function () { describe('Page.setBypassServiceWorker', () => { it('bypass for network', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const responses = new Map(); page.on('response', r => { diff --git a/test/src/oopif.spec.ts b/test/src/oopif.spec.ts index 9389f1a3eff..096090ff5f5 100644 --- a/test/src/oopif.spec.ts +++ b/test/src/oopif.spec.ts @@ -29,7 +29,7 @@ describeWithDebugLogs('OOPIF', function () { let page: Page; before(async () => { - const {puppeteer, defaultBrowserOptions} = getTestState(); + const {puppeteer, defaultBrowserOptions} = await getTestState(); // eslint-disable-next-line no-restricted-syntax browser = await puppeteer.launch( Object.assign({}, defaultBrowserOptions, { @@ -56,7 +56,7 @@ describeWithDebugLogs('OOPIF', function () { }); it('should treat OOP iframes and normal iframes the same', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const framePromise = page.waitForFrame(frame => { @@ -72,7 +72,7 @@ describeWithDebugLogs('OOPIF', function () { expect(page.mainFrame().childFrames()).toHaveLength(2); }); it('should track navigations within OOP iframes', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const framePromise = page.waitForFrame(frame => { @@ -93,7 +93,7 @@ describeWithDebugLogs('OOPIF', function () { expect(frame.url()).toContain('/assets/frame.html'); }); it('should support OOP iframes becoming normal iframes again', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const framePromise = page.waitForFrame(frame => { @@ -114,7 +114,7 @@ describeWithDebugLogs('OOPIF', function () { expect(page.frames()).toHaveLength(2); }); it('should support frames within OOP frames', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const frame1Promise = page.waitForFrame(frame => { @@ -143,7 +143,7 @@ describeWithDebugLogs('OOPIF', function () { ).toMatch(/frames\/frame\.html$/); }); it('should support OOP iframes getting detached', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const framePromise = page.waitForFrame(frame => { @@ -164,7 +164,7 @@ describeWithDebugLogs('OOPIF', function () { }); it('should support wait for navigation for transitions from local to OOPIF', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const framePromise = page.waitForFrame(frame => { @@ -187,7 +187,7 @@ describeWithDebugLogs('OOPIF', function () { }); it('should keep track of a frames OOP state', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const framePromise = page.waitForFrame(frame => { @@ -205,7 +205,7 @@ describeWithDebugLogs('OOPIF', function () { }); it('should support evaluating in oop iframes', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const framePromise = page.waitForFrame(frame => { @@ -230,7 +230,7 @@ describeWithDebugLogs('OOPIF', function () { expect(result).toBe('Test 123!'); }); it('should provide access to elements', async () => { - const {server, isHeadless, headless} = getTestState(); + const {server, isHeadless, headless} = await getTestState(); if (!isHeadless || headless === 'new') { // TODO: this test is partially blocked on crbug.com/1334119. Enable test once @@ -276,7 +276,7 @@ describeWithDebugLogs('OOPIF', function () { await frame.waitForSelector('#clicked'); }); it('should report oopif frames', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); const frame = page.waitForFrame(frame => { return frame.url().endsWith('/oopif.html'); @@ -288,7 +288,7 @@ describeWithDebugLogs('OOPIF', function () { }); it('should wait for inner OOPIFs', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); await page.goto(`http://mainframe:${server.PORT}/main-frame.html`); const frame2 = await page.waitForFrame(frame => { return frame.url().endsWith('inner-frame2.html'); @@ -307,7 +307,7 @@ describeWithDebugLogs('OOPIF', function () { }); it('should load oopif iframes with subresources and request interception', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); const frame = page.waitForFrame(frame => { return frame.url().endsWith('/oopif.html'); @@ -321,7 +321,7 @@ describeWithDebugLogs('OOPIF', function () { expect(oopifs(context)).toHaveLength(1); }); it('should support frames within OOP iframes', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); const oopIframePromise = page.waitForFrame(frame => { return frame.url().endsWith('/oopif.html'); @@ -352,7 +352,7 @@ describeWithDebugLogs('OOPIF', function () { }); it('clickablePoint, boundingBox, boxModel should work for elements inside OOPIFs', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const framePromise = page.waitForFrame(frame => { return page.frames().indexOf(frame) === 1; @@ -398,7 +398,7 @@ describeWithDebugLogs('OOPIF', function () { }); it('should detect existing OOPIFs when Puppeteer connects to an existing page', async () => { - const {server, puppeteer} = getTestState(); + const {server, puppeteer} = await getTestState(); const frame = page.waitForFrame(frame => { return frame.url().endsWith('/oopif.html'); @@ -418,7 +418,7 @@ describeWithDebugLogs('OOPIF', function () { }); it('should support lazy OOP frames', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); await page.goto(server.PREFIX + '/lazy-oopif-frame.html'); await page.setViewport({width: 1000, height: 1000}); @@ -432,7 +432,7 @@ describeWithDebugLogs('OOPIF', function () { describe('waitForFrame', () => { it('should resolve immediately if the frame already exists', async () => { - const {server} = getTestState(); + const {server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await attachFrame( diff --git a/test/src/page.spec.ts b/test/src/page.spec.ts index 51f08a2d464..9c64dc6943a 100644 --- a/test/src/page.spec.ts +++ b/test/src/page.spec.ts @@ -25,19 +25,13 @@ import {ConsoleMessage} from 'puppeteer-core/internal/common/ConsoleMessage.js'; import {CDPPage} from 'puppeteer-core/internal/common/Page.js'; import sinon from 'sinon'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; import {attachFrame, detachFrame, isFavicon, waitEvent} from './utils.js'; describe('Page', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); describe('Page.close', function () { it('should reject all promises when page is closed', async () => { - const {context} = getTestState(); + const {context} = await getTestState(); const newPage = await context.newPage(); let error!: Error; @@ -54,7 +48,7 @@ describe('Page', function () { expect(error.message).toContain('Protocol error'); }); it('should not be visible in browser.pages', async () => { - const {browser} = getTestState(); + const {browser} = await getTestState(); const newPage = await browser.newPage(); expect(await browser.pages()).toContain(newPage); @@ -62,7 +56,7 @@ describe('Page', function () { expect(await browser.pages()).not.toContain(newPage); }); it('should run beforeunload if asked for', async () => { - const {context, server, isChrome} = getTestState(); + const {context, server, isChrome} = await getTestState(); const newPage = await context.newPage(); await newPage.goto(server.PREFIX + '/beforeunload.html'); @@ -82,7 +76,7 @@ describe('Page', function () { await pageClosingPromise; }); it('should *not* run beforeunload by default', async () => { - const {context, server} = getTestState(); + const {context, server} = await getTestState(); const newPage = await context.newPage(); await newPage.goto(server.PREFIX + '/beforeunload.html'); @@ -92,7 +86,7 @@ describe('Page', function () { await newPage.close(); }); it('should set the page close state', async () => { - const {context} = getTestState(); + const {context} = await getTestState(); const newPage = await context.newPage(); expect(newPage.isClosed()).toBe(false); @@ -100,7 +94,7 @@ describe('Page', function () { expect(newPage.isClosed()).toBe(true); }); it('should terminate network waiters', async () => { - const {context, server} = getTestState(); + const {context, server} = await getTestState(); const newPage = await context.newPage(); const results = await Promise.all([ @@ -122,7 +116,7 @@ describe('Page', function () { describe('Page.Events.Load', function () { it('should fire when expected', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await Promise.all([waitEvent(page, 'load'), page.goto('about:blank')]); }); @@ -130,7 +124,7 @@ describe('Page', function () { describe('removing and adding event handlers', () => { it('should correctly fire event handlers as they are added and then removed', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const handler = sinon.spy(); const onResponse = (response: {url: () => string}) => { @@ -153,7 +147,7 @@ describe('Page', function () { }); it('should correctly added and removed request events', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const handler = sinon.spy(); const onResponse = (response: {url: () => string}) => { @@ -183,7 +177,7 @@ describe('Page', function () { describe('Page.Events.error', function () { it('should throw when page crashes', async () => { - const {page, isChrome} = getTestState(); + const {page, isChrome} = await getTestState(); let navigate: Promise; if (isChrome) { @@ -201,7 +195,7 @@ describe('Page', function () { describe('Page.Events.Popup', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const [popup] = await Promise.all([ waitEvent(page, 'popup'), @@ -221,7 +215,7 @@ describe('Page', function () { ).toBe(true); }); it('should work with noopener', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const [popup] = await Promise.all([ waitEvent(page, 'popup'), @@ -241,7 +235,7 @@ describe('Page', function () { ).toBe(false); }); it('should work with clicking target=_blank and without rel=opener', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setContent('yo'); @@ -261,7 +255,7 @@ describe('Page', function () { ).toBe(false); }); it('should work with clicking target=_blank and with rel=opener', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setContent( @@ -283,7 +277,7 @@ describe('Page', function () { ).toBe(true); }); it('should work with fake-clicking target=_blank and rel=noopener', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setContent( @@ -307,7 +301,7 @@ describe('Page', function () { ).toBe(false); }); it('should work with clicking target=_blank and rel=noopener', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setContent( @@ -340,20 +334,20 @@ describe('Page', function () { } it('should be prompt by default', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); expect(await getPermission(page, 'geolocation')).toBe('prompt'); }); it('should deny permission when not listed', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); await page.goto(server.EMPTY_PAGE); await context.overridePermissions(server.EMPTY_PAGE, []); expect(await getPermission(page, 'geolocation')).toBe('denied'); }); it('should fail when bad permission is given', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); await page.goto(server.EMPTY_PAGE); let error!: Error; @@ -366,14 +360,14 @@ describe('Page', function () { expect(error.message).toBe('Unknown permission: foo'); }); it('should grant permission when listed', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); await page.goto(server.EMPTY_PAGE); await context.overridePermissions(server.EMPTY_PAGE, ['geolocation']); expect(await getPermission(page, 'geolocation')).toBe('granted'); }); it('should reset permissions', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); await page.goto(server.EMPTY_PAGE); await context.overridePermissions(server.EMPTY_PAGE, ['geolocation']); @@ -382,7 +376,7 @@ describe('Page', function () { expect(await getPermission(page, 'geolocation')).toBe('prompt'); }); it('should trigger permission onchange', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.evaluate(() => { @@ -421,7 +415,7 @@ describe('Page', function () { ).toEqual(['prompt', 'denied', 'granted', 'prompt']); }); it('should isolate permissions between browser contexts', async () => { - const {page, server, context, browser} = getTestState(); + const {page, server, context, browser} = await getTestState(); await page.goto(server.EMPTY_PAGE); const otherContext = await browser.createIncognitoBrowserContext(); @@ -444,7 +438,7 @@ describe('Page', function () { await otherContext.close(); }); it('should grant persistent-storage', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); await page.goto(server.EMPTY_PAGE); expect(await getPermission(page, 'persistent-storage')).not.toBe( @@ -459,7 +453,7 @@ describe('Page', function () { describe('Page.setGeolocation', function () { it('should work', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); await context.overridePermissions(server.PREFIX, ['geolocation']); await page.goto(server.EMPTY_PAGE); @@ -480,7 +474,7 @@ describe('Page', function () { }); }); it('should throw when invalid longitude', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; try { @@ -494,7 +488,7 @@ describe('Page', function () { describe('Page.setOfflineMode', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setOfflineMode(true); let error!: Error; @@ -507,7 +501,7 @@ describe('Page', function () { expect(response.status()).toBe(200); }); it('should emulate navigator.onLine', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); expect( await page.evaluate(() => { @@ -531,7 +525,7 @@ describe('Page', function () { describe('ExecutionContext.queryObjects', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); // Create a custom class const classHandle = await page.evaluateHandle(() => { @@ -564,7 +558,7 @@ describe('Page', function () { ).resolves.toBeTruthy(); }); it('should work for non-trivial page', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); // Create a custom class @@ -598,7 +592,7 @@ describe('Page', function () { ).resolves.toBeTruthy(); }); it('should fail for disposed handles', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const prototypeHandle = await page.evaluateHandle(() => { return HTMLBodyElement.prototype; @@ -611,7 +605,7 @@ describe('Page', function () { expect(error.message).toBe('Prototype JSHandle is disposed!'); }); it('should fail primitive values as prototypes', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const prototypeHandle = await page.evaluateHandle(() => { return 42; @@ -628,7 +622,7 @@ describe('Page', function () { describe('Page.Events.Console', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const [message] = await Promise.all([ waitEvent(page, 'console'), @@ -650,7 +644,7 @@ describe('Page', function () { expect(await message.args()[2]!.jsonValue()).toEqual({foo: 'bar'}); }); it('should work on script call right after navigation', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const [message] = await Promise.all([ waitEvent(page, 'console'), @@ -663,7 +657,7 @@ describe('Page', function () { expect(message.text()).toEqual('SOME_LOG_MESSAGE'); }); it('should work for different console API calls with logging functions', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const messages: any[] = []; page.on('console', msg => { @@ -695,7 +689,7 @@ describe('Page', function () { ]); }); it('should work for different console API calls with timing functions', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const messages: any[] = []; page.on('console', msg => { @@ -715,7 +709,7 @@ describe('Page', function () { expect(messages[0]!.text()).toContain('calling console.time'); }); it('should not fail for window object', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const [message] = await Promise.all([ waitEvent(page, 'console'), @@ -729,7 +723,7 @@ describe('Page', function () { ]); }); it('should trigger correct Log', async () => { - const {page, server, isChrome} = getTestState(); + const {page, server, isChrome} = await getTestState(); await page.goto('about:blank'); const [message] = await Promise.all([ @@ -746,7 +740,7 @@ describe('Page', function () { } }); it('should have location when fetch fails', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // The point of this test is to make sure that we report console messages from // Log domain: https://vanilla.aslushnikov.com/?Log.entryAdded @@ -763,7 +757,7 @@ describe('Page', function () { }); }); it('should have location and stack trace for console API calls', async () => { - const {page, server, isChrome} = getTestState(); + const {page, server, isChrome} = await getTestState(); await page.goto(server.EMPTY_PAGE); const [message] = await Promise.all([ @@ -797,7 +791,7 @@ describe('Page', function () { }); // @see https://github.com/puppeteer/puppeteer/issues/3865 it('should not throw when there are console messages in detached iframes', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.evaluate(async () => { @@ -832,7 +826,7 @@ describe('Page', function () { describe('Page.Events.DOMContentLoaded', function () { it('should fire when expected', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); page.goto('about:blank'); await waitEvent(page, 'domcontentloaded'); @@ -841,14 +835,14 @@ describe('Page', function () { describe('Page.metrics', function () { it('should get metrics from a page', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.goto('about:blank'); const metrics = await page.metrics(); checkMetrics(metrics); }); it('metrics event fired on console.timeStamp', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const metricsPromise = waitEvent<{metrics: Metrics; title: string}>( page, @@ -889,7 +883,7 @@ describe('Page', function () { describe('Page.waitForRequest', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const [request] = await Promise.all([ @@ -903,7 +897,7 @@ describe('Page', function () { expect(request.url()).toBe(server.PREFIX + '/digits/2.png'); }); it('should work with predicate', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const [request] = await Promise.all([ @@ -919,7 +913,7 @@ describe('Page', function () { expect(request.url()).toBe(server.PREFIX + '/digits/2.png'); }); it('should work with async predicate', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const [request] = await Promise.all([ @@ -935,7 +929,7 @@ describe('Page', function () { expect(request.url()).toBe(server.PREFIX + '/digits/2.png'); }); it('should respect timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page @@ -951,7 +945,7 @@ describe('Page', function () { expect(error).toBeInstanceOf(TimeoutError); }); it('should respect default timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; page.setDefaultTimeout(1); @@ -965,7 +959,7 @@ describe('Page', function () { expect(error).toBeInstanceOf(TimeoutError); }); it('should work with no timeout', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const [request] = await Promise.all([ @@ -984,7 +978,7 @@ describe('Page', function () { describe('Page.waitForResponse', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const [response] = await Promise.all([ @@ -998,7 +992,7 @@ describe('Page', function () { expect(response.url()).toBe(server.PREFIX + '/digits/2.png'); }); it('should respect timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page @@ -1014,7 +1008,7 @@ describe('Page', function () { expect(error).toBeInstanceOf(TimeoutError); }); it('should respect default timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; page.setDefaultTimeout(1); @@ -1028,7 +1022,7 @@ describe('Page', function () { expect(error).toBeInstanceOf(TimeoutError); }); it('should work with predicate', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const [response] = await Promise.all([ @@ -1044,7 +1038,7 @@ describe('Page', function () { expect(response.url()).toBe(server.PREFIX + '/digits/2.png'); }); it('should work with async predicate', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const [response] = await Promise.all([ page.waitForResponse(async response => { @@ -1059,7 +1053,7 @@ describe('Page', function () { expect(response.url()).toBe(server.PREFIX + '/digits/2.png'); }); it('should work with no timeout', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const [response] = await Promise.all([ @@ -1078,7 +1072,7 @@ describe('Page', function () { describe('Page.waitForNetworkIdle', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); let res; const [t1, t2] = await Promise.all([ @@ -1112,7 +1106,7 @@ describe('Page', function () { expect(t1 - t2).toBeGreaterThanOrEqual(400); }); it('should respect timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page.waitForNetworkIdle({timeout: 1}).catch(error_ => { return (error = error_); @@ -1120,7 +1114,7 @@ describe('Page', function () { expect(error).toBeInstanceOf(TimeoutError); }); it('should respect idleTime', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const [t1, t2] = await Promise.all([ page.waitForNetworkIdle({idleTime: 10}).then(() => { @@ -1145,7 +1139,7 @@ describe('Page', function () { expect(t2).toBeGreaterThan(t1); }); it('should work with no timeout', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const [result] = await Promise.all([ page.waitForNetworkIdle({timeout: 0}), @@ -1160,7 +1154,7 @@ describe('Page', function () { expect(result).toBe(undefined); }); it('should work with aborted requests', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/abort-request.html'); @@ -1178,7 +1172,7 @@ describe('Page', function () { describe('Page.exposeFunction', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.exposeFunction('compute', function (a: number, b: number) { return a * b; @@ -1189,7 +1183,7 @@ describe('Page', function () { expect(result).toBe(36); }); it('should throw exception in page context', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.exposeFunction('woof', () => { throw new Error('WOOF WOOF'); @@ -1208,7 +1202,7 @@ describe('Page', function () { expect(stack).toContain('page.spec.ts'); }); it('should support throwing "null"', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.exposeFunction('woof', function () { throw null; @@ -1224,7 +1218,7 @@ describe('Page', function () { expect(thrown).toBe(null); }); it('should be callable from-inside evaluateOnNewDocument', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let called = false; await page.exposeFunction('woof', function () { @@ -1237,7 +1231,7 @@ describe('Page', function () { expect(called).toBe(true); }); it('should survive navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.exposeFunction('compute', function (a: number, b: number) { return a * b; @@ -1250,7 +1244,7 @@ describe('Page', function () { expect(result).toBe(36); }); it('should await returned promise', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.exposeFunction('compute', function (a: number, b: number) { return Promise.resolve(a * b); @@ -1262,7 +1256,7 @@ describe('Page', function () { expect(result).toBe(15); }); it('should work on frames', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.exposeFunction('compute', function (a: number, b: number) { return Promise.resolve(a * b); @@ -1276,7 +1270,7 @@ describe('Page', function () { expect(result).toBe(15); }); it('should work on frames before navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/frames/nested-frames.html'); await page.exposeFunction('compute', function (a: number, b: number) { @@ -1290,7 +1284,7 @@ describe('Page', function () { expect(result).toBe(15); }); it('should not throw when frames detach', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await attachFrame(page, 'frame1', server.EMPTY_PAGE); @@ -1306,7 +1300,7 @@ describe('Page', function () { ).resolves.toEqual(15); }); it('should work with complex objects', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.exposeFunction( 'complexObject', @@ -1320,7 +1314,7 @@ describe('Page', function () { expect(result.x).toBe(7); }); it('should fallback to default export when passed a module object', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const moduleObject = { default: function (a: number, b: number) { return a * b; @@ -1337,7 +1331,7 @@ describe('Page', function () { describe('Page.removeExposedFunction', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.exposeFunction('compute', function (a: number, b: number) { return a * b; @@ -1362,7 +1356,7 @@ describe('Page', function () { describe('Page.Events.PageError', function () { it('should fire', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const [error] = await Promise.all([ waitEvent(page, 'pageerror'), @@ -1374,7 +1368,7 @@ describe('Page', function () { describe('Page.setUserAgent', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); expect( await page.evaluate(() => { @@ -1389,7 +1383,7 @@ describe('Page', function () { expect(request.headers['user-agent']).toBe('foobar'); }); it('should work for subframes', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); expect( await page.evaluate(() => { @@ -1404,7 +1398,7 @@ describe('Page', function () { expect(request.headers['user-agent']).toBe('foobar'); }); it('should emulate device user-agent', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/mobile.html'); expect( @@ -1420,7 +1414,7 @@ describe('Page', function () { ).toContain('iPhone'); }); it('should work with additional userAgentMetdata', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setUserAgent('MockBrowser', { architecture: 'Mock1', @@ -1463,14 +1457,14 @@ describe('Page', function () { const expectedOutput = '
hello
'; it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
hello
'); const result = await page.content(); expect(result).toBe(expectedOutput); }); it('should work with doctype', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const doctype = ''; await page.setContent(`${doctype}
hello
`); @@ -1478,7 +1472,7 @@ describe('Page', function () { expect(result).toBe(`${doctype}${expectedOutput}`); }); it('should work with HTML 4 doctype', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const doctype = ' { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const imgPath = '/img.png'; // stall for image @@ -1504,7 +1498,7 @@ describe('Page', function () { expect(error).toBeInstanceOf(TimeoutError); }); it('should respect default navigation timeout', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); page.setDefaultNavigationTimeout(1); const imgPath = '/img.png'; @@ -1519,7 +1513,7 @@ describe('Page', function () { expect(error).toBeInstanceOf(TimeoutError); }); it('should await resources to load', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const imgPath = '/img.png'; let imgResponse!: ServerResponse; @@ -1538,14 +1532,14 @@ describe('Page', function () { await contentPromise; }); it('should work fast enough', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); for (let i = 0; i < 20; ++i) { await page.setContent('
yo
'); } }); it('should work with tricky content', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
hello world
' + '\x7F'); expect( @@ -1555,7 +1549,7 @@ describe('Page', function () { ).toBe('hello world'); }); it('should work with accents', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
aberración
'); expect( @@ -1565,7 +1559,7 @@ describe('Page', function () { ).toBe('aberración'); }); it('should work with emojis', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
🐥
'); expect( @@ -1575,7 +1569,7 @@ describe('Page', function () { ).toBe('🐥'); }); it('should work with newline', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
\n
'); expect( @@ -1585,7 +1579,7 @@ describe('Page', function () { ).toBe('\n'); }); it('should work with comments outside HTML tag', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const comment = ''; await page.setContent(`${comment}
hello
`); @@ -1596,7 +1590,7 @@ describe('Page', function () { describe('Page.setBypassCSP', function () { it('should bypass CSP meta tag', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Make sure CSP prohibits addScriptTag. await page.goto(server.PREFIX + '/csp.html'); @@ -1623,7 +1617,7 @@ describe('Page', function () { }); it('should bypass CSP header', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Make sure CSP prohibits addScriptTag. server.setCSP('/empty.html', 'default-src "self"'); @@ -1651,7 +1645,7 @@ describe('Page', function () { }); it('should bypass after cross-process navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setBypassCSP(true); await page.goto(server.PREFIX + '/csp.html'); @@ -1671,7 +1665,7 @@ describe('Page', function () { ).toBe(42); }); it('should bypass CSP in iframes as well', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); { @@ -1719,7 +1713,7 @@ describe('Page', function () { describe('Page.addScriptTag', function () { it('should throw an error if no options are provided', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; try { @@ -1734,7 +1728,7 @@ describe('Page', function () { }); it('should work with a url', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const scriptHandle = await page.addScriptTag({url: '/injectedfile.js'}); @@ -1747,7 +1741,7 @@ describe('Page', function () { }); it('should work with a url and type=module', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.addScriptTag({url: '/es6/es6import.js', type: 'module'}); @@ -1759,7 +1753,7 @@ describe('Page', function () { }); it('should work with a path and type=module', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.addScriptTag({ @@ -1777,7 +1771,7 @@ describe('Page', function () { }); it('should work with a content and type=module', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.addScriptTag({ @@ -1795,7 +1789,7 @@ describe('Page', function () { }); it('should throw an error if loading from url fail', async () => { - const {page, server, isFirefox} = getTestState(); + const {page, server, isFirefox} = await getTestState(); await page.goto(server.EMPTY_PAGE); let error!: Error; @@ -1812,7 +1806,7 @@ describe('Page', function () { }); it('should work with a path', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const scriptHandle = await page.addScriptTag({ @@ -1827,7 +1821,7 @@ describe('Page', function () { }); it('should include sourcemap when path is provided', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.addScriptTag({ @@ -1840,7 +1834,7 @@ describe('Page', function () { }); it('should work with content', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const scriptHandle = await page.addScriptTag({ @@ -1855,7 +1849,7 @@ describe('Page', function () { }); it('should add id when provided', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.addScriptTag({content: 'window.__injected = 1;', id: 'one'}); await page.addScriptTag({url: '/injectedfile.js', id: 'two'}); @@ -1865,7 +1859,7 @@ describe('Page', function () { // @see https://github.com/puppeteer/puppeteer/issues/4840 it('should throw when added with content to the CSP page', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/csp.html'); let error!: Error; @@ -1878,7 +1872,7 @@ describe('Page', function () { }); it('should throw when added with URL to the CSP page', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/csp.html'); let error!: Error; @@ -1893,7 +1887,7 @@ describe('Page', function () { describe('Page.addStyleTag', function () { it('should throw an error if no options are provided', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; try { @@ -1908,7 +1902,7 @@ describe('Page', function () { }); it('should work with a url', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const styleHandle = await page.addStyleTag({url: '/injectedstyle.css'}); @@ -1921,7 +1915,7 @@ describe('Page', function () { }); it('should throw an error if loading from url fail', async () => { - const {page, server, isFirefox} = getTestState(); + const {page, server, isFirefox} = await getTestState(); await page.goto(server.EMPTY_PAGE); let error!: Error; @@ -1938,7 +1932,7 @@ describe('Page', function () { }); it('should work with a path', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const styleHandle = await page.addStyleTag({ @@ -1953,7 +1947,7 @@ describe('Page', function () { }); it('should include sourcemap when path is provided', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.addStyleTag({ @@ -1967,7 +1961,7 @@ describe('Page', function () { }); it('should work with content', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const styleHandle = await page.addStyleTag({ @@ -1982,7 +1976,7 @@ describe('Page', function () { }); it('should throw when added with content to the CSP page', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/csp.html'); let error!: Error; @@ -1995,7 +1989,7 @@ describe('Page', function () { }); it('should throw when added with URL to the CSP page', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/csp.html'); let error!: Error; @@ -2012,7 +2006,7 @@ describe('Page', function () { describe('Page.url', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); expect(page.url()).toBe('about:blank'); await page.goto(server.EMPTY_PAGE); @@ -2022,7 +2016,7 @@ describe('Page', function () { describe('Page.setJavaScriptEnabled', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setJavaScriptEnabled(false); await page.goto( @@ -2044,7 +2038,7 @@ describe('Page', function () { describe('Page.setCacheEnabled', function () { it('should enable or disable the cache based on the state passed', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/cached/one-style.html'); const [cachedRequest] = await Promise.all([ @@ -2062,7 +2056,7 @@ describe('Page', function () { expect(nonCachedRequest.headers['if-modified-since']).toBe(undefined); }); it('should stay disabled when toggling request interception on/off', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setCacheEnabled(false); await page.setRequestInterception(true); @@ -2079,7 +2073,7 @@ describe('Page', function () { describe('Page.pdf', function () { it('can print to PDF and save to file', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const outputFile = __dirname + '/../assets/output.pdf'; await page.goto(server.PREFIX + '/pdf.html'); @@ -2089,7 +2083,7 @@ describe('Page', function () { }); it('can print to PDF and stream the result', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const stream = await page.createPDFStream(); let size = 0; @@ -2100,7 +2094,7 @@ describe('Page', function () { }); it('should respect timeout', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/pdf.html'); @@ -2114,7 +2108,7 @@ describe('Page', function () { describe('Page.title', function () { it('should return the page title', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/title.html'); expect(await page.title()).toBe('Woof-Woof'); @@ -2123,7 +2117,7 @@ describe('Page', function () { describe('Page.select', function () { it('should select single option', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/select.html'); await page.select('select', 'blue'); @@ -2139,7 +2133,7 @@ describe('Page', function () { ).toEqual(['blue']); }); it('should select only first option', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/select.html'); await page.select('select', 'blue', 'green', 'red'); @@ -2155,7 +2149,7 @@ describe('Page', function () { ).toEqual(['blue']); }); it('should not throw when select causes navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/select.html'); await page.$eval('select', select => { @@ -2170,7 +2164,7 @@ describe('Page', function () { expect(page.url()).toContain('empty.html'); }); it('should select multiple options', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/select.html'); await page.evaluate(() => { @@ -2189,7 +2183,7 @@ describe('Page', function () { ).toEqual(['blue', 'green', 'red']); }); it('should respect event bubbling', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/select.html'); await page.select('select', 'blue'); @@ -2205,7 +2199,7 @@ describe('Page', function () { ).toEqual(['blue']); }); it('should throw when element is not a element.'); }); it('should return [] on no matched values', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/select.html'); const result = await page.select('select', '42', 'abc'); expect(result).toEqual([]); }); it('should return an array of matched values', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/select.html'); await page.evaluate(() => { @@ -2236,7 +2230,7 @@ describe('Page', function () { ).toEqual(true); }); it('should return an array of one element when multiple is not set', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/select.html'); const result = await page.select( @@ -2249,14 +2243,14 @@ describe('Page', function () { expect(result).toHaveLength(1); }); it('should return [] on no values', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/select.html'); const result = await page.select('select'); expect(result).toEqual([]); }); it('should deselect all options when passed no values for a multiple select', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/select.html'); await page.evaluate(() => { @@ -2275,7 +2269,7 @@ describe('Page', function () { ).toEqual(true); }); it('should deselect all options when passed no values for a select without multiple', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/select.html'); await page.select('select', 'blue', 'black', 'magenta'); @@ -2291,7 +2285,7 @@ describe('Page', function () { ).toEqual(''); }); it('should throw if passed in non-strings', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(''); let error!: Error; @@ -2305,7 +2299,7 @@ describe('Page', function () { }); // @see https://github.com/puppeteer/puppeteer/issues/3327 it('should work when re-defining top-level Event class', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/input/select.html'); await page.evaluate(() => { @@ -2328,7 +2322,7 @@ describe('Page', function () { describe('Page.Events.Close', function () { it('should work with window.close', async () => { - const {page, context} = getTestState(); + const {page, context} = await getTestState(); const newPagePromise = new Promise(fulfill => { return context.once('targetcreated', target => { @@ -2346,7 +2340,7 @@ describe('Page', function () { await closedPromise; }); it('should work with page.close', async () => { - const {context} = getTestState(); + const {context} = await getTestState(); const newPage = await context.newPage(); const closedPromise = waitEvent(newPage, 'close'); @@ -2357,7 +2351,7 @@ describe('Page', function () { describe('Page.browser', function () { it('should return the correct browser instance', async () => { - const {page, browser} = getTestState(); + const {page, browser} = await getTestState(); expect(page.browser()).toBe(browser); }); @@ -2365,7 +2359,7 @@ describe('Page', function () { describe('Page.browserContext', function () { it('should return the correct browser context instance', async () => { - const {page, context} = getTestState(); + const {page, context} = await getTestState(); expect(page.browserContext()).toBe(context); }); @@ -2373,7 +2367,7 @@ describe('Page', function () { describe('Page.client', function () { it('should return the client instance', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); expect((page as CDPPage)._client()).toBeInstanceOf(CDPSession); }); }); diff --git a/test/src/proxy.spec.ts b/test/src/proxy.spec.ts index 6688534f0b2..5c117be2af3 100644 --- a/test/src/proxy.spec.ts +++ b/test/src/proxy.spec.ts @@ -109,11 +109,11 @@ describe('request proxy', () => { }); it('should proxy requests when configured', async () => { - const {defaultBrowserOptions, server} = getTestState(); + const {server} = await getTestState({ + skipLaunch: true, + }); const emptyPageUrl = getEmptyPageUrl(server); - const {browser, close} = await launch({ - ...defaultBrowserOptions, args: [...defaultArgs, `--proxy-server=${proxyServerUrl}`], }); try { @@ -128,11 +128,11 @@ describe('request proxy', () => { }); it('should respect proxy bypass list', async () => { - const {defaultBrowserOptions, server} = getTestState(); + const {server} = await getTestState({ + skipLaunch: true, + }); const emptyPageUrl = getEmptyPageUrl(server); - const {browser, close} = await launch({ - ...defaultBrowserOptions, args: [ ...defaultArgs, `--proxy-server=${proxyServerUrl}`, @@ -152,11 +152,11 @@ describe('request proxy', () => { describe('in incognito browser context', () => { it('should proxy requests when configured at browser level', async () => { - const {defaultBrowserOptions, server} = getTestState(); + const {server} = await getTestState({ + skipLaunch: true, + }); const emptyPageUrl = getEmptyPageUrl(server); - const {browser, close} = await launch({ - ...defaultBrowserOptions, args: [...defaultArgs, `--proxy-server=${proxyServerUrl}`], }); try { @@ -172,11 +172,11 @@ describe('request proxy', () => { }); it('should respect proxy bypass list when configured at browser level', async () => { - const {defaultBrowserOptions, server} = getTestState(); + const {server} = await getTestState({ + skipLaunch: true, + }); const emptyPageUrl = getEmptyPageUrl(server); - const {browser, close} = await launch({ - ...defaultBrowserOptions, args: [ ...defaultArgs, `--proxy-server=${proxyServerUrl}`, @@ -199,11 +199,11 @@ describe('request proxy', () => { * See issues #7873, #7719, and #7698. */ it('should proxy requests when configured at context level', async () => { - const {defaultBrowserOptions, server} = getTestState(); + const {server} = await getTestState({ + skipLaunch: true, + }); const emptyPageUrl = getEmptyPageUrl(server); - const {browser, close} = await launch({ - ...defaultBrowserOptions, args: defaultArgs, }); try { @@ -221,11 +221,11 @@ describe('request proxy', () => { }); it('should respect proxy bypass list when configured at context level', async () => { - const {defaultBrowserOptions, server} = getTestState(); + const {server} = await getTestState({ + skipLaunch: true, + }); const emptyPageUrl = getEmptyPageUrl(server); - const {browser, close} = await launch({ - ...defaultBrowserOptions, args: defaultArgs, }); try { diff --git a/test/src/queryhandler.spec.ts b/test/src/queryhandler.spec.ts index 4f8e30919a0..75f4be00d31 100644 --- a/test/src/queryhandler.spec.ts +++ b/test/src/queryhandler.spec.ts @@ -19,20 +19,13 @@ import expect from 'expect'; import {Puppeteer} from 'puppeteer-core'; import {ElementHandle} from 'puppeteer-core/internal/api/ElementHandle.js'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; describe('Query handler tests', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - describe('Pierce selectors', function () { - beforeEach(async () => { - const {page} = getTestState(); - await page.setContent( + async function setUpPage(): ReturnType { + const state = await getTestState(); + await state.page.setContent( `` ); - }); + return state; + } it('should find first element in shadow', async () => { - const {page} = getTestState(); + const {page} = await setUpPage(); const div = (await page.$('pierce/.foo')) as ElementHandle; const text = await div.evaluate(element => { return element.textContent; @@ -57,7 +51,7 @@ describe('Query handler tests', function () { expect(text).toBe('Hello'); }); it('should find all elements in shadow', async () => { - const {page} = getTestState(); + const {page} = await setUpPage(); const divs = (await page.$$('pierce/.foo')) as Array< ElementHandle >; @@ -71,7 +65,7 @@ describe('Query handler tests', function () { expect(text.join(' ')).toBe('Hello World'); }); it('should find first child element', async () => { - const {page} = getTestState(); + const {page} = await setUpPage(); const parentElement = (await page.$('html > div'))!; const childElement = (await parentElement.$( 'pierce/div' @@ -82,7 +76,7 @@ describe('Query handler tests', function () { expect(text).toBe('Hello'); }); it('should find all child elements', async () => { - const {page} = getTestState(); + const {page} = await setUpPage(); const parentElement = (await page.$('html > div'))!; const childElements = (await parentElement.$$('pierce/div')) as Array< ElementHandle @@ -101,7 +95,7 @@ describe('Query handler tests', function () { describe('Text selectors', function () { describe('in Page', function () { it('should query existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
test
'); @@ -109,13 +103,13 @@ describe('Query handler tests', function () { expect(await page.$$('text/test')).toHaveLength(1); }); it('should return empty array for non-existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); expect(await page.$('text/test')).toBeFalsy(); expect(await page.$$('text/test')).toHaveLength(0); }); it('should return first element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
a
a
'); @@ -127,7 +121,7 @@ describe('Query handler tests', function () { ).toBe('1'); }); it('should return multiple elements', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
a
a
'); @@ -135,7 +129,7 @@ describe('Query handler tests', function () { expect(elements).toHaveLength(2); }); it('should pierce shadow DOM', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.evaluate(() => { const div = document.createElement('div'); @@ -157,7 +151,7 @@ describe('Query handler tests', function () { ).toBe('a'); }); it('should query deeply nested text', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
a
b
'); @@ -169,7 +163,7 @@ describe('Query handler tests', function () { ).toBe('a'); }); it('should query inputs', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(''); @@ -183,14 +177,14 @@ describe('Query handler tests', function () { ).toBe('a'); }); it('should not query radio', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(''); expect(await page.$('text/a')).toBeNull(); }); it('should query text spanning multiple elements', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
a b
'); @@ -202,7 +196,7 @@ describe('Query handler tests', function () { ).toBe('a b'); }); it('should clear caches', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
text
text
' @@ -271,7 +265,7 @@ describe('Query handler tests', function () { }); describe('in ElementHandles', function () { it('should query existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
a
'); @@ -281,7 +275,7 @@ describe('Query handler tests', function () { }); it('should return null for non-existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
'); @@ -295,7 +289,7 @@ describe('Query handler tests', function () { describe('XPath selectors', function () { describe('in Page', function () { it('should query existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
test
'); @@ -303,7 +297,7 @@ describe('Query handler tests', function () { expect(await page.$$('xpath/html/body/section')).toHaveLength(1); }); it('should return empty array for non-existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); expect( await page.$('xpath/html/body/non-existing-element') @@ -313,7 +307,7 @@ describe('Query handler tests', function () { ).toHaveLength(0); }); it('should return first element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
a
'); @@ -325,7 +319,7 @@ describe('Query handler tests', function () { ).toBeTruthy(); }); it('should return multiple elements', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
'); @@ -335,7 +329,7 @@ describe('Query handler tests', function () { }); describe('in ElementHandles', function () { it('should query existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
a
'); @@ -345,7 +339,7 @@ describe('Query handler tests', function () { }); it('should return null for non-existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
a
'); @@ -358,13 +352,12 @@ describe('Query handler tests', function () { describe('P selectors', () => { beforeEach(async () => { - const {page, server} = getTestState(); - await page.goto(`${server.PREFIX}/p-selectors.html`); Puppeteer.clearCustomQueryHandlers(); }); it('should work with CSS selectors', async () => { - const {page} = getTestState(); + const {server, page} = await getTestState(); + await page.goto(`${server.PREFIX}/p-selectors.html`); const element = await page.$('div > button'); assert(element, 'Could not find element'); expect( @@ -385,7 +378,8 @@ describe('Query handler tests', function () { }); it('should work with deep combinators', async () => { - const {page} = getTestState(); + const {server, page} = await getTestState(); + await page.goto(`${server.PREFIX}/p-selectors.html`); { const element = await page.$('div >>>> div'); assert(element, 'Could not find element'); @@ -425,7 +419,8 @@ describe('Query handler tests', function () { }); it('should work with text selectors', async () => { - const {page} = getTestState(); + const {server, page} = await getTestState(); + await page.goto(`${server.PREFIX}/p-selectors.html`); const element = await page.$('div ::-p-text(world)'); assert(element, 'Could not find element'); expect( @@ -436,7 +431,8 @@ describe('Query handler tests', function () { }); it('should work ARIA selectors', async () => { - const {page} = getTestState(); + const {server, page} = await getTestState(); + await page.goto(`${server.PREFIX}/p-selectors.html`); const element = await page.$('div ::-p-aria(world)'); assert(element, 'Could not find element'); expect( @@ -447,7 +443,8 @@ describe('Query handler tests', function () { }); it('should work for ARIA selectors in multiple isolated worlds', async () => { - const {page} = getTestState(); + const {server, page} = await getTestState(); + await page.goto(`${server.PREFIX}/p-selectors.html`); let element = await page.waitForSelector('::-p-aria(world)'); assert(element, 'Could not find element'); expect( @@ -467,7 +464,8 @@ describe('Query handler tests', function () { }); it('should work ARIA selectors with role', async () => { - const {page} = getTestState(); + const {server, page} = await getTestState(); + await page.goto(`${server.PREFIX}/p-selectors.html`); const element = await page.$('::-p-aria(world[role="button"])'); assert(element, 'Could not find element'); expect( @@ -478,7 +476,8 @@ describe('Query handler tests', function () { }); it('should work ARIA selectors with name and role', async () => { - const {page} = getTestState(); + const {server, page} = await getTestState(); + await page.goto(`${server.PREFIX}/p-selectors.html`); const element = await page.$('::-p-aria([name="world"][role="button"])'); assert(element, 'Could not find element'); expect( @@ -489,7 +488,8 @@ describe('Query handler tests', function () { }); it('should work XPath selectors', async () => { - const {page} = getTestState(); + const {server, page} = await getTestState(); + await page.goto(`${server.PREFIX}/p-selectors.html`); const element = await page.$('div ::-p-xpath(//button)'); assert(element, 'Could not find element'); expect( @@ -506,7 +506,8 @@ describe('Query handler tests', function () { }, }); - const {page} = getTestState(); + const {server, page} = await getTestState(); + await page.goto(`${server.PREFIX}/p-selectors.html`); const element = await page.$('::-p-div'); assert(element, 'Could not find element'); expect( @@ -517,7 +518,8 @@ describe('Query handler tests', function () { }); it('should work with custom selectors with args', async () => { - const {page} = getTestState(); + const {server, page} = await getTestState(); + await page.goto(`${server.PREFIX}/p-selectors.html`); Puppeteer.registerCustomQueryHandler('div', { queryOne(_, selector) { if (selector === 'true') { @@ -567,7 +569,8 @@ describe('Query handler tests', function () { }); it('should work with :hover', async () => { - const {page} = getTestState(); + const {server, page} = await getTestState(); + await page.goto(`${server.PREFIX}/p-selectors.html`); let button = await page.$('div ::-p-text(world)'); assert(button, 'Could not find element'); await button.hover(); @@ -582,7 +585,8 @@ describe('Query handler tests', function () { }); it('should work with selector lists', async () => { - const {page} = getTestState(); + const {server, page} = await getTestState(); + await page.goto(`${server.PREFIX}/p-selectors.html`); const elements = await page.$$('div, ::-p-text(world)'); expect(elements).toHaveLength(3); }); @@ -606,7 +610,8 @@ describe('Query handler tests', function () { }; it('should match querySelector* ordering', async () => { - const {page} = getTestState(); + const {server, page} = await getTestState(); + await page.goto(`${server.PREFIX}/p-selectors.html`); for (const list of permute(['div', 'button', 'span'])) { const elements = await page.$$( list @@ -627,7 +632,8 @@ describe('Query handler tests', function () { }); it('should not have duplicate elements from selector lists', async () => { - const {page} = getTestState(); + const {server, page} = await getTestState(); + await page.goto(`${server.PREFIX}/p-selectors.html`); const elements = await page.$$('::-p-text(world), button'); expect(elements).toHaveLength(1); }); diff --git a/test/src/queryselector.spec.ts b/test/src/queryselector.spec.ts index 190578bd591..58ca2207e26 100644 --- a/test/src/queryselector.spec.ts +++ b/test/src/queryselector.spec.ts @@ -17,18 +17,12 @@ import expect from 'expect'; import {Puppeteer} from 'puppeteer'; import type {CustomQueryHandler} from 'puppeteer-core/internal/common/CustomQueryHandler.js'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; describe('querySelector', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); describe('Page.$eval', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
43543
'); const idAttribute = await page.$eval('section', e => { @@ -37,7 +31,7 @@ describe('querySelector', function () { expect(idAttribute).toBe('testAttribute'); }); it('should accept arguments', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
hello
'); const text = await page.$eval( @@ -50,7 +44,7 @@ describe('querySelector', function () { expect(text).toBe('hello world!'); }); it('should accept ElementHandles as arguments', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
hello
world
'); const divHandle = (await page.$('div'))!; @@ -64,7 +58,7 @@ describe('querySelector', function () { expect(text).toBe('hello world'); }); it('should throw error if no element is found', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page @@ -85,7 +79,7 @@ describe('querySelector', function () { // as opposed to NodeListOf. describe('Page.$$eval', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
hello
beautiful
world!
' @@ -96,7 +90,7 @@ describe('querySelector', function () { expect(divsCount).toBe(3); }); it('should accept extra arguments', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
hello
beautiful
world!
' ); @@ -111,7 +105,7 @@ describe('querySelector', function () { expect(divsCountPlus5).toBe(8); }); it('should accept ElementHandles as arguments', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
2
2
1
3
' ); @@ -132,7 +126,7 @@ describe('querySelector', function () { it('should handle many elements', async function () { this.timeout(25_000); - const {page} = getTestState(); + const {page} = await getTestState(); await page.evaluate( ` for (var i = 0; i <= 1000; i++) { @@ -153,14 +147,14 @@ describe('querySelector', function () { describe('Page.$', function () { it('should query existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
test
'); const element = (await page.$('section'))!; expect(element).toBeTruthy(); }); it('should return null for non-existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const element = (await page.$('non-existing-element'))!; expect(element).toBe(null); @@ -169,7 +163,7 @@ describe('querySelector', function () { describe('Page.$$', function () { it('should query existing elements', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
A

B
'); const elements = await page.$$('div'); @@ -182,7 +176,7 @@ describe('querySelector', function () { expect(await Promise.all(promises)).toEqual(['A', 'B']); }); it('should return empty array if nothing is found', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const elements = await page.$$('div'); @@ -192,7 +186,7 @@ describe('querySelector', function () { describe('Page.$x', function () { it('should query existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
test
'); const elements = await page.$x('/html/body/section'); @@ -200,13 +194,13 @@ describe('querySelector', function () { expect(elements).toHaveLength(1); }); it('should return empty array for non-existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const element = await page.$x('/html/body/non-existing-element'); expect(element).toEqual([]); }); it('should return multiple elements', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
'); const elements = await page.$x('/html/body/div'); @@ -216,7 +210,7 @@ describe('querySelector', function () { describe('ElementHandle.$', function () { it('should query existing element', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/playground.html'); await page.setContent( @@ -232,7 +226,7 @@ describe('querySelector', function () { }); it('should return null for non-existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
B
' @@ -244,7 +238,7 @@ describe('querySelector', function () { }); describe('ElementHandle.$eval', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
10
' @@ -257,7 +251,7 @@ describe('querySelector', function () { }); it('should retrieve content from subtree', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const htmlContent = '
not-a-child-div
a-child-div
'; @@ -270,7 +264,7 @@ describe('querySelector', function () { }); it('should throw in case of missing selector', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const htmlContent = '
not-a-child-div
'; @@ -290,7 +284,7 @@ describe('querySelector', function () { }); describe('ElementHandle.$$eval', function () { it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
' @@ -305,7 +299,7 @@ describe('querySelector', function () { }); it('should retrieve content from subtree', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const htmlContent = '
not-a-child-div
a1-child-div
a2-child-div
'; @@ -320,7 +314,7 @@ describe('querySelector', function () { }); it('should not throw in case of missing selector', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const htmlContent = '
not-a-child-div
'; @@ -335,7 +329,7 @@ describe('querySelector', function () { describe('ElementHandle.$$', function () { it('should query existing elements', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
A

B
' @@ -352,7 +346,7 @@ describe('querySelector', function () { }); it('should return empty array for non-existing elements', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( 'A
B' @@ -365,7 +359,7 @@ describe('querySelector', function () { describe('ElementHandle.$x', function () { it('should query existing element', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.PREFIX + '/playground.html'); await page.setContent( @@ -381,7 +375,7 @@ describe('querySelector', function () { }); it('should return null for non-existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
B
' @@ -410,7 +404,7 @@ describe('querySelector', function () { ).toBeTruthy(); }); it('$$ should query existing elements', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
A

B
' @@ -427,7 +421,7 @@ describe('querySelector', function () { }); it('$$ should return empty array for non-existing elements', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( 'A
B' @@ -437,7 +431,7 @@ describe('querySelector', function () { expect(elements).toHaveLength(0); }); it('$$eval should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
hello
beautiful
world!
' @@ -448,7 +442,7 @@ describe('querySelector', function () { expect(divsCount).toBe(3); }); it('$$eval should accept extra arguments', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
hello
beautiful
world!
' ); @@ -463,7 +457,7 @@ describe('querySelector', function () { expect(divsCountPlus5).toBe(8); }); it('$$eval should accept ElementHandles as arguments', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
2
2
1
3
' ); @@ -484,7 +478,7 @@ describe('querySelector', function () { it('$$eval should handle many elements', async function () { this.timeout(25_000); - const {page} = getTestState(); + const {page} = await getTestState(); await page.evaluate( ` for (var i = 0; i <= 1000; i++) { diff --git a/test/src/requestinterception-experimental.spec.ts b/test/src/requestinterception-experimental.spec.ts index 62f0cb640e3..4ee0ac57cd5 100644 --- a/test/src/requestinterception-experimental.spec.ts +++ b/test/src/requestinterception-experimental.spec.ts @@ -25,22 +25,16 @@ import { } from 'puppeteer-core/internal/api/HTTPRequest.js'; import {ConsoleMessage} from 'puppeteer-core/internal/common/ConsoleMessage.js'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; import {isFavicon, waitEvent} from './utils.js'; describe('request interception', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); describe('Page.setRequestInterception', function () { const expectedActions: ActionResult[] = ['abort', 'continue', 'respond']; while (expectedActions.length > 0) { const expectedAction = expectedActions.pop(); it(`should cooperatively ${expectedAction} by priority`, async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const actionResults: ActionResult[] = []; await page.setRequestInterception(true); @@ -105,7 +99,7 @@ describe('request interception', function () { } it('should intercept', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -129,7 +123,7 @@ describe('request interception', function () { }); // @see https://github.com/puppeteer/puppeteer/pull/3105 it('should work when POST is redirected with 302', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRedirect('/rredirect', '/empty.html'); await page.goto(server.EMPTY_PAGE); @@ -151,7 +145,7 @@ describe('request interception', function () { }); // @see https://github.com/puppeteer/puppeteer/issues/3973 it('should work when header manipulation headers with redirect', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRedirect('/rrredirect', '/empty.html'); await page.setRequestInterception(true); @@ -168,7 +162,7 @@ describe('request interception', function () { }); // @see https://github.com/puppeteer/puppeteer/issues/4743 it('should be able to remove headers', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -187,7 +181,7 @@ describe('request interception', function () { expect(serverRequest.headers.origin).toBe(undefined); }); it('should contain referer header', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); const requests: HTTPRequest[] = []; @@ -202,7 +196,7 @@ describe('request interception', function () { expect(requests[1]!.headers()['referer']).toContain('/one-style.html'); }); it('should properly return navigation response when URL has cookies', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Setup cookie. await page.goto(server.EMPTY_PAGE); @@ -217,7 +211,7 @@ describe('request interception', function () { expect(response!.status()).toBe(200); }); it('should stop intercepting', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.once('request', request => { @@ -228,7 +222,7 @@ describe('request interception', function () { await page.goto(server.EMPTY_PAGE); }); it('should show custom HTTP headers', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setExtraHTTPHeaders({ foo: 'bar', @@ -243,7 +237,7 @@ describe('request interception', function () { }); // @see https://github.com/puppeteer/puppeteer/issues/4337 it('should work with redirect inside sync XHR', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); server.setRedirect('/logo.png', '/pptr.png'); @@ -260,7 +254,7 @@ describe('request interception', function () { expect(status).toBe(200); }); it('should work with custom referer headers', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setExtraHTTPHeaders({referer: server.EMPTY_PAGE}); await page.setRequestInterception(true); @@ -272,7 +266,7 @@ describe('request interception', function () { expect(response!.ok()).toBe(true); }); it('should be abortable', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -292,7 +286,7 @@ describe('request interception', function () { expect(failedRequests).toBe(1); }); it('should be able to access the error reason', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -307,7 +301,7 @@ describe('request interception', function () { expect(abortReason).toBe('Failed'); }); it('should be abortable with custom error codes', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -324,7 +318,7 @@ describe('request interception', function () { ); }); it('should send referer', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setExtraHTTPHeaders({ referer: 'http://google.com/', @@ -340,7 +334,7 @@ describe('request interception', function () { expect(request.headers['referer']).toBe('http://google.com/'); }); it('should fail navigation when aborting main resource', async () => { - const {page, server, isChrome} = getTestState(); + const {page, server, isChrome} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -358,7 +352,7 @@ describe('request interception', function () { } }); it('should work with redirects', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); const requests: HTTPRequest[] = []; @@ -398,7 +392,7 @@ describe('request interception', function () { } }); it('should work with redirects for subresources', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); const requests: HTTPRequest[] = []; @@ -428,7 +422,7 @@ describe('request interception', function () { expect(redirectChain[2]!.url()).toContain('/three-style.css'); }); it('should be able to abort redirects', async () => { - const {page, server, isChrome} = getTestState(); + const {page, server, isChrome} = await getTestState(); await page.setRequestInterception(true); server.setRedirect('/non-existing.json', '/non-existing-2.json'); @@ -455,7 +449,7 @@ describe('request interception', function () { } }); it('should work with equal requests', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); let responseCount = 1; @@ -502,7 +496,7 @@ describe('request interception', function () { expect(results).toEqual(['11', 'FAILED', '22']); }); it('should navigate to dataURL and fire dataURL requests', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setRequestInterception(true); const requests: HTTPRequest[] = []; @@ -517,7 +511,7 @@ describe('request interception', function () { expect(requests[0]!.url()).toBe(dataURL); }); it('should be able to fetch dataURL and fire dataURL requests', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setRequestInterception(true); @@ -537,7 +531,7 @@ describe('request interception', function () { expect(requests[0]!.url()).toBe(dataURL); }); it('should navigate to URL with hash and fire requests without hash', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); const requests: HTTPRequest[] = []; @@ -552,7 +546,7 @@ describe('request interception', function () { expect(requests[0]!.url()).toBe(server.EMPTY_PAGE); }); it('should work with encoded server', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // The requestWillBeSent will report encoded URL, whereas interception will // report URL as-is. @see crbug.com/759388 @@ -566,7 +560,7 @@ describe('request interception', function () { expect(response!.status()).toBe(404); }); it('should work with badly encoded server', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); server.setRoute('/malformed?rnd=%911', (_req, res) => { @@ -579,7 +573,7 @@ describe('request interception', function () { expect(response!.status()).toBe(200); }); it('should work with encoded server - 2', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // The requestWillBeSent will report URL as-is, whereas interception will // report encoded URL for stylesheet. @see crbug.com/759388 @@ -597,7 +591,7 @@ describe('request interception', function () { expect(requests[1]!.response()!.status()).toBe(404); }); it('should not throw "Invalid Interception Id" if the request was cancelled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setContent(''); await page.setRequestInterception(true); @@ -625,7 +619,7 @@ describe('request interception', function () { expect(error).toBeUndefined(); }); it('should throw if interception is not enabled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let error!: Error; page.on('request', async request => { @@ -639,7 +633,7 @@ describe('request interception', function () { expect(error.message).toContain('Request Interception is not enabled'); }); it('should work with file URLs', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setRequestInterception(true); const urls = new Set(); @@ -655,7 +649,7 @@ describe('request interception', function () { expect(urls.has('one-style.css')).toBe(true); }); it('should not cache if cache disabled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Load and re-load to make sure it's cached. await page.goto(server.PREFIX + '/cached/one-style.html'); @@ -675,7 +669,7 @@ describe('request interception', function () { expect(cached).toHaveLength(0); }); it('should cache if cache enabled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Load and re-load to make sure it's cached. await page.goto(server.PREFIX + '/cached/one-style.html'); @@ -695,7 +689,7 @@ describe('request interception', function () { expect(cached).toHaveLength(1); }); it('should load fonts if cache enabled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); await page.setCacheEnabled(true); @@ -712,7 +706,7 @@ describe('request interception', function () { describe('Request.continue', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -721,7 +715,7 @@ describe('request interception', function () { await page.goto(server.EMPTY_PAGE); }); it('should amend HTTP headers', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -739,7 +733,7 @@ describe('request interception', function () { expect(request.headers['foo']).toBe('bar'); }); it('should redirect in a way non-observable to page', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -757,7 +751,7 @@ describe('request interception', function () { expect(consoleMessage.text()).toBe('yellow'); }); it('should amend method', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); @@ -774,7 +768,7 @@ describe('request interception', function () { expect(request.method).toBe('POST'); }); it('should amend post data', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); @@ -791,7 +785,7 @@ describe('request interception', function () { expect(await serverRequest.postBody).toBe('doggo'); }); it('should amend both post data and method on navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -808,7 +802,7 @@ describe('request interception', function () { describe('Request.respond', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -833,7 +827,7 @@ describe('request interception', function () { ).toBe('Yo, page!'); }); it('should be able to access the response', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -854,7 +848,7 @@ describe('request interception', function () { expect(response).toEqual({status: 200, body: 'Yo, page!'}); }); it('should work with status code 422', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -876,7 +870,7 @@ describe('request interception', function () { ).toBe('Yo, page!'); }); it('should redirect', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -902,7 +896,7 @@ describe('request interception', function () { expect(response!.url()).toBe(server.EMPTY_PAGE); }); it('should allow mocking binary responses', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -929,7 +923,7 @@ describe('request interception', function () { expect(await img.screenshot()).toBeGolden('mock-binary-response.png'); }); it('should stringify intercepted request response headers', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -955,7 +949,7 @@ describe('request interception', function () { ).toBe('Yo, page!'); }); it('should indicate already-handled if an intercept has been handled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { diff --git a/test/src/requestinterception.spec.ts b/test/src/requestinterception.spec.ts index 51e63f4be01..444a7d71f6c 100644 --- a/test/src/requestinterception.spec.ts +++ b/test/src/requestinterception.spec.ts @@ -21,19 +21,13 @@ import expect from 'expect'; import {HTTPRequest} from 'puppeteer-core/internal/api/HTTPRequest.js'; import {ConsoleMessage} from 'puppeteer-core/internal/common/ConsoleMessage.js'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; import {isFavicon, waitEvent} from './utils.js'; describe('request interception', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); describe('Page.setRequestInterception', function () { it('should intercept', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -58,7 +52,7 @@ describe('request interception', function () { }); // @see https://github.com/puppeteer/puppeteer/pull/3105 it('should work when POST is redirected with 302', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRedirect('/rredirect', '/empty.html'); await page.goto(server.EMPTY_PAGE); @@ -80,7 +74,7 @@ describe('request interception', function () { }); // @see https://github.com/puppeteer/puppeteer/issues/3973 it('should work when header manipulation headers with redirect', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setRedirect('/rrredirect', '/empty.html'); await page.setRequestInterception(true); @@ -94,7 +88,7 @@ describe('request interception', function () { }); // @see https://github.com/puppeteer/puppeteer/issues/4743 it('should be able to remove headers', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -113,7 +107,7 @@ describe('request interception', function () { expect(serverRequest.headers.origin).toBe(undefined); }); it('should contain referer header', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); const requests: HTTPRequest[] = []; @@ -128,7 +122,7 @@ describe('request interception', function () { expect(requests[1]!.headers()['referer']).toContain('/one-style.html'); }); it('should work with requests without networkId', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setRequestInterception(true); @@ -144,7 +138,7 @@ describe('request interception', function () { expect(urls).toStrictEqual([server.EMPTY_PAGE]); }); it('should properly return navigation response when URL has cookies', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Setup cookie. await page.goto(server.EMPTY_PAGE); @@ -159,7 +153,7 @@ describe('request interception', function () { expect(response.status()).toBe(200); }); it('should stop intercepting', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.once('request', request => { @@ -170,7 +164,7 @@ describe('request interception', function () { await page.goto(server.EMPTY_PAGE); }); it('should show custom HTTP headers', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setExtraHTTPHeaders({ foo: 'bar', @@ -185,7 +179,7 @@ describe('request interception', function () { }); // @see https://github.com/puppeteer/puppeteer/issues/4337 it('should work with redirect inside sync XHR', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); server.setRedirect('/logo.png', '/pptr.png'); @@ -202,7 +196,7 @@ describe('request interception', function () { expect(status).toBe(200); }); it('should work with custom referer headers', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setExtraHTTPHeaders({referer: server.EMPTY_PAGE}); await page.setRequestInterception(true); @@ -214,7 +208,7 @@ describe('request interception', function () { expect(response.ok()).toBe(true); }); it('should be abortable', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -234,7 +228,7 @@ describe('request interception', function () { expect(failedRequests).toBe(1); }); it('should be abortable with custom error codes', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -251,7 +245,7 @@ describe('request interception', function () { ); }); it('should send referer', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setExtraHTTPHeaders({ referer: 'http://google.com/', @@ -267,7 +261,7 @@ describe('request interception', function () { expect(request.headers['referer']).toBe('http://google.com/'); }); it('should fail navigation when aborting main resource', async () => { - const {page, server, isChrome} = getTestState(); + const {page, server, isChrome} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -285,7 +279,7 @@ describe('request interception', function () { } }); it('should work with redirects', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); const requests: HTTPRequest[] = []; @@ -325,7 +319,7 @@ describe('request interception', function () { } }); it('should work with redirects for subresources', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); const requests: HTTPRequest[] = []; @@ -355,7 +349,7 @@ describe('request interception', function () { expect(redirectChain[2]!.url()).toContain('/three-style.css'); }); it('should be able to abort redirects', async () => { - const {page, server, isChrome} = getTestState(); + const {page, server, isChrome} = await getTestState(); await page.setRequestInterception(true); server.setRedirect('/non-existing.json', '/non-existing-2.json'); @@ -382,7 +376,7 @@ describe('request interception', function () { } }); it('should work with equal requests', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); let responseCount = 1; @@ -429,7 +423,7 @@ describe('request interception', function () { expect(results).toEqual(['11', 'FAILED', '22']); }); it('should navigate to dataURL and fire dataURL requests', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setRequestInterception(true); const requests: HTTPRequest[] = []; @@ -444,7 +438,7 @@ describe('request interception', function () { expect(requests[0]!.url()).toBe(dataURL); }); it('should be able to fetch dataURL and fire dataURL requests', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.setRequestInterception(true); @@ -464,7 +458,7 @@ describe('request interception', function () { expect(requests[0]!.url()).toBe(dataURL); }); it('should navigate to URL with hash and fire requests without hash', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); const requests: HTTPRequest[] = []; @@ -479,7 +473,7 @@ describe('request interception', function () { expect(requests[0]!.url()).toBe(server.EMPTY_PAGE); }); it('should work with encoded server', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // The requestWillBeSent will report encoded URL, whereas interception will // report URL as-is. @see crbug.com/759388 @@ -493,7 +487,7 @@ describe('request interception', function () { expect(response.status()).toBe(404); }); it('should work with badly encoded server', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); server.setRoute('/malformed?rnd=%911', (_req, res) => { @@ -508,7 +502,7 @@ describe('request interception', function () { expect(response.status()).toBe(200); }); it('should work with encoded server - 2', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // The requestWillBeSent will report URL as-is, whereas interception will // report encoded URL for stylesheet. @see crbug.com/759388 @@ -526,7 +520,7 @@ describe('request interception', function () { expect(requests[1]!.response()!.status()).toBe(404); }); it('should not throw "Invalid Interception Id" if the request was cancelled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setContent(''); await page.setRequestInterception(true); @@ -554,7 +548,7 @@ describe('request interception', function () { expect(error).toBeUndefined(); }); it('should throw if interception is not enabled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let error!: Error; page.on('request', async request => { @@ -568,7 +562,7 @@ describe('request interception', function () { expect(error.message).toContain('Request Interception is not enabled'); }); it('should work with file URLs', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setRequestInterception(true); const urls = new Set(); @@ -584,7 +578,7 @@ describe('request interception', function () { expect(urls.has('one-style.css')).toBe(true); }); it('should not cache if cache disabled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Load and re-load to make sure it's cached. await page.goto(server.PREFIX + '/cached/one-style.html'); @@ -604,7 +598,7 @@ describe('request interception', function () { expect(cached).toHaveLength(0); }); it('should cache if cache enabled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); // Load and re-load to make sure it's cached. await page.goto(server.PREFIX + '/cached/one-style.html'); @@ -624,7 +618,7 @@ describe('request interception', function () { expect(cached).toHaveLength(1); }); it('should load fonts if cache enabled', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); await page.setCacheEnabled(true); @@ -642,7 +636,7 @@ describe('request interception', function () { describe('Request.continue', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -651,7 +645,7 @@ describe('request interception', function () { await page.goto(server.EMPTY_PAGE); }); it('should amend HTTP headers', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -669,7 +663,7 @@ describe('request interception', function () { expect(request.headers['foo']).toBe('bar'); }); it('should redirect in a way non-observable to page', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -686,7 +680,7 @@ describe('request interception', function () { expect(consoleMessage.text()).toBe('yellow'); }); it('should amend method', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); @@ -703,7 +697,7 @@ describe('request interception', function () { expect(request.method).toBe('POST'); }); it('should amend post data', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); @@ -720,7 +714,7 @@ describe('request interception', function () { expect(await serverRequest.postBody).toBe('doggo'); }); it('should amend both post data and method on navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -734,7 +728,7 @@ describe('request interception', function () { expect(await serverRequest.postBody).toBe('doggo'); }); it('should fail if the header value is invalid', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let error!: Error; await page.setRequestInterception(true); @@ -757,7 +751,7 @@ describe('request interception', function () { describe('Request.respond', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -779,7 +773,7 @@ describe('request interception', function () { ).toBe('Yo, page!'); }); it('should work with status code 422', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -798,7 +792,7 @@ describe('request interception', function () { ).toBe('Yo, page!'); }); it('should redirect', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -821,7 +815,7 @@ describe('request interception', function () { expect(response.url()).toBe(server.EMPTY_PAGE); }); it('should allow mocking multiple headers with same key', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -852,7 +846,7 @@ describe('request interception', function () { expect(secondCookie?.value).toBe('2'); }); it('should allow mocking binary responses', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -876,7 +870,7 @@ describe('request interception', function () { expect(await img.screenshot()).toBeGolden('mock-binary-response.png'); }); it('should stringify intercepted request response headers', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setRequestInterception(true); page.on('request', request => { @@ -899,7 +893,7 @@ describe('request interception', function () { ).toBe('Yo, page!'); }); it('should fail if the header value is invalid', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let error!: Error; await page.setRequestInterception(true); diff --git a/test/src/screenshot.spec.ts b/test/src/screenshot.spec.ts index c5e360a4b0d..e5966337824 100644 --- a/test/src/screenshot.spec.ts +++ b/test/src/screenshot.spec.ts @@ -16,20 +16,12 @@ import expect from 'expect'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, - launch, -} from './mocha-utils.js'; +import {getTestState, launch} from './mocha-utils.js'; describe('Screenshots', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - describe('Page.screenshot', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.goto(server.PREFIX + '/grid.html'); @@ -37,7 +29,7 @@ describe('Screenshots', function () { expect(screenshot).toBeGolden('screenshot-sanity.png'); }); it('should clip rect', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.goto(server.PREFIX + '/grid.html'); @@ -52,7 +44,7 @@ describe('Screenshots', function () { expect(screenshot).toBeGolden('screenshot-clip-rect.png'); }); it('should use scale for clip', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.goto(server.PREFIX + '/grid.html'); @@ -68,7 +60,7 @@ describe('Screenshots', function () { expect(screenshot).toBeGolden('screenshot-clip-rect-scale2.png'); }); it('should get screenshot bigger than the viewport', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 50, height: 50}); await page.goto(server.PREFIX + '/grid.html'); const screenshot = await page.screenshot({ @@ -82,7 +74,7 @@ describe('Screenshots', function () { expect(screenshot).toBeGolden('screenshot-offscreen-clip.png'); }); it('should run in parallel', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.goto(server.PREFIX + '/grid.html'); @@ -103,7 +95,7 @@ describe('Screenshots', function () { expect(screenshots[1]).toBeGolden('grid-cell-1.png'); }); it('should take fullPage screenshots', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.goto(server.PREFIX + '/grid.html'); @@ -113,7 +105,7 @@ describe('Screenshots', function () { expect(screenshot).toBeGolden('screenshot-grid-fullpage.png'); }); it('should run in parallel in multiple pages', async () => { - const {server, context} = getTestState(); + const {server, context} = await getTestState(); const N = 2; const pages = await Promise.all( @@ -144,7 +136,7 @@ describe('Screenshots', function () { ); }); it('should allow transparency', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 100, height: 100}); await page.goto(server.EMPTY_PAGE); @@ -152,7 +144,7 @@ describe('Screenshots', function () { expect(screenshot).toBeGolden('transparent.png'); }); it('should render white background on jpeg file', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 100, height: 100}); await page.goto(server.EMPTY_PAGE); @@ -163,7 +155,7 @@ describe('Screenshots', function () { expect(screenshot).toBeGolden('white.jpg'); }); it('should work with webp', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 100, height: 100}); await page.goto(server.PREFIX + '/grid.html'); @@ -174,7 +166,7 @@ describe('Screenshots', function () { expect(screenshot).toBeInstanceOf(Buffer); }); it('should work with odd clip size on Retina displays', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const screenshot = await page.screenshot({ clip: { @@ -187,7 +179,7 @@ describe('Screenshots', function () { expect(screenshot).toBeGolden('screenshot-clip-odd-size.png'); }); it('should return base64', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.goto(server.PREFIX + '/grid.html'); @@ -199,7 +191,7 @@ describe('Screenshots', function () { ); }); it('should work in "fromSurface: false" mode', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.goto(server.PREFIX + '/grid.html'); @@ -212,7 +204,7 @@ describe('Screenshots', function () { describe('ElementHandle.screenshot', function () { it('should work', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.goto(server.PREFIX + '/grid.html'); @@ -224,10 +216,10 @@ describe('Screenshots', function () { expect(screenshot).toBeGolden('screenshot-element-bounding-box.png'); }); it('should work with a null viewport', async () => { - const {defaultBrowserOptions, server} = getTestState(); - + const {server} = await getTestState({ + skipLaunch: true, + }); const {browser, close} = await launch({ - ...defaultBrowserOptions, defaultViewport: null, }); @@ -245,7 +237,7 @@ describe('Screenshots', function () { } }); it('should take into account padding and border', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.setContent(` @@ -264,7 +256,7 @@ describe('Screenshots', function () { expect(screenshot).toBeGolden('screenshot-element-padding-border.png'); }); it('should capture full element when larger than viewport', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); @@ -299,7 +291,7 @@ describe('Screenshots', function () { ).toEqual({w: 500, h: 500}); }); it('should scroll element into view', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.setContent(` @@ -326,7 +318,7 @@ describe('Screenshots', function () { ); }); it('should work with a rotated element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setViewport({width: 500, height: 500}); await page.setContent(`
'); const div = (await page.$('div'))!; @@ -366,7 +358,7 @@ describe('Screenshots', function () { expect(error.message).toBe('Node has 0 height.'); }); it('should work for an element with fractional dimensions', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
' @@ -376,7 +368,7 @@ describe('Screenshots', function () { expect(screenshot).toBeGolden('screenshot-element-fractional.png'); }); it('should work for an element with an offset', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent( '
' diff --git a/test/src/stacktrace.spec.ts b/test/src/stacktrace.spec.ts index c26ebf1a002..62b02f9e8fc 100644 --- a/test/src/stacktrace.spec.ts +++ b/test/src/stacktrace.spec.ts @@ -18,21 +18,14 @@ import assert from 'assert'; import expect from 'expect'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; import {waitEvent} from './utils.js'; const FILENAME = __filename.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&'); describe('Stack trace', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - it('should work', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const error = (await page .evaluate(() => { @@ -49,13 +42,13 @@ describe('Stack trace', function () { expect(error.stack.split('\n at ').slice(0, 2)).toMatchObject({ ...[ 'Error: Test', - 'evaluate (evaluate at Context. (:32:14), :1:18)', + 'evaluate (evaluate at Context. (:30:14), :1:18)', ], }); }); it('should work with handles', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const error = (await page .evaluateHandle(() => { @@ -72,13 +65,13 @@ describe('Stack trace', function () { expect(error.stack.split('\n at ').slice(0, 2)).toMatchObject({ ...[ 'Error: Test', - 'evaluateHandle (evaluateHandle at Context. (:52:14), :1:18)', + 'evaluateHandle (evaluateHandle at Context. (:50:14), :1:18)', ], }); }); it('should work with contiguous evaluation', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const thrower = await page.evaluateHandle(() => { return () => { @@ -100,14 +93,14 @@ describe('Stack trace', function () { expect(error.stack.split('\n at ').slice(0, 3)).toMatchObject({ ...[ 'Error: Test', - 'evaluateHandle (evaluateHandle at Context. (:71:36), :2:22)', - 'evaluate (evaluate at Context. (:77:14), :1:12)', + 'evaluateHandle (evaluateHandle at Context. (:69:36), :2:22)', + 'evaluate (evaluate at Context. (:75:14), :1:12)', ], }); }); it('should work with nested function calls', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const error = (await page .evaluate(() => { @@ -136,17 +129,17 @@ describe('Stack trace', function () { expect(error.stack.split('\n at ').slice(0, 6)).toMatchObject({ ...[ 'Error: Test', - 'a (evaluate at Context. (:98:14), :2:22)', - 'b (evaluate at Context. (:98:14), :5:16)', - 'c (evaluate at Context. (:98:14), :8:16)', - 'd (evaluate at Context. (:98:14), :11:16)', - 'evaluate (evaluate at Context. (:98:14), :13:12)', + 'a (evaluate at Context. (:96:14), :2:22)', + 'b (evaluate at Context. (:96:14), :5:16)', + 'c (evaluate at Context. (:96:14), :8:16)', + 'd (evaluate at Context. (:96:14), :11:16)', + 'evaluate (evaluate at Context. (:96:14), :13:12)', ], }); }); it('should work for none error objects', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const [error] = await Promise.all([ waitEvent(page, 'pageerror'), diff --git a/test/src/target.spec.ts b/test/src/target.spec.ts index 3b5e5c3401a..185eecf2874 100644 --- a/test/src/target.spec.ts +++ b/test/src/target.spec.ts @@ -21,19 +21,12 @@ import {TimeoutError} from 'puppeteer'; import {Page} from 'puppeteer-core/internal/api/Page.js'; import {Target} from 'puppeteer-core/internal/common/Target.js'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; import {waitEvent} from './utils.js'; describe('Target', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - it('Browser.targets should return all of the targets', async () => { - const {browser} = getTestState(); + const {browser} = await getTestState(); // The pages will be the testing page and the original newtab page const targets = browser.targets(); @@ -49,7 +42,7 @@ describe('Target', function () { ).toBeTruthy(); }); it('Browser.pages should return all of the pages', async () => { - const {page, context} = getTestState(); + const {page, context} = await getTestState(); // The pages will be the testing page const allPages = await context.pages(); @@ -57,7 +50,7 @@ describe('Target', function () { expect(allPages).toContain(page); }); it('should contain browser target', async () => { - const {browser} = getTestState(); + const {browser} = await getTestState(); const targets = browser.targets(); const browserTarget = targets.find(target => { @@ -66,7 +59,7 @@ describe('Target', function () { expect(browserTarget).toBeTruthy(); }); it('should be able to use the default page in the browser', async () => { - const {page, browser} = getTestState(); + const {page, browser} = await getTestState(); // The pages will be the testing page and the original newtab page const allPages = await browser.pages(); @@ -81,7 +74,7 @@ describe('Target', function () { expect(await originalPage.$('body')).toBeTruthy(); }); it('should be able to use async waitForTarget', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); const [otherPage] = await Promise.all([ context @@ -103,7 +96,7 @@ describe('Target', function () { expect(page).not.toEqual(otherPage); }); it('should report when a new page is created and closed', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); const [otherPage] = await Promise.all([ context @@ -144,7 +137,7 @@ describe('Target', function () { expect(allPages).not.toContain(otherPage); }); it('should report when a service worker is created and destroyed', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); await page.goto(server.EMPTY_PAGE); const createdTarget = waitEvent(context, 'targetcreated'); @@ -169,7 +162,7 @@ describe('Target', function () { expect(await destroyedTarget).toBe(await createdTarget); }); it('should create a worker from a service worker', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); await page.goto(server.PREFIX + '/serviceworkers/empty/sw.html'); @@ -184,7 +177,7 @@ describe('Target', function () { ).toBe('[object ServiceWorkerGlobalScope]'); }); it('should create a worker from a shared worker', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); await page.goto(server.EMPTY_PAGE); await page.evaluate(() => { @@ -201,7 +194,7 @@ describe('Target', function () { ).toBe('[object SharedWorkerGlobalScope]'); }); it('should report when a target url changes', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); await page.goto(server.EMPTY_PAGE); let changedTarget = waitEvent(context, 'targetchanged'); @@ -213,7 +206,7 @@ describe('Target', function () { expect((await changedTarget).url()).toBe(server.EMPTY_PAGE); }); it('should not report uninitialized pages', async () => { - const {context} = getTestState(); + const {context} = await getTestState(); let targetChanged = false; const listener = () => { @@ -238,7 +231,7 @@ describe('Target', function () { context.off('targetchanged', listener); }); it('should not crash while redirecting if original request was missed', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); let serverResponse!: ServerResponse; server.setRoute('/one-style.css', (_req, res) => { @@ -265,7 +258,7 @@ describe('Target', function () { await newPage.close(); }); it('should have an opener', async () => { - const {page, server, context} = getTestState(); + const {page, server, context} = await getTestState(); await page.goto(server.EMPTY_PAGE); const [createdTarget] = await Promise.all([ @@ -281,7 +274,7 @@ describe('Target', function () { describe('Browser.waitForTarget', () => { it('should wait for a target', async () => { - const {browser, server} = getTestState(); + const {browser, server} = await getTestState(); let resolved = false; const targetPromise = browser.waitForTarget(target => { @@ -315,7 +308,7 @@ describe('Target', function () { await page.close(); }); it('should timeout waiting for a non-existent target', async () => { - const {browser, server} = getTestState(); + const {browser, server} = await getTestState(); let error!: Error; await browser diff --git a/test/src/touchscreen.spec.ts b/test/src/touchscreen.spec.ts index cd78f41b206..7e66356b4f9 100644 --- a/test/src/touchscreen.spec.ts +++ b/test/src/touchscreen.spec.ts @@ -17,18 +17,11 @@ import expect from 'expect'; import {KnownDevices, BoundingBox} from 'puppeteer'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; describe('Touchscreen', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - it('should tap the button', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const iPhone = KnownDevices['iPhone 6']!; await page.emulate(iPhone); await page.goto(server.PREFIX + '/input/button.html'); @@ -41,7 +34,7 @@ describe('Touchscreen', function () { }); it('should report touches', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const iPhone = KnownDevices['iPhone 6']!; await page.emulate(iPhone); await page.goto(server.PREFIX + '/input/touches.html'); @@ -55,7 +48,7 @@ describe('Touchscreen', function () { }); it('should report touchMove', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const iPhone = KnownDevices['iPhone 6']!; await page.emulate(iPhone); await page.goto(server.PREFIX + '/input/touches-move.html'); diff --git a/test/src/tracing.spec.ts b/test/src/tracing.spec.ts index 9c8bec7dc1b..9504335d2b7 100644 --- a/test/src/tracing.spec.ts +++ b/test/src/tracing.spec.ts @@ -19,7 +19,7 @@ import path from 'path'; import expect from 'expect'; -import {getTestState, launch} from './mocha-utils.js'; +import {launch} from './mocha-utils.js'; describe('Tracing', function () { let outputFile!: string; @@ -29,8 +29,7 @@ describe('Tracing', function () { * individual test, which isn't the default behaviour of getTestState() */ beforeEach(async () => { - const {defaultBrowserOptions} = getTestState(); - testState = await launch(defaultBrowserOptions); + testState = await launch({}); outputFile = path.join(__dirname, 'trace.json'); }); diff --git a/test/src/waittask.spec.ts b/test/src/waittask.spec.ts index 27977fb7ac1..98addcbd69e 100644 --- a/test/src/waittask.spec.ts +++ b/test/src/waittask.spec.ts @@ -18,21 +18,13 @@ import expect from 'expect'; import {TimeoutError, ElementHandle} from 'puppeteer'; import {isErrorLike} from 'puppeteer-core/internal/util/ErrorLike.js'; -import { - createTimeout, - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {createTimeout, getTestState} from './mocha-utils.js'; import {attachFrame, detachFrame} from './utils.js'; describe('waittask specs', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); - describe('Frame.waitForFunction', function () { it('should accept a string', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const watchdog = page.waitForFunction('self.__FOO === 1'); await page.evaluate(() => { @@ -41,7 +33,7 @@ describe('waittask specs', function () { await watchdog; }); it('should work when resolved right before execution context disposal', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.evaluateOnNewDocument(() => { return ((globalThis as any).__RELOADED = true); @@ -55,7 +47,7 @@ describe('waittask specs', function () { }); }); it('should poll on interval', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const startTime = Date.now(); const polling = 100; const watchdog = page.waitForFunction( @@ -73,7 +65,7 @@ describe('waittask specs', function () { expect(Date.now() - startTime).not.toBeLessThan(polling / 2); }); it('should poll on mutation', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let success = false; const watchdog = page @@ -98,7 +90,7 @@ describe('waittask specs', function () { await watchdog; }); it('should poll on mutation async', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let success = false; const watchdog = page @@ -123,7 +115,7 @@ describe('waittask specs', function () { await watchdog; }); it('should poll on raf', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const watchdog = page.waitForFunction( () => { @@ -139,7 +131,7 @@ describe('waittask specs', function () { await watchdog; }); it('should poll on raf async', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const watchdog = page.waitForFunction( async () => { @@ -155,7 +147,7 @@ describe('waittask specs', function () { await watchdog; }); it('should work with strict CSP policy', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); server.setCSP('/empty.html', 'script-src ' + server.PREFIX); await page.goto(server.EMPTY_PAGE); @@ -180,7 +172,7 @@ describe('waittask specs', function () { expect(error).toBeUndefined(); }); it('should throw negative polling interval', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; try { @@ -200,7 +192,7 @@ describe('waittask specs', function () { ); }); it('should return the success value as a JSHandle', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); expect( await ( @@ -211,7 +203,7 @@ describe('waittask specs', function () { ).toBe(5); }); it('should return the window as a success value', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); expect( await page.waitForFunction(() => { @@ -220,7 +212,7 @@ describe('waittask specs', function () { ).toBeTruthy(); }); it('should accept ElementHandle arguments', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent('
'); const div = (await page.$('div'))!; @@ -243,7 +235,7 @@ describe('waittask specs', function () { await waitForFunction; }); it('should respect timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page @@ -261,7 +253,7 @@ describe('waittask specs', function () { expect(error?.message).toContain('Waiting failed: 10ms exceeded'); }); it('should respect default timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); page.setDefaultTimeout(1); let error!: Error; @@ -276,7 +268,7 @@ describe('waittask specs', function () { expect(error?.message).toContain('Waiting failed: 1ms exceeded'); }); it('should disable timeout when its set to 0', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const watchdog = page.waitForFunction( () => { @@ -295,7 +287,7 @@ describe('waittask specs', function () { await watchdog; }); it('should survive cross-process navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let fooFound = false; const waitForFunction = page @@ -318,7 +310,7 @@ describe('waittask specs', function () { expect(fooFound).toBe(true); }); it('should survive navigations', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); const watchdog = page.waitForFunction(() => { return (globalThis as any).__done; @@ -331,7 +323,7 @@ describe('waittask specs', function () { await watchdog; }); it('should be cancellable', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const abortController = new AbortController(); @@ -350,7 +342,7 @@ describe('waittask specs', function () { describe('Page.waitForTimeout', () => { it('waits for the given timeout before resolving', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const startTime = Date.now(); await page.waitForTimeout(1000); @@ -366,7 +358,7 @@ describe('waittask specs', function () { describe('Frame.waitForTimeout', () => { it('waits for the given timeout before resolving', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const frame = page.mainFrame(); const startTime = Date.now(); @@ -387,7 +379,7 @@ describe('waittask specs', function () { }; it('should immediately resolve promise if node exists', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const frame = page.mainFrame(); @@ -397,7 +389,7 @@ describe('waittask specs', function () { }); it('should be cancellable', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const abortController = new AbortController(); @@ -409,7 +401,7 @@ describe('waittask specs', function () { }); it('should work with removed MutationObserver', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.evaluate(() => { // @ts-expect-error We want to remove it for the test. @@ -427,7 +419,7 @@ describe('waittask specs', function () { }); it('should resolve promise when node is added', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const frame = page.mainFrame(); @@ -440,7 +432,7 @@ describe('waittask specs', function () { }); it('should work when node is added through innerHTML', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); const watchdog = page.waitForSelector('h3 div'); @@ -453,7 +445,7 @@ describe('waittask specs', function () { }); it('Page.waitForSelector is shortcut for main frame', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await page.goto(server.EMPTY_PAGE); await attachFrame(page, 'frame1', server.EMPTY_PAGE); @@ -466,7 +458,7 @@ describe('waittask specs', function () { }); it('should run in specified frame', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await attachFrame(page, 'frame1', server.EMPTY_PAGE); await attachFrame(page, 'frame2', server.EMPTY_PAGE); @@ -480,7 +472,7 @@ describe('waittask specs', function () { }); it('should throw when frame is detached', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await attachFrame(page, 'frame1', server.EMPTY_PAGE); const frame = page.frames()[1]!; @@ -496,7 +488,7 @@ describe('waittask specs', function () { ); }); it('should survive cross-process navigation', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); let boxFound = false; const waitForSelector = page.waitForSelector('.box').then(() => { @@ -511,7 +503,7 @@ describe('waittask specs', function () { expect(boxFound).toBe(true); }); it('should wait for element to be visible (display)', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const promise = page.waitForSelector('div', {visible: true}); await page.setContent('
text
'); @@ -527,7 +519,7 @@ describe('waittask specs', function () { await expect(promise).resolves.toBeTruthy(); }); it('should wait for element to be visible (visibility)', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const promise = page.waitForSelector('div', {visible: true}); await page.setContent('
text
'); @@ -549,7 +541,7 @@ describe('waittask specs', function () { await expect(promise).resolves.toBeTruthy(); }); it('should wait for element to be visible (bounding box)', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const promise = page.waitForSelector('div', {visible: true}); await page.setContent('
text
'); @@ -572,7 +564,7 @@ describe('waittask specs', function () { await expect(promise).resolves.toBeTruthy(); }); it('should wait for element to be visible recursively', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const promise = page.waitForSelector('div#inner', { visible: true, @@ -598,7 +590,7 @@ describe('waittask specs', function () { await expect(promise).resolves.toBeTruthy(); }); it('should wait for element to be hidden (visibility)', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const promise = page.waitForSelector('div', {hidden: true}); await page.setContent(`
text
`); @@ -614,7 +606,7 @@ describe('waittask specs', function () { await expect(promise).resolves.toBeTruthy(); }); it('should wait for element to be hidden (display)', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const promise = page.waitForSelector('div', {hidden: true}); await page.setContent(`
text
`); @@ -630,7 +622,7 @@ describe('waittask specs', function () { await expect(promise).resolves.toBeTruthy(); }); it('should wait for element to be hidden (bounding box)', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const promise = page.waitForSelector('div', {hidden: true}); await page.setContent('
text
'); @@ -646,7 +638,7 @@ describe('waittask specs', function () { await expect(promise).resolves.toBeTruthy(); }); it('should wait for element to be hidden (removal)', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const promise = page.waitForSelector('div', {hidden: true}); await page.setContent(`
text
`); @@ -662,7 +654,7 @@ describe('waittask specs', function () { await expect(promise).resolves.toBeFalsy(); }); it('should return null if waiting to hide non-existing element', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const handle = await page.waitForSelector('non-existing', { hidden: true, @@ -670,7 +662,7 @@ describe('waittask specs', function () { expect(handle).toBe(null); }); it('should respect timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page.waitForSelector('div', {timeout: 10}).catch(error_ => { @@ -682,7 +674,7 @@ describe('waittask specs', function () { ); }); it('should have an error message specifically for awaiting an element to be hidden', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(`
text
`); let error!: Error; @@ -698,7 +690,7 @@ describe('waittask specs', function () { }); it('should respond to node attribute mutation', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let divFound = false; const waitForSelector = page.waitForSelector('.zombo').then(() => { @@ -712,7 +704,7 @@ describe('waittask specs', function () { expect(await waitForSelector).toBe(true); }); it('should return the element handle', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const waitForSelector = page.waitForSelector('.zombo'); await page.setContent(`
anything
`); @@ -723,7 +715,7 @@ describe('waittask specs', function () { ).toBe('anything'); }); it('should have correct stack trace for timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page.waitForSelector('.zombo', {timeout: 10}).catch(error_ => { @@ -743,7 +735,7 @@ describe('waittask specs', function () { }; it('should support some fancy xpath', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(`

red herring

hello world

`); const waitForXPath = page.waitForXPath( @@ -756,7 +748,7 @@ describe('waittask specs', function () { ).toBe('hello world '); }); it('should respect timeout', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let error!: Error; await page.waitForXPath('//div', {timeout: 10}).catch(error_ => { @@ -766,7 +758,7 @@ describe('waittask specs', function () { expect(error?.message).toContain('Waiting failed: 10ms exceeded'); }); it('should run in specified frame', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await attachFrame(page, 'frame1', server.EMPTY_PAGE); await attachFrame(page, 'frame2', server.EMPTY_PAGE); @@ -779,7 +771,7 @@ describe('waittask specs', function () { expect(eHandle?.frame).toBe(frame2); }); it('should throw when frame is detached', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await attachFrame(page, 'frame1', server.EMPTY_PAGE); const frame = page.frames()[1]!; @@ -797,7 +789,7 @@ describe('waittask specs', function () { ); }); it('hidden should wait for display: none', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); let divHidden = false; await page.setContent(`
text
`); @@ -817,14 +809,14 @@ describe('waittask specs', function () { expect(divHidden).toBe(true); }); it('hidden should return null if the element is not found', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const waitForXPath = await page.waitForXPath('//div', {hidden: true}); expect(waitForXPath).toBe(null); }); it('hidden should return an empty element handle if the element is found', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(`
text
`); @@ -833,7 +825,7 @@ describe('waittask specs', function () { expect(waitForXPath).toBeInstanceOf(ElementHandle); }); it('should return the element handle', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const waitForXPath = page.waitForXPath('//*[@class="zombo"]'); await page.setContent(`
anything
`); @@ -844,7 +836,7 @@ describe('waittask specs', function () { ).toBe('anything'); }); it('should allow you to select a text node', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(`
some text
`); const text = await page.waitForXPath('//div/text()'); @@ -853,7 +845,7 @@ describe('waittask specs', function () { ); }); it('should allow you to select an element with single slash', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); await page.setContent(`
some text
`); const waitForXPath = page.waitForXPath('/html/body/div'); diff --git a/test/src/worker.spec.ts b/test/src/worker.spec.ts index 733c5bdff1f..f0f2a1040d9 100644 --- a/test/src/worker.spec.ts +++ b/test/src/worker.spec.ts @@ -18,18 +18,12 @@ import expect from 'expect'; import {ConsoleMessage} from 'puppeteer-core/internal/common/ConsoleMessage.js'; import {WebWorker} from 'puppeteer-core/internal/common/WebWorker.js'; -import { - getTestState, - setupTestBrowserHooks, - setupTestPageAndContextHooks, -} from './mocha-utils.js'; +import {getTestState} from './mocha-utils.js'; import {waitEvent} from './utils.js'; describe('Workers', function () { - setupTestBrowserHooks(); - setupTestPageAndContextHooks(); it('Page.workers', async () => { - const {page, server} = getTestState(); + const {page, server} = await getTestState(); await Promise.all([ waitEvent(page, 'workercreated'), @@ -48,7 +42,7 @@ describe('Workers', function () { expect(page.workers()).toHaveLength(0); }); it('should emit created and destroyed events', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const workerCreatedPromise = waitEvent(page, 'workercreated'); const workerObj = await page.evaluateHandle(() => { @@ -69,7 +63,7 @@ describe('Workers', function () { expect(error.message).toContain('Most likely the worker has been closed.'); }); it('should report console logs', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const [message] = await Promise.all([ waitEvent(page, 'console'), @@ -85,7 +79,7 @@ describe('Workers', function () { }); }); it('should have JSHandles for console logs', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const logPromise = waitEvent(page, 'console'); await page.evaluate(() => { @@ -99,7 +93,7 @@ describe('Workers', function () { ); }); it('should have an execution context', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const workerCreatedPromise = waitEvent(page, 'workercreated'); await page.evaluate(() => { @@ -109,7 +103,7 @@ describe('Workers', function () { expect(await (await worker.executionContext()).evaluate('1+1')).toBe(2); }); it('should report errors', async () => { - const {page} = getTestState(); + const {page} = await getTestState(); const errorPromise = waitEvent(page, 'pageerror'); await page.evaluate(() => {