ci: remove before hooks (#10431)

This commit is contained in:
Nikolay Vitkov 2023-06-21 21:41:09 +02:00 committed by GitHub
parent 337184e722
commit ff8529696d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
47 changed files with 1364 additions and 1610 deletions

View File

@ -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);
});

View File

@ -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"],

View File

@ -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();

View File

@ -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([

View File

@ -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(`
<head>
@ -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(`<textarea>hi</textarea>`);
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(
`<!DOCTYPE html>
@ -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(
'<div tabIndex=-1 aria-roledescription="foo">Hi</div>'
@ -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(
'<a href="" role="slider" aria-orientation="vertical">11</a>'
@ -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('<input type="number" aria-autocomplete="list" />');
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(
'<div role="grid" tabIndex=-1 aria-multiselectable=true>hey</div>'
@ -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(
'<div role="grid" tabIndex=-1 aria-keyshortcuts="foo">hey</div>'
@ -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(`
<div role="tablist">
@ -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(`
<div contenteditable="true">
@ -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(`
<div contenteditable="true" role='textbox'>
@ -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(`
<div contenteditable="plaintext-only" role='textbox'>Edit this image:<img src="fakeimage.png" alt="my fake image"></div>`);
@ -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(`
<div role="textbox" tabIndex=0 aria-checked="true" aria-label="my favorite textbox">
@ -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(`
<div role="checkbox" tabIndex=0 aria-checked="true" aria-label="my favorite checkbox">
@ -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(`
<div role="checkbox" aria-checked="true">
@ -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(`<button>My Button</button>`);
@ -495,7 +488,7 @@ describe('Accessibility', function () {
});
});
it('should work an input', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setContent(`<input title="My Input" value="My Value">`);
@ -507,7 +500,7 @@ describe('Accessibility', function () {
});
});
it('should work a menu', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setContent(`
<div role="menu" title="My Menu">
@ -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(`<button>My Button</button>`);
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(`<div><button>My Button</button></div>`);
const div = (await page.$('div'))!;

View File

@ -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(
'<button id="btn" role="button"> Submit button and some spaces </button>'
);
});
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(
'<div id="div"><button id="btn" role="button">Submit</button></div>'
);
@ -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(
'<div id="div"><button id="btn" role="button">Submit</button></div>'
);
@ -123,7 +113,7 @@ describe('AriaQueryHandler', () => {
});
it('should find first matching element', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setContent(
`
<div role="menu" id="mnu1" aria-label="menu div"></div>
@ -140,7 +130,7 @@ describe('AriaQueryHandler', () => {
});
it('should find by name', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setContent(
`
<div role="menu" id="mnu1" aria-label="menu-label1">menu div</div>
@ -157,7 +147,7 @@ describe('AriaQueryHandler', () => {
});
it('should find by name', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setContent(
`
<div role="menu" id="mnu1" aria-label="menu-label1">menu div</div>
@ -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(
`
<div role="menu" id="mnu1" aria-label="menu div"></div>
@ -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 = `<div><button>test</button></div>`);
@ -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(`<div role='main'>text</div>`);
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(`<div role='main'>text</div>`);
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<typeof getTestState> {
const state = await getTestState();
await state.page.setContent(
`
<h2 id="shown">title</h2>
<h2 id="hidden" aria-hidden="true">title</h2>
@ -658,7 +648,8 @@ describe('AriaQueryHandler', () => {
<div aria-describedby="node30"></div>
`
);
});
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<HTMLButtonElement>
>;
@ -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']);

View File

@ -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({

View File

@ -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();

View File

@ -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(`

View File

@ -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(`
<svg height="100" width="100">
@ -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(`
<style>
@ -88,7 +82,7 @@ describe('Page.click', function () {
).toBe(42);
});
it('should not throw UnhandledPromiseRejection when page closes', async () => {
const {page} = getTestState();
const {page} = await getTestState();
const newPage = await page.browser().newPage();
await Promise.all([newPage.close(), newPage.mouse.click(1, 2)]).catch(
@ -96,7 +90,7 @@ describe('Page.click', function () {
);
});
it('should click the button after navigation', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/button.html');
await page.click('button');
@ -109,7 +103,7 @@ describe('Page.click', function () {
).toBe('Clicked');
});
it('should click with disabled javascript', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.setJavaScriptEnabled(false);
await page.goto(server.PREFIX + '/wrappedlink.html');
@ -117,7 +111,7 @@ describe('Page.click', function () {
expect(page.url()).toBe(server.PREFIX + '/wrappedlink.html#clicked');
});
it('should scroll and click with disabled javascript', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.setJavaScriptEnabled(false);
await page.goto(server.PREFIX + '/wrappedlink.html');
@ -129,7 +123,7 @@ describe('Page.click', function () {
expect(page.url()).toBe(server.PREFIX + '/wrappedlink.html#clicked');
});
it('should click when one of inline box children is outside of viewport', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setContent(`
<style>
@ -148,7 +142,7 @@ describe('Page.click', function () {
).toBe(42);
});
it('should select the text by triple clicking', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/textarea.html');
await page.focus('textarea');
@ -178,7 +172,7 @@ describe('Page.click', function () {
).toBe(text);
});
it('should click offscreen buttons', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/offscreenbuttons.html');
const messages: any[] = [];
@ -211,7 +205,7 @@ describe('Page.click', function () {
});
it('should click wrapped links', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/wrappedlink.html');
await page.click('a');
@ -223,7 +217,7 @@ describe('Page.click', function () {
});
it('should click on checkbox input and toggle', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/checkbox.html');
expect(
@ -260,7 +254,7 @@ describe('Page.click', function () {
});
it('should click on checkbox label and toggle', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/checkbox.html');
expect(
@ -288,7 +282,7 @@ describe('Page.click', function () {
});
it('should fail to click a missing button', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/button.html');
let error!: Error;
@ -301,7 +295,7 @@ describe('Page.click', function () {
});
// @see https://github.com/puppeteer/puppeteer/issues/161
it('should not hang with touch-enabled viewports', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setViewport(KnownDevices['iPhone 6'].viewport);
await page.mouse.down();
@ -309,7 +303,7 @@ describe('Page.click', function () {
await page.mouse.up();
});
it('should scroll and click the button', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/scrollable.html');
await page.click('#button-5');
@ -326,7 +320,7 @@ describe('Page.click', function () {
).toBe('clicked');
});
it('should double click the button', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/button.html');
await page.evaluate(() => {
@ -342,7 +336,7 @@ describe('Page.click', function () {
expect(await page.evaluate('result')).toBe('Clicked');
});
it('should click a partially obscured button', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/button.html');
await page.evaluate(() => {
@ -359,7 +353,7 @@ describe('Page.click', function () {
).toBe('Clicked');
});
it('should click a rotated button', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/rotatedButton.html');
await page.click('button');
@ -370,7 +364,7 @@ describe('Page.click', function () {
).toBe('Clicked');
});
it('should fire contextmenu event on right click', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/scrollable.html');
await page.click('#button-8', {button: 'right'});
@ -381,7 +375,7 @@ describe('Page.click', function () {
).toBe('context menu');
});
it('should fire aux event on middle click', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/scrollable.html');
await page.click('#button-8', {button: 'middle'});
@ -392,7 +386,7 @@ describe('Page.click', function () {
).toBe('aux click');
});
it('should fire back click', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/scrollable.html');
await page.click('#button-8', {button: 'back'});
@ -403,7 +397,7 @@ describe('Page.click', function () {
).toBe('back click');
});
it('should fire forward click', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/scrollable.html');
await page.click('#button-8', {button: 'forward'});
@ -415,14 +409,14 @@ describe('Page.click', function () {
});
// @see https://github.com/puppeteer/puppeteer/issues/206
it('should click links which cause navigation', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.setContent(`<a href="${server.EMPTY_PAGE}">empty.html</a>`);
// This await should not hang.
await page.click('a');
});
it('should click the button inside an iframe', async () => {
const {page, server} = getTestState();
const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE);
await page.setContent('<div style="width:100px;height:100px">spacer</div>');
@ -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(

View File

@ -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(

View File

@ -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');

View File

@ -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',

View File

@ -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();

View File

@ -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);

View File

@ -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('<div style="display:none">hi</div>');
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(`
<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500">
@ -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('<div style="display:none">hi</div>');
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('<div style="display: none">text</div>');
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 <br> elements', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setContent('hello<br>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<ElementHandle<HTMLDivElement>>;
@ -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(
`<div id=el1>
@ -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('<div id="not-foo"></div><div id="foo"></div>');
// 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(
'<div id="not-foo"></div><div class="foo">Foo1</div><div class="foo baz">Foo2</div>'
);
@ -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(
'<div id="not-foo"></div><div class="foo">Foo1</div><div class="foo baz">Foo2</div>'
);
@ -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(
'<div id="not-foo"></div><div class="foo"><div id="nested-foo" class="foo"/></div><div class="foo baz">Foo2</div>'
);
@ -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(
'<div id="not-foo"></div><div class="foo">text</div><div class="foo baz">content</div>'
);
@ -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('<div id="not-foo"></div><div id="foo"></div>');
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('<div class="foo">Foo1</div>');
const element = await page.$('.foo');
const div = await element?.toElement('div');

View File

@ -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);

View File

@ -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('<section>42</section>');
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('<section>39</section>');
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();

View File

@ -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, {

View File

@ -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);
});
});

View File

@ -58,8 +58,10 @@ describe('headful tests', function () {
};
const browsers: Array<() => Promise<void>> = [];
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();

View File

@ -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<HTMLElement>;
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);
});
});

View File

@ -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(`<iframe src=${server.EMPTY_PAGE}></iframe>`);

View File

@ -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(

View File

@ -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(`<input type=file>`);
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(`<input type=file>`);
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(
`<input type=file oninput='javascript:console.timeStamp()'>`
@ -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(`<input type=file>`);
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(`<input type=file>`);
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(`<input type=file>`);
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(`<input type=file>`);
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(`<input type=file>`);
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(`<input type=file>`);
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(`<input type=file>`);
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(`<input type=file>`);
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(`<input multiple type=file>`);
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(`<input multiple webkitdirectory type=file>`);
const [chooser] = await Promise.all([

View File

@ -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('<div>ee!</div>');
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'

View File

@ -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;

View File

@ -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({

View File

@ -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(`
<select>
@ -367,7 +360,7 @@ describe('Locator', function () {
});
it('should work for inputs', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setContent(`
<input>
`);
@ -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(`
<input disabled>
@ -404,7 +397,7 @@ describe('Locator', function () {
});
it('should work for contenteditable', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setContent(`
<div contenteditable="true">
`);
@ -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(`
<input value="te">
`);
@ -430,7 +423,7 @@ describe('Locator', function () {
});
it('should override pre-filled inputs', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setContent(`
<input value="wrong prefix">
`);
@ -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(`
<input type="color">
`);
@ -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});

View File

@ -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<void> => {
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<PuppeteerTestState> => {
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<void> => {
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<void> => {
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<void> => {
state.server!.reset();
state.httpsServer!.reset();
async afterAll(): Promise<void> {
await state.browser?.close();
await state.server?.stop();
await state.httpsServer?.stop();
},
afterAll: [
async (): Promise<void> => {
await state.server!.stop();
state.server = undefined;
await state.httpsServer!.stop();
state.httpsServer = undefined;
},
],
afterEach: (): void => {
async afterEach(): Promise<void> {
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<Partial<Protocol.Network.Cookie>>
): void => {
const {isChrome} = getTestState();
if (!isChrome) {
): Promise<void> => {
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 = <T>(
let browserCleanups: Array<() => Promise<void>> = [];
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;
}

View File

@ -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);

View File

@ -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(`<a href='#foobar'>foobar</a>`);
@ -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(() => {

View File

@ -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<HTTPRequest>(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 => {

View File

@ -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(

File diff suppressed because it is too large Load Diff

View File

@ -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 {

View File

@ -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<typeof getTestState> {
const state = await getTestState();
await state.page.setContent(
`<script>
const div = document.createElement('div');
const shadowRoot = div.attachShadow({mode: 'open'});
@ -47,9 +40,10 @@ describe('Query handler tests', function () {
document.documentElement.appendChild(div);
</script>`
);
});
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<HTMLElement>;
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<HTMLElement>
>;
@ -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<HTMLElement>
@ -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('<section>test</section>');
@ -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('<div id="1">a</div><div>a</div>');
@ -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('<div>a</div><div>a</div>');
@ -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('<div><div>a</div><div>b</div></div>');
@ -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('<input value="a">');
@ -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('<radio value="a">');
expect(await page.$('text/a')).toBeNull();
});
it('should query text spanning multiple elements', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setContent('<div><span>a</span> <span>b</span><div>');
@ -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(
'<div id=target1>text</div><input id=target2 value=text><div id=target3>text</div>'
@ -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('<div class="a"><span>a</span></div>');
@ -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('<div class="a"></div>');
@ -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('<section>test</section>');
@ -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('<div>a</div><div></div>');
@ -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('<div></div><div></div>');
@ -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('<div class="a">a<span></span></div>');
@ -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('<div class="a">a</div>');
@ -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);
});

View File

@ -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('<section id="testAttribute">43543</section>');
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('<section>hello</section>');
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('<section>hello</section><div> world</div>');
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<Element>.
describe('Page.$$eval', function () {
it('should work', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setContent(
'<div>hello</div><div>beautiful</div><div>world!</div>'
@ -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(
'<div>hello</div><div>beautiful</div><div>world!</div>'
);
@ -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(
'<section>2</section><section>2</section><section>1</section><div>3</div>'
);
@ -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('<section>test</section>');
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('<div>A</div><br/><div>B</div>');
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('<section>test</section>');
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('<div></div><div></div>');
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(
'<html><body><div class="second"><div class="inner">B</div></div></body></html>'
@ -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(
'<html><body><div class="tweet"><div class="like">100</div><div class="retweets">10</div></div></body></html>'
@ -257,7 +251,7 @@ describe('querySelector', function () {
});
it('should retrieve content from subtree', async () => {
const {page} = getTestState();
const {page} = await getTestState();
const htmlContent =
'<div class="a">not-a-child-div</div><div id="myId"><div class="a">a-child-div</div></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 =
'<div class="a">not-a-child-div</div><div id="myId"></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(
'<html><body><div class="tweet"><div class="like">100</div><div class="like">10</div></div></body></html>'
@ -305,7 +299,7 @@ describe('querySelector', function () {
});
it('should retrieve content from subtree', async () => {
const {page} = getTestState();
const {page} = await getTestState();
const htmlContent =
'<div class="a">not-a-child-div</div><div id="myId"><div class="a">a1-child-div</div><div class="a">a2-child-div</div></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 =
'<div class="a">not-a-child-div</div><div id="myId"></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(
'<html><body><div>A</div><br/><div>B</div></body></html>'
@ -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(
'<html><body><span>A</span><br/><span>B</span></body></html>'
@ -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(
'<html><body><div class="second"><div class="inner">B</div></div></body></html>'
@ -410,7 +404,7 @@ describe('querySelector', function () {
).toBeTruthy();
});
it('$$ should query existing elements', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setContent(
'<html><body><div>A</div><br/><div>B</div></body></html>'
@ -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(
'<html><body><span>A</span><br/><span>B</span></body></html>'
@ -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(
'<div>hello</div><div>beautiful</div><div>world!</div>'
@ -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(
'<div>hello</div><div>beautiful</div><div>world!</div>'
);
@ -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(
'<section>2</section><section>2</section><section>1</section><div>3</div>'
);
@ -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++) {

View File

@ -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('<iframe></iframe>');
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 => {

View File

@ -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('<iframe></iframe>');
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);

View File

@ -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(`<div style="position:absolute;
@ -341,7 +333,7 @@ describe('Screenshots', function () {
expect(screenshot).toBeGolden('screenshot-element-rotate.png');
});
it('should fail to screenshot a detached element', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setContent('<h1>remove this</h1>');
const elementHandle = (await page.$('h1'))!;
@ -356,7 +348,7 @@ describe('Screenshots', function () {
);
});
it('should not hang with zero width/height element', async () => {
const {page} = getTestState();
const {page} = await getTestState();
await page.setContent('<div style="width: 50px; height: 0"></div>');
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(
'<div style="width:48.51px;height:19.8px;border:1px solid black;"></div>'
@ -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(
'<div style="position:absolute; top: 10.3px; left: 20.4px;width:50.3px;height:20.2px;border:1px solid black;"></div>'

View File

@ -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.<anonymous> (<filename>:32:14), <anonymous>:1:18)',
'evaluate (evaluate at Context.<anonymous> (<filename>:30:14), <anonymous>: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.<anonymous> (<filename>:52:14), <anonymous>:1:18)',
'evaluateHandle (evaluateHandle at Context.<anonymous> (<filename>:50:14), <anonymous>: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.<anonymous> (<filename>:71:36), <anonymous>:2:22)',
'evaluate (evaluate at Context.<anonymous> (<filename>:77:14), <anonymous>:1:12)',
'evaluateHandle (evaluateHandle at Context.<anonymous> (<filename>:69:36), <anonymous>:2:22)',
'evaluate (evaluate at Context.<anonymous> (<filename>:75:14), <anonymous>: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.<anonymous> (<filename>:98:14), <anonymous>:2:22)',
'b (evaluate at Context.<anonymous> (<filename>:98:14), <anonymous>:5:16)',
'c (evaluate at Context.<anonymous> (<filename>:98:14), <anonymous>:8:16)',
'd (evaluate at Context.<anonymous> (<filename>:98:14), <anonymous>:11:16)',
'evaluate (evaluate at Context.<anonymous> (<filename>:98:14), <anonymous>:13:12)',
'a (evaluate at Context.<anonymous> (<filename>:96:14), <anonymous>:2:22)',
'b (evaluate at Context.<anonymous> (<filename>:96:14), <anonymous>:5:16)',
'c (evaluate at Context.<anonymous> (<filename>:96:14), <anonymous>:8:16)',
'd (evaluate at Context.<anonymous> (<filename>:96:14), <anonymous>:11:16)',
'evaluate (evaluate at Context.<anonymous> (<filename>:96:14), <anonymous>:13:12)',
],
});
});
it('should work for none error objects', async () => {
const {page} = getTestState();
const {page} = await getTestState();
const [error] = await Promise.all([
waitEvent<Error>(page, 'pageerror'),

View File

@ -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

View File

@ -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');

View File

@ -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');
});

View File

@ -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('<div></div>');
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('<div style="display: none">text</div>');
@ -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('<div style="visibility: hidden">text</div>');
@ -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('<div style="width: 0">text</div>');
@ -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(`<div style='display: block;'>text</div>`);
@ -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(`<div style='display: block;'>text</div>`);
@ -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('<div>text</div>');
@ -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(`<div>text</div>`);
@ -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(`<div>text</div>`);
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(`<div class='zombo'>anything</div>`);
@ -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(`<p>red herring</p><p>hello world </p>`);
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(`<div style='display: block;'>text</div>`);
@ -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(`<div style='display: none;'>text</div>`);
@ -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(`<div class='zombo'>anything</div>`);
@ -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(`<div>some text</div>`);
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(`<div>some text</div>`);
const waitForXPath = page.waitForXPath('/html/body/div');

View File

@ -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<WebWorker>(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<ConsoleMessage>(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<WebWorker>(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<Error>(page, 'pageerror');
await page.evaluate(() => {