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 ```ts
... ...
it.only('should work', async function() { it.only('should work', async function() {
const {server, page} = getTestState(); const {server, page} = await getTestState();
const response = await page.goto(server.EMPTY_PAGE); const response = await page.goto(server.EMPTY_PAGE);
expect(response.ok).toBe(true); expect(response.ok).toBe(true);
}); });
@ -73,7 +73,7 @@ npm run build --workspace=@puppeteer-test/test && npm test
```ts ```ts
... ...
it.skip('should work', async function({server, page}) { 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); const response = await page.goto(server.EMPTY_PAGE);
expect(response.ok).toBe(true); expect(response.ok).toBe(true);
}); });

View File

@ -1547,12 +1547,6 @@
"parameters": ["cdp", "firefox"], "parameters": ["cdp", "firefox"],
"expectations": ["FAIL"] "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", "testIdPattern": "[browsercontext.spec] BrowserContext should provide a context id",
"platforms": ["darwin", "linux", "win32"], "platforms": ["darwin", "linux", "win32"],
@ -1781,6 +1775,12 @@
"parameters": ["chrome", "webDriverBiDi"], "parameters": ["chrome", "webDriverBiDi"],
"expectations": ["FAIL", "PASS"] "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", "testIdPattern": "[defaultbrowsercontext.spec] DefaultBrowserContext page.deleteCookie() should work",
"platforms": ["darwin", "linux", "win32"], "platforms": ["darwin", "linux", "win32"],

View File

@ -17,19 +17,12 @@
import expect from 'expect'; import expect from 'expect';
import {isErrorLike} from 'puppeteer-core/internal/util/ErrorLike.js'; import {isErrorLike} from 'puppeteer-core/internal/util/ErrorLike.js';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {waitEvent} from './utils.js'; import {waitEvent} from './utils.js';
describe('Target.createCDPSession', function () { describe('Target.createCDPSession', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const client = await page.target().createCDPSession(); 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 () => { it('should not report created targets for custom CDP sessions', async () => {
const {browser} = getTestState(); const {browser} = await getTestState();
let called = 0; let called = 0;
browser.browserContexts()[0]!.on('targetcreated', async target => { const handler = async (target: any) => {
called++; called++;
if (called > 1) { if (called > 1) {
throw new Error('Too many targets created'); throw new Error('Too many targets created');
} }
await target.createCDPSession(); await target.createCDPSession();
}); };
browser.browserContexts()[0]!.on('targetcreated', handler);
await browser.newPage(); await browser.newPage();
browser.browserContexts()[0]!.off('targetcreated', handler);
}); });
it('should send events', async () => { it('should send events', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const client = await page.target().createCDPSession(); const client = await page.target().createCDPSession();
await client.send('Network.enable'); await client.send('Network.enable');
@ -72,7 +67,7 @@ describe('Target.createCDPSession', function () {
expect(events).toHaveLength(1); expect(events).toHaveLength(1);
}); });
it('should enable and disable domains independently', async () => { it('should enable and disable domains independently', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const client = await page.target().createCDPSession(); const client = await page.target().createCDPSession();
await client.send('Runtime.enable'); await client.send('Runtime.enable');
@ -89,7 +84,7 @@ describe('Target.createCDPSession', function () {
expect(event.url).toBe('foo.js'); expect(event.url).toBe('foo.js');
}); });
it('should be able to detach session', async () => { it('should be able to detach session', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const client = await page.target().createCDPSession(); const client = await page.target().createCDPSession();
await client.send('Runtime.enable'); await client.send('Runtime.enable');
@ -113,7 +108,7 @@ describe('Target.createCDPSession', function () {
expect(error.message).toContain('Session closed.'); expect(error.message).toContain('Session closed.');
}); });
it('should throw nice errors', async () => { it('should throw nice errors', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const client = await page.target().createCDPSession(); const client = await page.target().createCDPSession();
const error = await theSourceOfTheProblems().catch(error => { const error = await theSourceOfTheProblems().catch(error => {
@ -131,7 +126,7 @@ describe('Target.createCDPSession', function () {
}); });
it('should expose the underlying connection', async () => { it('should expose the underlying connection', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const client = await page.target().createCDPSession(); const client = await page.target().createCDPSession();
expect(client.connection()).toBeTruthy(); expect(client.connection()).toBeTruthy();

View File

@ -27,7 +27,9 @@ describe('TargetManager', () => {
}; };
beforeEach(async () => { beforeEach(async () => {
const {defaultBrowserOptions} = getTestState(); const {defaultBrowserOptions} = await getTestState({
skipLaunch: true,
});
testState = (await launch( testState = (await launch(
Object.assign({}, defaultBrowserOptions, { Object.assign({}, defaultBrowserOptions, {
args: (defaultBrowserOptions.args || []).concat([ args: (defaultBrowserOptions.args || []).concat([

View File

@ -19,18 +19,11 @@ import assert from 'assert';
import expect from 'expect'; import expect from 'expect';
import {SerializedAXNode} from 'puppeteer-core/internal/common/Accessibility.js'; import {SerializedAXNode} from 'puppeteer-core/internal/common/Accessibility.js';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
describe('Accessibility', function () { describe('Accessibility', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('should work', async () => { it('should work', async () => {
const {page, isFirefox} = getTestState(); const {page, isFirefox} = await getTestState();
await page.setContent(` await page.setContent(`
<head> <head>
@ -122,7 +115,7 @@ describe('Accessibility', function () {
expect(await page.accessibility.snapshot()).toEqual(golden); expect(await page.accessibility.snapshot()).toEqual(golden);
}); });
it('should report uninteresting nodes', async () => { it('should report uninteresting nodes', async () => {
const {page, isFirefox} = getTestState(); const {page, isFirefox} = await getTestState();
await page.setContent(`<textarea>hi</textarea>`); await page.setContent(`<textarea>hi</textarea>`);
await page.focus('textarea'); await page.focus('textarea');
@ -167,7 +160,7 @@ describe('Accessibility', function () {
}); });
it('get snapshots while the tree is re-calculated', async () => { it('get snapshots while the tree is re-calculated', async () => {
// see https://github.com/puppeteer/puppeteer/issues/9404 // see https://github.com/puppeteer/puppeteer/issues/9404
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
`<!DOCTYPE html> `<!DOCTYPE html>
@ -211,7 +204,7 @@ describe('Accessibility', function () {
await page.waitForSelector('aria/Hide'); await page.waitForSelector('aria/Hide');
}); });
it('roledescription', async () => { it('roledescription', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div tabIndex=-1 aria-roledescription="foo">Hi</div>' '<div tabIndex=-1 aria-roledescription="foo">Hi</div>'
@ -224,7 +217,7 @@ describe('Accessibility', function () {
expect(snapshot.children[0]!.roledescription).toBeUndefined(); expect(snapshot.children[0]!.roledescription).toBeUndefined();
}); });
it('orientation', async () => { it('orientation', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<a href="" role="slider" aria-orientation="vertical">11</a>' '<a href="" role="slider" aria-orientation="vertical">11</a>'
@ -236,7 +229,7 @@ describe('Accessibility', function () {
expect(snapshot.children[0]!.orientation).toEqual('vertical'); expect(snapshot.children[0]!.orientation).toEqual('vertical');
}); });
it('autocomplete', async () => { it('autocomplete', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<input type="number" aria-autocomplete="list" />'); await page.setContent('<input type="number" aria-autocomplete="list" />');
const snapshot = await page.accessibility.snapshot(); const snapshot = await page.accessibility.snapshot();
@ -246,7 +239,7 @@ describe('Accessibility', function () {
expect(snapshot.children[0]!.autocomplete).toEqual('list'); expect(snapshot.children[0]!.autocomplete).toEqual('list');
}); });
it('multiselectable', async () => { it('multiselectable', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div role="grid" tabIndex=-1 aria-multiselectable=true>hey</div>' '<div role="grid" tabIndex=-1 aria-multiselectable=true>hey</div>'
@ -258,7 +251,7 @@ describe('Accessibility', function () {
expect(snapshot.children[0]!.multiselectable).toEqual(true); expect(snapshot.children[0]!.multiselectable).toEqual(true);
}); });
it('keyshortcuts', async () => { it('keyshortcuts', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div role="grid" tabIndex=-1 aria-keyshortcuts="foo">hey</div>' '<div role="grid" tabIndex=-1 aria-keyshortcuts="foo">hey</div>'
@ -271,7 +264,7 @@ describe('Accessibility', function () {
}); });
describe('filtering children of leaf nodes', function () { describe('filtering children of leaf nodes', function () {
it('should not report text nodes inside controls', async () => { it('should not report text nodes inside controls', async () => {
const {page, isFirefox} = getTestState(); const {page, isFirefox} = await getTestState();
await page.setContent(` await page.setContent(`
<div role="tablist"> <div role="tablist">
@ -312,7 +305,7 @@ describe('Accessibility', function () {
expect(await page.accessibility.snapshot()).toEqual(golden); expect(await page.accessibility.snapshot()).toEqual(golden);
}); });
it('rich text editable fields should have children', async () => { it('rich text editable fields should have children', async () => {
const {page, isFirefox} = getTestState(); const {page, isFirefox} = await getTestState();
await page.setContent(` await page.setContent(`
<div contenteditable="true"> <div contenteditable="true">
@ -354,7 +347,7 @@ describe('Accessibility', function () {
expect(snapshot.children[0]).toEqual(golden); expect(snapshot.children[0]).toEqual(golden);
}); });
it('rich text editable fields with role should have children', async () => { it('rich text editable fields with role should have children', async () => {
const {page, isFirefox} = getTestState(); const {page, isFirefox} = await getTestState();
await page.setContent(` await page.setContent(`
<div contenteditable="true" role='textbox'> <div contenteditable="true" role='textbox'>
@ -394,7 +387,7 @@ describe('Accessibility', function () {
// Firefox does not support contenteditable="plaintext-only". // Firefox does not support contenteditable="plaintext-only".
describe('plaintext contenteditable', function () { describe('plaintext contenteditable', function () {
it('plain text field with role should not have children', async () => { it('plain text field with role should not have children', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(` await page.setContent(`
<div contenteditable="plaintext-only" role='textbox'>Edit this image:<img src="fakeimage.png" alt="my fake image"></div>`); <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 () => { 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(` await page.setContent(`
<div role="textbox" tabIndex=0 aria-checked="true" aria-label="my favorite textbox"> <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); expect(snapshot.children[0]).toEqual(golden);
}); });
it('checkbox with and tabIndex and label should not have children', async () => { it('checkbox with and tabIndex and label should not have children', async () => {
const {page, isFirefox} = getTestState(); const {page, isFirefox} = await getTestState();
await page.setContent(` await page.setContent(`
<div role="checkbox" tabIndex=0 aria-checked="true" aria-label="my favorite checkbox"> <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); expect(snapshot.children[0]).toEqual(golden);
}); });
it('checkbox without label should not have children', async () => { it('checkbox without label should not have children', async () => {
const {page, isFirefox} = getTestState(); const {page, isFirefox} = await getTestState();
await page.setContent(` await page.setContent(`
<div role="checkbox" aria-checked="true"> <div role="checkbox" aria-checked="true">
@ -484,7 +477,7 @@ describe('Accessibility', function () {
describe('root option', function () { describe('root option', function () {
it('should work a button', async () => { it('should work a button', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(`<button>My Button</button>`); await page.setContent(`<button>My Button</button>`);
@ -495,7 +488,7 @@ describe('Accessibility', function () {
}); });
}); });
it('should work an input', async () => { it('should work an input', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(`<input title="My Input" value="My Value">`); await page.setContent(`<input title="My Input" value="My Value">`);
@ -507,7 +500,7 @@ describe('Accessibility', function () {
}); });
}); });
it('should work a menu', async () => { it('should work a menu', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(` await page.setContent(`
<div role="menu" title="My Menu"> <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 () => { 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>`); await page.setContent(`<button>My Button</button>`);
const button = (await page.$('button'))!; const button = (await page.$('button'))!;
@ -540,7 +533,7 @@ describe('Accessibility', function () {
expect(await page.accessibility.snapshot({root: button})).toEqual(null); expect(await page.accessibility.snapshot({root: button})).toEqual(null);
}); });
it('should support the interestingOnly option', async () => { it('should support the interestingOnly option', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(`<div><button>My Button</button></div>`); await page.setContent(`<div><button>My Button</button></div>`);
const div = (await page.$('div'))!; const div = (await page.$('div'))!;

View File

@ -20,26 +20,16 @@ import expect from 'expect';
import {TimeoutError} from 'puppeteer'; import {TimeoutError} from 'puppeteer';
import type {ElementHandle} from 'puppeteer-core/internal/api/ElementHandle.js'; import type {ElementHandle} from 'puppeteer-core/internal/api/ElementHandle.js';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {attachFrame, detachFrame} from './utils.js'; import {attachFrame, detachFrame} from './utils.js';
describe('AriaQueryHandler', () => { describe('AriaQueryHandler', () => {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('parseAriaSelector', () => { describe('parseAriaSelector', () => {
beforeEach(async () => { it('should find button', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<button id="btn" role="button"> Submit button and some spaces </button>' '<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) => { const expectFound = async (button: ElementHandle | null) => {
assert(button); assert(button);
const id = await button.evaluate((button: Element) => { const id = await button.evaluate((button: Element) => {
@ -95,7 +85,7 @@ describe('AriaQueryHandler', () => {
describe('queryOne', () => { describe('queryOne', () => {
it('should find button by role', async () => { it('should find button by role', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div id="div"><button id="btn" role="button">Submit</button></div>' '<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 () => { it('should find button by name and role', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div id="div"><button id="btn" role="button">Submit</button></div>' '<div id="div"><button id="btn" role="button">Submit</button></div>'
); );
@ -123,7 +113,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should find first matching element', async () => { it('should find first matching element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
` `
<div role="menu" id="mnu1" aria-label="menu div"></div> <div role="menu" id="mnu1" aria-label="menu div"></div>
@ -140,7 +130,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should find by name', async () => { it('should find by name', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
` `
<div role="menu" id="mnu1" aria-label="menu-label1">menu div</div> <div role="menu" id="mnu1" aria-label="menu-label1">menu div</div>
@ -157,7 +147,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should find by name', async () => { it('should find by name', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
` `
<div role="menu" id="mnu1" aria-label="menu-label1">menu div</div> <div role="menu" id="mnu1" aria-label="menu-label1">menu div</div>
@ -176,7 +166,7 @@ describe('AriaQueryHandler', () => {
describe('queryAll', () => { describe('queryAll', () => {
it('should find menu by name', async () => { it('should find menu by name', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
` `
<div role="menu" id="mnu1" aria-label="menu div"></div> <div role="menu" id="mnu1" aria-label="menu div"></div>
@ -200,7 +190,7 @@ describe('AriaQueryHandler', () => {
it('$$eval should handle many elements', async function () { it('$$eval should handle many elements', async function () {
this.timeout(25_000); this.timeout(25_000);
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(''); await page.setContent('');
await page.evaluate( await page.evaluate(
` `
@ -226,14 +216,14 @@ describe('AriaQueryHandler', () => {
}; };
it('should immediately resolve promise if node exists', async () => { 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.goto(server.EMPTY_PAGE);
await page.evaluate(addElement, 'button'); await page.evaluate(addElement, 'button');
await page.waitForSelector('aria/[role="button"]'); await page.waitForSelector('aria/[role="button"]');
}); });
it('should work for ElementHandle.waitForSelector', async () => { it('should work for ElementHandle.waitForSelector', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => { await page.evaluate(() => {
return (document.body.innerHTML = `<div><button>test</button></div>`); return (document.body.innerHTML = `<div><button>test</button></div>`);
@ -243,7 +233,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should persist query handler bindings across reloads', async () => { 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.goto(server.EMPTY_PAGE);
await page.evaluate(addElement, 'button'); await page.evaluate(addElement, 'button');
await page.waitForSelector('aria/[role="button"]'); await page.waitForSelector('aria/[role="button"]');
@ -253,7 +243,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should persist query handler bindings across navigations', async () => { 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. // Reset page but make sure that execution context ids start with 1.
await page.goto('data:text/html,'); await page.goto('data:text/html,');
@ -269,7 +259,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should work independently of `exposeFunction`', async () => { it('should work independently of `exposeFunction`', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.exposeFunction('ariaQuerySelector', (a: number, b: number) => { await page.exposeFunction('ariaQuerySelector', (a: number, b: number) => {
return a + b; return a + b;
@ -281,7 +271,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should work with removed MutationObserver', async () => { it('should work with removed MutationObserver', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.evaluate(() => { await page.evaluate(() => {
// @ts-expect-error This is the point of the test. // @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 () => { it('should resolve promise when node is added', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const frame = page.mainFrame(); const frame = page.mainFrame();
@ -315,7 +305,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should work when node is added through innerHTML', async () => { 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); await page.goto(server.EMPTY_PAGE);
const watchdog = page.waitForSelector('aria/name'); const watchdog = page.waitForSelector('aria/name');
@ -328,7 +318,7 @@ describe('AriaQueryHandler', () => {
}); });
it('Page.waitForSelector is shortcut for main frame', async () => { 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 page.goto(server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE); await attachFrame(page, 'frame1', server.EMPTY_PAGE);
@ -341,7 +331,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should run in specified frame', async () => { 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, 'frame1', server.EMPTY_PAGE);
await attachFrame(page, 'frame2', server.EMPTY_PAGE); await attachFrame(page, 'frame2', server.EMPTY_PAGE);
@ -357,7 +347,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should throw when frame is detached', async () => { it('should throw when frame is detached', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await attachFrame(page, 'frame1', server.EMPTY_PAGE); await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = page.frames()[1]; const frame = page.frames()[1];
@ -376,7 +366,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should survive cross-process navigation', async () => { it('should survive cross-process navigation', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
let imgFound = false; let imgFound = false;
const waitForSelector = page const waitForSelector = page
@ -394,7 +384,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should wait for visible', async () => { it('should wait for visible', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let divFound = false; let divFound = false;
const waitForSelector = page const waitForSelector = page
@ -420,7 +410,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should wait for visible recursively', async () => { it('should wait for visible recursively', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let divVisible = false; let divVisible = false;
const waitForSelector = page const waitForSelector = page
@ -449,7 +439,7 @@ describe('AriaQueryHandler', () => {
}); });
it('hidden should wait for visibility: hidden', async () => { it('hidden should wait for visibility: hidden', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let divHidden = false; let divHidden = false;
await page.setContent( await page.setContent(
@ -475,7 +465,7 @@ describe('AriaQueryHandler', () => {
}); });
it('hidden should wait for display: none', async () => { it('hidden should wait for display: none', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let divHidden = false; let divHidden = false;
await page.setContent( await page.setContent(
@ -501,7 +491,7 @@ describe('AriaQueryHandler', () => {
}); });
it('hidden should wait for removal', async () => { it('hidden should wait for removal', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(`<div role='main'>text</div>`); await page.setContent(`<div role='main'>text</div>`);
let divRemoved = false; let divRemoved = false;
@ -523,7 +513,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should return null if waiting to hide non-existing element', async () => { 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', { const handle = await page.waitForSelector('aria/non-existing', {
hidden: true, hidden: true,
@ -532,7 +522,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should respect timeout', async () => { it('should respect timeout', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const error = await page const error = await page
.waitForSelector('aria/[role="button"]', { .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 () => { 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>`); await page.setContent(`<div role='main'>text</div>`);
const promise = page.waitForSelector('aria/[role="main"]', { const promise = page.waitForSelector('aria/[role="main"]', {
@ -562,7 +552,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should respond to node attribute mutation', async () => { it('should respond to node attribute mutation', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let divFound = false; let divFound = false;
const waitForSelector = page const waitForSelector = page
@ -584,7 +574,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should return the element handle', async () => { it('should return the element handle', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const waitForSelector = page.waitForSelector('aria/zombo').catch(err => { const waitForSelector = page.waitForSelector('aria/zombo').catch(err => {
return err; return err;
@ -598,7 +588,7 @@ describe('AriaQueryHandler', () => {
}); });
it('should have correct stack trace for timeout', async () => { it('should have correct stack trace for timeout', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page.waitForSelector('aria/zombo', {timeout: 10}).catch(error_ => { await page.waitForSelector('aria/zombo', {timeout: 10}).catch(error_ => {
@ -611,9 +601,9 @@ describe('AriaQueryHandler', () => {
}); });
describe('queryOne (Chromium web test)', () => { describe('queryOne (Chromium web test)', () => {
beforeEach(async () => { async function setupPage(): ReturnType<typeof getTestState> {
const {page} = getTestState(); const state = await getTestState();
await page.setContent( await state.page.setContent(
` `
<h2 id="shown">title</h2> <h2 id="shown">title</h2>
<h2 id="hidden" aria-hidden="true">title</h2> <h2 id="hidden" aria-hidden="true">title</h2>
@ -658,7 +648,8 @@ describe('AriaQueryHandler', () => {
<div aria-describedby="node30"></div> <div aria-describedby="node30"></div>
` `
); );
}); return state;
}
const getIds = async (elements: ElementHandle[]) => { const getIds = async (elements: ElementHandle[]) => {
return Promise.all( return Promise.all(
elements.map(element => { elements.map(element => {
@ -669,25 +660,25 @@ describe('AriaQueryHandler', () => {
); );
}; };
it('should find by name "foo"', async () => { it('should find by name "foo"', async () => {
const {page} = getTestState(); const {page} = await setupPage();
const found = await page.$$('aria/foo'); const found = await page.$$('aria/foo');
const ids = await getIds(found); const ids = await getIds(found);
expect(ids).toEqual(['node3', 'node5', 'node6']); expect(ids).toEqual(['node3', 'node5', 'node6']);
}); });
it('should find by name "bar"', async () => { it('should find by name "bar"', async () => {
const {page} = getTestState(); const {page} = await setupPage();
const found = await page.$$('aria/bar'); const found = await page.$$('aria/bar');
const ids = await getIds(found); const ids = await getIds(found);
expect(ids).toEqual(['node1', 'node2', 'node8']); expect(ids).toEqual(['node1', 'node2', 'node8']);
}); });
it('should find treeitem by name', async () => { it('should find treeitem by name', async () => {
const {page} = getTestState(); const {page} = await setupPage();
const found = await page.$$('aria/item1 item2 item3'); const found = await page.$$('aria/item1 item2 item3');
const ids = await getIds(found); const ids = await getIds(found);
expect(ids).toEqual(['node30']); expect(ids).toEqual(['node30']);
}); });
it('should find by role "button"', async () => { it('should find by role "button"', async () => {
const {page} = getTestState(); const {page} = await setupPage();
const found = (await page.$$('aria/[role="button"]')) as Array< const found = (await page.$$('aria/[role="button"]')) as Array<
ElementHandle<HTMLButtonElement> ElementHandle<HTMLButtonElement>
>; >;
@ -702,13 +693,13 @@ describe('AriaQueryHandler', () => {
]); ]);
}); });
it('should find by role "heading"', async () => { it('should find by role "heading"', async () => {
const {page} = getTestState(); const {page} = await setupPage();
const found = await page.$$('aria/[role="heading"]'); const found = await page.$$('aria/[role="heading"]');
const ids = await getIds(found); const ids = await getIds(found);
expect(ids).toEqual(['shown', 'hidden', 'node11', 'node13']); expect(ids).toEqual(['shown', 'hidden', 'node11', 'node13']);
}); });
it('should find both ignored and unignored', async () => { it('should find both ignored and unignored', async () => {
const {page} = getTestState(); const {page} = await setupPage();
const found = await page.$$('aria/title'); const found = await page.$$('aria/title');
const ids = await getIds(found); const ids = await getIds(found);
expect(ids).toEqual(['shown']); expect(ids).toEqual(['shown']);

View File

@ -16,14 +16,12 @@
import expect from 'expect'; import expect from 'expect';
import {getTestState, setupTestBrowserHooks} from './mocha-utils.js'; import {getTestState} from './mocha-utils.js';
describe('Browser specs', function () { describe('Browser specs', function () {
setupTestBrowserHooks();
describe('Browser.version', function () { describe('Browser.version', function () {
it('should return version', async () => { it('should return version', async () => {
const {browser} = getTestState(); const {browser} = await getTestState();
const version = await browser.version(); const version = await browser.version();
expect(version.length).toBeGreaterThan(0); expect(version.length).toBeGreaterThan(0);
@ -33,7 +31,7 @@ describe('Browser specs', function () {
describe('Browser.userAgent', function () { describe('Browser.userAgent', function () {
it('should include WebKit', async () => { it('should include WebKit', async () => {
const {browser, isChrome} = getTestState(); const {browser, isChrome} = await getTestState();
const userAgent = await browser.userAgent(); const userAgent = await browser.userAgent();
expect(userAgent.length).toBeGreaterThan(0); expect(userAgent.length).toBeGreaterThan(0);
@ -47,7 +45,7 @@ describe('Browser specs', function () {
describe('Browser.target', function () { describe('Browser.target', function () {
it('should return browser target', async () => { it('should return browser target', async () => {
const {browser} = getTestState(); const {browser} = await getTestState();
const target = browser.target(); const target = browser.target();
expect(target.type()).toBe('browser'); expect(target.type()).toBe('browser');
@ -56,13 +54,13 @@ describe('Browser specs', function () {
describe('Browser.process', function () { describe('Browser.process', function () {
it('should return child_process instance', async () => { it('should return child_process instance', async () => {
const {browser} = getTestState(); const {browser} = await getTestState();
const process = await browser.process(); const process = await browser.process();
expect(process!.pid).toBeGreaterThan(0); expect(process!.pid).toBeGreaterThan(0);
}); });
it('should not return child_process for remote browser', async () => { it('should not return child_process for remote browser', async () => {
const {browser, puppeteer} = getTestState(); const {browser, puppeteer} = await getTestState();
const browserWSEndpoint = browser.wsEndpoint(); const browserWSEndpoint = browser.wsEndpoint();
const remoteBrowser = await puppeteer.connect({ const remoteBrowser = await puppeteer.connect({
@ -75,7 +73,7 @@ describe('Browser specs', function () {
describe('Browser.isConnected', () => { describe('Browser.isConnected', () => {
it('should set the browser connected state', async () => { it('should set the browser connected state', async () => {
const {browser, puppeteer} = getTestState(); const {browser, puppeteer} = await getTestState();
const browserWSEndpoint = browser.wsEndpoint(); const browserWSEndpoint = browser.wsEndpoint();
const newBrowser = await puppeteer.connect({ const newBrowser = await puppeteer.connect({

View File

@ -17,13 +17,14 @@
import expect from 'expect'; import expect from 'expect';
import {TimeoutError} from 'puppeteer'; import {TimeoutError} from 'puppeteer';
import {getTestState, setupTestBrowserHooks} from './mocha-utils.js'; import {getTestState} from './mocha-utils.js';
import {waitEvent} from './utils.js'; import {waitEvent} from './utils.js';
describe('BrowserContext', function () { describe('BrowserContext', function () {
setupTestBrowserHooks();
it('should have default context', async () => { it('should have default context', async () => {
const {browser} = getTestState(); const {browser} = await getTestState({
skipContextCreation: true,
});
expect(browser.browserContexts()).toHaveLength(1); expect(browser.browserContexts()).toHaveLength(1);
const defaultContext = browser.browserContexts()[0]!; const defaultContext = browser.browserContexts()[0]!;
expect(defaultContext!.isIncognito()).toBe(false); expect(defaultContext!.isIncognito()).toBe(false);
@ -35,7 +36,9 @@ describe('BrowserContext', function () {
expect(error.message).toContain('cannot be closed'); expect(error.message).toContain('cannot be closed');
}); });
it('should create new incognito context', async () => { it('should create new incognito context', async () => {
const {browser} = getTestState(); const {browser} = await getTestState({
skipContextCreation: true,
});
expect(browser.browserContexts()).toHaveLength(1); expect(browser.browserContexts()).toHaveLength(1);
const context = await browser.createIncognitoBrowserContext(); const context = await browser.createIncognitoBrowserContext();
@ -46,7 +49,9 @@ describe('BrowserContext', function () {
expect(browser.browserContexts()).toHaveLength(1); expect(browser.browserContexts()).toHaveLength(1);
}); });
it('should close all belonging targets once closing context', async () => { 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); expect(await browser.pages()).toHaveLength(1);
@ -59,10 +64,8 @@ describe('BrowserContext', function () {
expect(await browser.pages()).toHaveLength(1); expect(await browser.pages()).toHaveLength(1);
}); });
it('window.open should use parent tab context', async () => { 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); await page.goto(server.EMPTY_PAGE);
const [popupTarget] = await Promise.all([ const [popupTarget] = await Promise.all([
waitEvent(browser, 'targetcreated'), waitEvent(browser, 'targetcreated'),
@ -71,12 +74,10 @@ describe('BrowserContext', function () {
}, server.EMPTY_PAGE), }, server.EMPTY_PAGE),
]); ]);
expect(popupTarget.browserContext()).toBe(context); expect(popupTarget.browserContext()).toBe(context);
await context.close();
}); });
it('should fire target events', async () => { it('should fire target events', async () => {
const {browser, server} = getTestState(); const {server, context} = await getTestState();
const context = await browser.createIncognitoBrowserContext();
const events: any[] = []; const events: any[] = [];
context.on('targetcreated', target => { context.on('targetcreated', target => {
return events.push('CREATED: ' + target.url()); return events.push('CREATED: ' + target.url());
@ -95,12 +96,10 @@ describe('BrowserContext', function () {
`CHANGED: ${server.EMPTY_PAGE}`, `CHANGED: ${server.EMPTY_PAGE}`,
`DESTROYED: ${server.EMPTY_PAGE}`, `DESTROYED: ${server.EMPTY_PAGE}`,
]); ]);
await context.close();
}); });
it('should wait for a target', async () => { it('should wait for a target', async () => {
const {browser, server} = getTestState(); const {server, context} = await getTestState();
const context = await browser.createIncognitoBrowserContext();
let resolved = false; let resolved = false;
const targetPromise = context.waitForTarget(target => { const targetPromise = context.waitForTarget(target => {
@ -131,11 +130,10 @@ describe('BrowserContext', function () {
throw error; throw error;
} }
} }
await context.close();
}); });
it('should timeout waiting for a non-existent target', async () => { 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 context = await browser.createIncognitoBrowserContext();
const error = await context const error = await context
@ -155,7 +153,9 @@ describe('BrowserContext', function () {
}); });
it('should isolate localStorage and cookies', async () => { it('should isolate localStorage and cookies', async () => {
const {browser, server} = getTestState(); const {browser, server} = await getTestState({
skipContextCreation: true,
});
// Create two incognito contexts. // Create two incognito contexts.
const context1 = await browser.createIncognitoBrowserContext(); const context1 = await browser.createIncognitoBrowserContext();
@ -215,7 +215,9 @@ describe('BrowserContext', function () {
}); });
it('should work across sessions', async () => { it('should work across sessions', async () => {
const {browser, puppeteer} = getTestState(); const {browser, puppeteer} = await getTestState({
skipContextCreation: true,
});
expect(browser.browserContexts()).toHaveLength(1); expect(browser.browserContexts()).toHaveLength(1);
const context = await browser.createIncognitoBrowserContext(); const context = await browser.createIncognitoBrowserContext();
@ -230,12 +232,15 @@ describe('BrowserContext', function () {
}); });
it('should provide a context id', async () => { it('should provide a context id', async () => {
const {browser} = getTestState(); const {browser} = await getTestState({
skipContextCreation: true,
});
expect(browser.browserContexts()).toHaveLength(1); expect(browser.browserContexts()).toHaveLength(1);
expect(browser.browserContexts()[0]!.id).toBeUndefined(); expect(browser.browserContexts()[0]!.id).toBeUndefined();
const context = await browser.createIncognitoBrowserContext(); const context = await browser.createIncognitoBrowserContext();
console.log('2');
expect(browser.browserContexts()).toHaveLength(2); expect(browser.browserContexts()).toHaveLength(2);
expect(browser.browserContexts()[1]!.id).toBeDefined(); expect(browser.browserContexts()[1]!.id).toBeDefined();
await context.close(); await context.close();

View File

@ -17,12 +17,7 @@ import {IncomingMessage} from 'http';
import expect from 'expect'; import expect from 'expect';
import { import {getTestState, launch} from './mocha-utils.js';
getTestState,
launch,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {waitEvent} from './utils.js'; import {waitEvent} from './utils.js';
// TODO: rename this test suite to launch/connect test suite as it actually // 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('Chromium-Specific Launcher tests', function () {
describe('Puppeteer.launch |browserURL| option', function () { describe('Puppeteer.launch |browserURL| option', function () {
it('should be able to connect using browserUrl, with and without trailing slash', async () => { it('should be able to connect using browserUrl, with and without trailing slash', async () => {
const {defaultBrowserOptions, puppeteer} = getTestState(); const {close, puppeteer} = await launch({
args: ['--remote-debugging-port=21222'],
const {close} = await launch( });
Object.assign({}, defaultBrowserOptions, {
args: ['--remote-debugging-port=21222'],
})
);
try { try {
const browserURL = 'http://127.0.0.1:21222'; 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 () => { it('should throw when using both browserWSEndpoint and browserURL', async () => {
const {defaultBrowserOptions, puppeteer} = getTestState(); const {browser, close, puppeteer} = await launch({
args: ['--remote-debugging-port=21222'],
const {browser, close} = await launch( });
Object.assign({}, defaultBrowserOptions, {
args: ['--remote-debugging-port=21222'],
})
);
try { try {
const browserURL = 'http://127.0.0.1:21222'; 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 () => { it('should throw when trying to connect to non-existing browser', async () => {
const {defaultBrowserOptions, puppeteer} = getTestState(); const {close, puppeteer} = await launch({
args: ['--remote-debugging-port=21222'],
const {close} = await launch( });
Object.assign({}, defaultBrowserOptions, {
args: ['--remote-debugging-port=21222'],
})
);
try { try {
const browserURL = 'http://127.0.0.1:32333'; const browserURL = 'http://127.0.0.1:32333';
@ -116,9 +99,7 @@ describe('Chromium-Specific Launcher tests', function () {
describe('Puppeteer.launch |pipe| option', function () { describe('Puppeteer.launch |pipe| option', function () {
it('should support the pipe option', async () => { it('should support the pipe option', async () => {
const {defaultBrowserOptions} = getTestState(); const {browser, close} = await launch({pipe: true}, {createPage: false});
const options = Object.assign({pipe: true}, defaultBrowserOptions);
const {browser, close} = await launch(options, {createPage: false});
try { try {
expect(await browser.pages()).toHaveLength(1); expect(await browser.pages()).toHaveLength(1);
expect(browser.wsEndpoint()).toBe(''); expect(browser.wsEndpoint()).toBe('');
@ -130,7 +111,7 @@ describe('Chromium-Specific Launcher tests', function () {
} }
}); });
it('should support the pipe argument', async () => { it('should support the pipe argument', async () => {
const {defaultBrowserOptions} = getTestState(); const {defaultBrowserOptions} = await getTestState({skipLaunch: true});
const options = Object.assign({}, defaultBrowserOptions); const options = Object.assign({}, defaultBrowserOptions);
options.args = ['--remote-debugging-pipe'].concat(options.args || []); options.args = ['--remote-debugging-pipe'].concat(options.args || []);
const {browser, close} = await launch(options); 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 () => { it('should fire "disconnected" when closing with pipe', async () => {
const {defaultBrowserOptions} = getTestState(); const {browser, close} = await launch({pipe: true});
const options = Object.assign({pipe: true}, defaultBrowserOptions);
const {browser, close} = await launch(options);
try { try {
const disconnectedEventPromise = waitEvent(browser, 'disconnected'); const disconnectedEventPromise = waitEvent(browser, 'disconnected');
// Emulate user exiting browser. // Emulate user exiting browser.
@ -160,10 +139,8 @@ describe('Chromium-Specific Launcher tests', function () {
}); });
describe('Chromium-Specific Page Tests', function () { describe('Chromium-Specific Page Tests', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('Page.setRequestInterception should work with intervention headers', async () => { it('Page.setRequestInterception should work with intervention headers', async () => {
const {server, page} = getTestState(); const {server, page} = await getTestState();
server.setRoute('/intervention', (_req, res) => { server.setRoute('/intervention', (_req, res) => {
return res.end(` return res.end(`

View File

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

View File

@ -15,32 +15,23 @@
*/ */
import expect from 'expect'; import expect from 'expect';
import { import {expectCookieEquals, getTestState, launch} from './mocha-utils.js';
expectCookieEquals,
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
launch,
} from './mocha-utils.js';
describe('Cookie specs', () => { describe('Cookie specs', () => {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Page.cookies', function () { describe('Page.cookies', function () {
it('should return no cookies in pristine browser context', async () => { 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); await page.goto(server.EMPTY_PAGE);
expectCookieEquals(await page.cookies(), []); await expectCookieEquals(await page.cookies(), []);
}); });
it('should get a cookie', async () => { it('should get a cookie', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => { await page.evaluate(() => {
document.cookie = 'username=John Doe'; document.cookie = 'username=John Doe';
}); });
expectCookieEquals(await page.cookies(), [ await expectCookieEquals(await page.cookies(), [
{ {
name: 'username', name: 'username',
value: 'John Doe', value: 'John Doe',
@ -57,7 +48,7 @@ describe('Cookie specs', () => {
]); ]);
}); });
it('should properly report httpOnly cookie', async () => { it('should properly report httpOnly cookie', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.setRoute('/empty.html', (_req, res) => { server.setRoute('/empty.html', (_req, res) => {
res.setHeader('Set-Cookie', 'a=b; HttpOnly; Path=/'); res.setHeader('Set-Cookie', 'a=b; HttpOnly; Path=/');
res.end(); res.end();
@ -68,7 +59,7 @@ describe('Cookie specs', () => {
expect(cookies[0]!.httpOnly).toBe(true); expect(cookies[0]!.httpOnly).toBe(true);
}); });
it('should properly report "Strict" sameSite cookie', async () => { it('should properly report "Strict" sameSite cookie', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.setRoute('/empty.html', (_req, res) => { server.setRoute('/empty.html', (_req, res) => {
res.setHeader('Set-Cookie', 'a=b; SameSite=Strict'); res.setHeader('Set-Cookie', 'a=b; SameSite=Strict');
res.end(); res.end();
@ -79,7 +70,7 @@ describe('Cookie specs', () => {
expect(cookies[0]!.sameSite).toBe('Strict'); expect(cookies[0]!.sameSite).toBe('Strict');
}); });
it('should properly report "Lax" sameSite cookie', async () => { it('should properly report "Lax" sameSite cookie', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.setRoute('/empty.html', (_req, res) => { server.setRoute('/empty.html', (_req, res) => {
res.setHeader('Set-Cookie', 'a=b; SameSite=Lax'); res.setHeader('Set-Cookie', 'a=b; SameSite=Lax');
res.end(); res.end();
@ -90,7 +81,7 @@ describe('Cookie specs', () => {
expect(cookies[0]!.sameSite).toBe('Lax'); expect(cookies[0]!.sameSite).toBe('Lax');
}); });
it('should get multiple cookies', async () => { it('should get multiple cookies', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => { await page.evaluate(() => {
document.cookie = 'username=John Doe'; document.cookie = 'username=John Doe';
@ -100,7 +91,7 @@ describe('Cookie specs', () => {
cookies.sort((a, b) => { cookies.sort((a, b) => {
return a.name.localeCompare(b.name); return a.name.localeCompare(b.name);
}); });
expectCookieEquals(cookies, [ await expectCookieEquals(cookies, [
{ {
name: 'password', name: 'password',
value: '1234', value: '1234',
@ -130,7 +121,7 @@ describe('Cookie specs', () => {
]); ]);
}); });
it('should get cookies from multiple urls', async () => { it('should get cookies from multiple urls', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setCookie( await page.setCookie(
{ {
url: 'https://foo.com', url: 'https://foo.com',
@ -152,7 +143,7 @@ describe('Cookie specs', () => {
cookies.sort((a, b) => { cookies.sort((a, b) => {
return a.name.localeCompare(b.name); return a.name.localeCompare(b.name);
}); });
expectCookieEquals(cookies, [ await expectCookieEquals(cookies, [
{ {
name: 'birdo', name: 'birdo',
value: 'tweets', value: 'tweets',
@ -186,7 +177,7 @@ describe('Cookie specs', () => {
}); });
describe('Page.setCookie', function () { describe('Page.setCookie', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setCookie({ await page.setCookie({
@ -200,7 +191,7 @@ describe('Cookie specs', () => {
).toEqual('password=123456'); ).toEqual('password=123456');
}); });
it('should isolate cookies in browser contexts', async () => { 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 anotherContext = await browser.createIncognitoBrowserContext();
const anotherPage = await anotherContext.newPage(); const anotherPage = await anotherContext.newPage();
@ -222,7 +213,7 @@ describe('Cookie specs', () => {
await anotherContext.close(); await anotherContext.close();
}); });
it('should set multiple cookies', async () => { it('should set multiple cookies', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setCookie( await page.setCookie(
@ -247,7 +238,7 @@ describe('Cookie specs', () => {
expect(cookieStrings).toEqual(['foo=bar', 'password=123456']); expect(cookieStrings).toEqual(['foo=bar', 'password=123456']);
}); });
it('should have |expires| set to |-1| for session cookies', async () => { 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.goto(server.EMPTY_PAGE);
await page.setCookie({ await page.setCookie({
@ -259,7 +250,7 @@ describe('Cookie specs', () => {
expect(cookies[0]!.expires).toBe(-1); expect(cookies[0]!.expires).toBe(-1);
}); });
it('should set cookie with reasonable defaults', async () => { 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.goto(server.EMPTY_PAGE);
await page.setCookie({ await page.setCookie({
@ -267,7 +258,7 @@ describe('Cookie specs', () => {
value: '123456', value: '123456',
}); });
const cookies = await page.cookies(); const cookies = await page.cookies();
expectCookieEquals( await expectCookieEquals(
cookies.sort((a, b) => { cookies.sort((a, b) => {
return a.name.localeCompare(b.name); return a.name.localeCompare(b.name);
}), }),
@ -290,7 +281,7 @@ describe('Cookie specs', () => {
); );
}); });
it('should set a cookie with a path', async () => { 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.goto(server.PREFIX + '/grid.html');
await page.setCookie({ await page.setCookie({
@ -298,7 +289,7 @@ describe('Cookie specs', () => {
value: 'GRID', value: 'GRID',
path: '/grid.html', path: '/grid.html',
}); });
expectCookieEquals(await page.cookies(), [ await expectCookieEquals(await page.cookies(), [
{ {
name: 'gridcookie', name: 'gridcookie',
value: 'GRID', value: 'GRID',
@ -316,13 +307,13 @@ describe('Cookie specs', () => {
]); ]);
expect(await page.evaluate('document.cookie')).toBe('gridcookie=GRID'); expect(await page.evaluate('document.cookie')).toBe('gridcookie=GRID');
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
expectCookieEquals(await page.cookies(), []); await expectCookieEquals(await page.cookies(), []);
expect(await page.evaluate('document.cookie')).toBe(''); expect(await page.evaluate('document.cookie')).toBe('');
await page.goto(server.PREFIX + '/grid.html'); await page.goto(server.PREFIX + '/grid.html');
expect(await page.evaluate('document.cookie')).toBe('gridcookie=GRID'); expect(await page.evaluate('document.cookie')).toBe('gridcookie=GRID');
}); });
it('should not set a cookie on a blank page', async () => { it('should not set a cookie on a blank page', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.goto('about:blank'); await page.goto('about:blank');
let error!: Error; let error!: Error;
@ -336,7 +327,7 @@ describe('Cookie specs', () => {
); );
}); });
it('should not set a cookie with blank page URL', async () => { it('should not set a cookie with blank page URL', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
let error!: Error; let error!: Error;
await page.goto(server.EMPTY_PAGE); 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 () => { it('should not set a cookie on a data URL page', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page.goto('data:,Hello%2C%20World!'); 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 () => { 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); await page.goto(server.EMPTY_PAGE);
const SECURE_URL = 'https://example.com'; const SECURE_URL = 'https://example.com';
@ -380,7 +371,7 @@ describe('Cookie specs', () => {
expect(cookie!.secure).toBe(true); expect(cookie!.secure).toBe(true);
}); });
it('should be able to set insecure cookie for HTTP website', async () => { 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); await page.goto(server.EMPTY_PAGE);
const HTTP_URL = 'http://example.com'; const HTTP_URL = 'http://example.com';
@ -393,7 +384,7 @@ describe('Cookie specs', () => {
expect(cookie!.secure).toBe(false); expect(cookie!.secure).toBe(false);
}); });
it('should set a cookie on a different domain', async () => { 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.goto(server.EMPTY_PAGE);
await page.setCookie({ await page.setCookie({
@ -402,8 +393,8 @@ describe('Cookie specs', () => {
value: 'best', value: 'best',
}); });
expect(await page.evaluate('document.cookie')).toBe(''); expect(await page.evaluate('document.cookie')).toBe('');
expectCookieEquals(await page.cookies(), []); await expectCookieEquals(await page.cookies(), []);
expectCookieEquals(await page.cookies('https://www.example.com'), [ await expectCookieEquals(await page.cookies('https://www.example.com'), [
{ {
name: 'example-cookie', name: 'example-cookie',
value: 'best', value: 'best',
@ -421,7 +412,7 @@ describe('Cookie specs', () => {
]); ]);
}); });
it('should set cookies from a frame', async () => { 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.goto(server.PREFIX + '/grid.html');
await page.setCookie({name: 'localhost-cookie', value: 'best'}); await page.setCookie({name: 'localhost-cookie', value: 'best'});
@ -446,7 +437,7 @@ describe('Cookie specs', () => {
); );
expect(await page.frames()[1]!.evaluate('document.cookie')).toBe(''); expect(await page.frames()[1]!.evaluate('document.cookie')).toBe('');
expectCookieEquals(await page.cookies(), [ await expectCookieEquals(await page.cookies(), [
{ {
name: 'localhost-cookie', name: 'localhost-cookie',
value: 'best', value: 'best',
@ -463,28 +454,28 @@ describe('Cookie specs', () => {
}, },
]); ]);
expectCookieEquals(await page.cookies(server.CROSS_PROCESS_PREFIX), [ await expectCookieEquals(
{ await page.cookies(server.CROSS_PROCESS_PREFIX),
name: '127-cookie', [
value: 'worst', {
domain: '127.0.0.1', name: '127-cookie',
path: '/', value: 'worst',
sameParty: false, domain: '127.0.0.1',
expires: -1, path: '/',
size: 15, sameParty: false,
httpOnly: false, expires: -1,
secure: false, size: 15,
session: true, httpOnly: false,
sourcePort: 80, secure: false,
sourceScheme: 'NonSecure', session: true,
}, sourcePort: 80,
]); sourceScheme: 'NonSecure',
},
]
);
}); });
it('should set secure same-site cookies from a frame', async () => { it('should set secure same-site cookies from a frame', async () => {
const {httpsServer, defaultBrowserOptions} = getTestState(); const {httpsServer, browser, close} = await launch({
const {browser, close} = await launch({
...defaultBrowserOptions,
ignoreHTTPSErrors: true, ignoreHTTPSErrors: true,
}); });
@ -512,7 +503,7 @@ describe('Cookie specs', () => {
expect(await page.frames()[1]!.evaluate('document.cookie')).toBe( expect(await page.frames()[1]!.evaluate('document.cookie')).toBe(
'127-same-site-cookie=best' '127-same-site-cookie=best'
); );
expectCookieEquals( await expectCookieEquals(
await page.cookies(httpsServer.CROSS_PROCESS_PREFIX), await page.cookies(httpsServer.CROSS_PROCESS_PREFIX),
[ [
{ {
@ -540,7 +531,7 @@ describe('Cookie specs', () => {
describe('Page.deleteCookie', function () { describe('Page.deleteCookie', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setCookie( await page.setCookie(

View File

@ -16,19 +16,12 @@
import expect from 'expect'; import expect from 'expect';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestPageAndContextHooks,
setupTestBrowserHooks,
} from './mocha-utils.js';
describe('Coverage specs', function () { describe('Coverage specs', function () {
describe('JSCoverage', function () { describe('JSCoverage', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startJSCoverage(); await page.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/simple.html', { await page.goto(server.PREFIX + '/jscoverage/simple.html', {
waitUntil: 'networkidle0', waitUntil: 'networkidle0',
@ -42,7 +35,7 @@ describe('Coverage specs', function () {
]); ]);
}); });
it('should report sourceURLs', async () => { it('should report sourceURLs', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startJSCoverage(); await page.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/sourceurl.html'); await page.goto(server.PREFIX + '/jscoverage/sourceurl.html');
@ -51,7 +44,7 @@ describe('Coverage specs', function () {
expect(coverage[0]!.url).toBe('nicename.js'); expect(coverage[0]!.url).toBe('nicename.js');
}); });
it('should ignore eval() scripts by default', async () => { it('should ignore eval() scripts by default', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startJSCoverage(); await page.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/eval.html'); await page.goto(server.PREFIX + '/jscoverage/eval.html');
@ -59,7 +52,7 @@ describe('Coverage specs', function () {
expect(coverage).toHaveLength(1); expect(coverage).toHaveLength(1);
}); });
it("shouldn't ignore eval() scripts if reportAnonymousScripts is true", async () => { 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.coverage.startJSCoverage({reportAnonymousScripts: true});
await page.goto(server.PREFIX + '/jscoverage/eval.html'); await page.goto(server.PREFIX + '/jscoverage/eval.html');
@ -72,7 +65,7 @@ describe('Coverage specs', function () {
expect(coverage).toHaveLength(2); expect(coverage).toHaveLength(2);
}); });
it('should ignore pptr internal scripts if reportAnonymousScripts is true', async () => { 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.coverage.startJSCoverage({reportAnonymousScripts: true});
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -84,7 +77,7 @@ describe('Coverage specs', function () {
expect(coverage).toHaveLength(0); expect(coverage).toHaveLength(0);
}); });
it('should report multiple scripts', async () => { it('should report multiple scripts', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startJSCoverage(); await page.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/multiple.html'); await page.goto(server.PREFIX + '/jscoverage/multiple.html');
@ -97,7 +90,7 @@ describe('Coverage specs', function () {
expect(coverage[1]!.url).toContain('/jscoverage/script2.js'); expect(coverage[1]!.url).toContain('/jscoverage/script2.js');
}); });
it('should report right ranges', async () => { it('should report right ranges', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startJSCoverage(); await page.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/ranges.html'); 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 () => { it('should report right ranges for "per function" scope', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const coverageOptions = { const coverageOptions = {
useBlockCoverage: false, useBlockCoverage: false,
@ -133,7 +126,7 @@ describe('Coverage specs', function () {
); );
}); });
it('should report scripts that have no coverage', async () => { it('should report scripts that have no coverage', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startJSCoverage(); await page.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/unused.html'); await page.goto(server.PREFIX + '/jscoverage/unused.html');
@ -144,7 +137,7 @@ describe('Coverage specs', function () {
expect(entry.ranges).toHaveLength(0); expect(entry.ranges).toHaveLength(0);
}); });
it('should work with conditionals', async () => { it('should work with conditionals', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startJSCoverage(); await page.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/involved.html'); await page.goto(server.PREFIX + '/jscoverage/involved.html');
@ -155,7 +148,7 @@ describe('Coverage specs', function () {
}); });
// @see https://crbug.com/990945 // @see https://crbug.com/990945
it.skip('should not hang when there is a debugger statement', async () => { 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.coverage.startJSCoverage();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -166,7 +159,7 @@ describe('Coverage specs', function () {
}); });
describe('resetOnNavigation', function () { describe('resetOnNavigation', function () {
it('should report scripts across navigations when disabled', async () => { 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.coverage.startJSCoverage({resetOnNavigation: false});
await page.goto(server.PREFIX + '/jscoverage/multiple.html'); 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 () => { 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.coverage.startJSCoverage(); // Enabled by default.
await page.goto(server.PREFIX + '/jscoverage/multiple.html'); await page.goto(server.PREFIX + '/jscoverage/multiple.html');
@ -187,7 +180,7 @@ describe('Coverage specs', function () {
}); });
describe('includeRawScriptCoverage', function () { describe('includeRawScriptCoverage', function () {
it('should not include rawScriptCoverage field when disabled', async () => { it('should not include rawScriptCoverage field when disabled', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startJSCoverage(); await page.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/simple.html', { await page.goto(server.PREFIX + '/jscoverage/simple.html', {
waitUntil: 'networkidle0', waitUntil: 'networkidle0',
@ -197,7 +190,7 @@ describe('Coverage specs', function () {
expect(coverage[0]!.rawScriptCoverage).toBeUndefined(); expect(coverage[0]!.rawScriptCoverage).toBeUndefined();
}); });
it('should include rawScriptCoverage field when enabled', async () => { it('should include rawScriptCoverage field when enabled', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startJSCoverage({ await page.coverage.startJSCoverage({
includeRawScriptCoverage: true, includeRawScriptCoverage: true,
}); });
@ -211,7 +204,7 @@ describe('Coverage specs', function () {
}); });
// @see https://crbug.com/990945 // @see https://crbug.com/990945
it.skip('should not hang when there is a debugger statement', async () => { 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.coverage.startJSCoverage();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -223,11 +216,8 @@ describe('Coverage specs', function () {
}); });
describe('CSSCoverage', function () { describe('CSSCoverage', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startCSSCoverage(); await page.coverage.startCSSCoverage();
await page.goto(server.PREFIX + '/csscoverage/simple.html'); await page.goto(server.PREFIX + '/csscoverage/simple.html');
@ -241,7 +231,7 @@ describe('Coverage specs', function () {
); );
}); });
it('should report sourceURLs', async () => { it('should report sourceURLs', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startCSSCoverage(); await page.coverage.startCSSCoverage();
await page.goto(server.PREFIX + '/csscoverage/sourceurl.html'); await page.goto(server.PREFIX + '/csscoverage/sourceurl.html');
@ -250,7 +240,7 @@ describe('Coverage specs', function () {
expect(coverage[0]!.url).toBe('nicename.css'); expect(coverage[0]!.url).toBe('nicename.css');
}); });
it('should report multiple stylesheets', async () => { it('should report multiple stylesheets', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startCSSCoverage(); await page.coverage.startCSSCoverage();
await page.goto(server.PREFIX + '/csscoverage/multiple.html'); await page.goto(server.PREFIX + '/csscoverage/multiple.html');
@ -263,7 +253,7 @@ describe('Coverage specs', function () {
expect(coverage[1]!.url).toContain('/csscoverage/stylesheet2.css'); expect(coverage[1]!.url).toContain('/csscoverage/stylesheet2.css');
}); });
it('should report stylesheets that have no coverage', async () => { it('should report stylesheets that have no coverage', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startCSSCoverage(); await page.coverage.startCSSCoverage();
await page.goto(server.PREFIX + '/csscoverage/unused.html'); await page.goto(server.PREFIX + '/csscoverage/unused.html');
@ -273,7 +263,7 @@ describe('Coverage specs', function () {
expect(coverage[0]!.ranges).toHaveLength(0); expect(coverage[0]!.ranges).toHaveLength(0);
}); });
it('should work with media queries', async () => { it('should work with media queries', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startCSSCoverage(); await page.coverage.startCSSCoverage();
await page.goto(server.PREFIX + '/csscoverage/media.html'); 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}]); expect(coverage[0]!.ranges).toEqual([{start: 8, end: 40}]);
}); });
it('should work with complicated usecases', async () => { it('should work with complicated usecases', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startCSSCoverage(); await page.coverage.startCSSCoverage();
await page.goto(server.PREFIX + '/csscoverage/involved.html'); await page.goto(server.PREFIX + '/csscoverage/involved.html');
@ -293,7 +283,7 @@ describe('Coverage specs', function () {
).toBeGolden('csscoverage-involved.txt'); ).toBeGolden('csscoverage-involved.txt');
}); });
it('should work with empty stylesheets', async () => { it('should work with empty stylesheets', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startCSSCoverage(); await page.coverage.startCSSCoverage();
await page.goto(server.PREFIX + '/csscoverage/empty.html'); await page.goto(server.PREFIX + '/csscoverage/empty.html');
@ -302,7 +292,7 @@ describe('Coverage specs', function () {
expect(coverage[0]!.text).toEqual(''); expect(coverage[0]!.text).toEqual('');
}); });
it('should ignore injected stylesheets', async () => { it('should ignore injected stylesheets', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.coverage.startCSSCoverage(); await page.coverage.startCSSCoverage();
await page.addStyleTag({content: 'body { margin: 10px;}'}); await page.addStyleTag({content: 'body { margin: 10px;}'});
@ -315,7 +305,7 @@ describe('Coverage specs', function () {
expect(coverage).toHaveLength(0); expect(coverage).toHaveLength(0);
}); });
it('should work with a recently loaded stylesheet', async () => { it('should work with a recently loaded stylesheet', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startCSSCoverage(); await page.coverage.startCSSCoverage();
await page.evaluate(async url => { await page.evaluate(async url => {
@ -334,7 +324,7 @@ describe('Coverage specs', function () {
}); });
describe('resetOnNavigation', function () { describe('resetOnNavigation', function () {
it('should report stylesheets across navigations', async () => { it('should report stylesheets across navigations', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.coverage.startCSSCoverage({resetOnNavigation: false}); await page.coverage.startCSSCoverage({resetOnNavigation: false});
await page.goto(server.PREFIX + '/csscoverage/multiple.html'); await page.goto(server.PREFIX + '/csscoverage/multiple.html');
@ -343,7 +333,7 @@ describe('Coverage specs', function () {
expect(coverage).toHaveLength(2); expect(coverage).toHaveLength(2);
}); });
it('should NOT report scripts across navigations', async () => { 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.coverage.startCSSCoverage(); // Enabled by default.
await page.goto(server.PREFIX + '/csscoverage/multiple.html'); await page.goto(server.PREFIX + '/csscoverage/multiple.html');

View File

@ -15,24 +15,17 @@
*/ */
import expect from 'expect'; import expect from 'expect';
import { import {expectCookieEquals, getTestState} from './mocha-utils.js';
expectCookieEquals,
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
describe('DefaultBrowserContext', function () { describe('DefaultBrowserContext', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('page.cookies() should work', async () => { it('page.cookies() should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => { await page.evaluate(() => {
document.cookie = 'username=John Doe'; document.cookie = 'username=John Doe';
}); });
expectCookieEquals(await page.cookies(), [ await expectCookieEquals(await page.cookies(), [
{ {
name: 'username', name: 'username',
value: 'John Doe', value: 'John Doe',
@ -49,7 +42,7 @@ describe('DefaultBrowserContext', function () {
]); ]);
}); });
it('page.setCookie() should work', async () => { it('page.setCookie() should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setCookie({ await page.setCookie({
@ -61,7 +54,7 @@ describe('DefaultBrowserContext', function () {
return document.cookie; return document.cookie;
}) })
).toBe('username=John Doe'); ).toBe('username=John Doe');
expectCookieEquals(await page.cookies(), [ await expectCookieEquals(await page.cookies(), [
{ {
name: 'username', name: 'username',
value: 'John Doe', value: 'John Doe',
@ -79,7 +72,7 @@ describe('DefaultBrowserContext', function () {
]); ]);
}); });
it('page.deleteCookie() should work', async () => { it('page.deleteCookie() should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setCookie( await page.setCookie(
@ -95,7 +88,7 @@ describe('DefaultBrowserContext', function () {
expect(await page.evaluate('document.cookie')).toBe('cookie1=1; cookie2=2'); expect(await page.evaluate('document.cookie')).toBe('cookie1=1; cookie2=2');
await page.deleteCookie({name: 'cookie2'}); await page.deleteCookie({name: 'cookie2'});
expect(await page.evaluate('document.cookie')).toBe('cookie1=1'); expect(await page.evaluate('document.cookie')).toBe('cookie1=1');
expectCookieEquals(await page.cookies(), [ await expectCookieEquals(await page.cookies(), [
{ {
name: 'cookie1', name: 'cookie1',
value: '1', value: '1',

View File

@ -16,18 +16,11 @@
import expect from 'expect'; import expect from 'expect';
import sinon from 'sinon'; import sinon from 'sinon';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestPageAndContextHooks,
setupTestBrowserHooks,
} from './mocha-utils.js';
describe('Page.Events.Dialog', function () { describe('Page.Events.Dialog', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('should fire', async () => { it('should fire', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const onDialog = sinon.stub().callsFake(dialog => { const onDialog = sinon.stub().callsFake(dialog => {
dialog.accept(); dialog.accept();
@ -46,7 +39,7 @@ describe('Page.Events.Dialog', function () {
}); });
it('should allow accepting prompts', async () => { it('should allow accepting prompts', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const onDialog = sinon.stub().callsFake(dialog => { const onDialog = sinon.stub().callsFake(dialog => {
dialog.accept('answer!'); dialog.accept('answer!');
@ -66,7 +59,7 @@ describe('Page.Events.Dialog', function () {
expect(result).toBe('answer!'); expect(result).toBe('answer!');
}); });
it('should dismiss the prompt', async () => { it('should dismiss the prompt', async () => {
const {page} = getTestState(); const {page} = await getTestState();
page.on('dialog', dialog => { page.on('dialog', dialog => {
dialog.dismiss(); dialog.dismiss();

View File

@ -16,17 +16,11 @@
import expect from 'expect'; import expect from 'expect';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestPageAndContextHooks,
setupTestBrowserHooks,
} from './mocha-utils.js';
describe('Input.drag', function () { describe('Input.drag', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('should throw an exception if not enabled before usage', async () => { 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'); await page.goto(server.PREFIX + '/input/drag-and-drop.html');
const draggable = (await page.$('#drag'))!; const draggable = (await page.$('#drag'))!;
@ -40,7 +34,7 @@ describe('Input.drag', function () {
} }
}); });
it('should emit a dragIntercepted event when dragged', async () => { 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'); await page.goto(server.PREFIX + '/input/drag-and-drop.html');
expect(page.isDragInterceptionEnabled()).toBe(false); expect(page.isDragInterceptionEnabled()).toBe(false);
@ -57,7 +51,7 @@ describe('Input.drag', function () {
).toBe(true); ).toBe(true);
}); });
it('should emit a dragEnter', async () => { 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'); await page.goto(server.PREFIX + '/input/drag-and-drop.html');
expect(page.isDragInterceptionEnabled()).toBe(false); expect(page.isDragInterceptionEnabled()).toBe(false);
@ -80,7 +74,7 @@ describe('Input.drag', function () {
).toBe(true); ).toBe(true);
}); });
it('should emit a dragOver event', async () => { 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'); await page.goto(server.PREFIX + '/input/drag-and-drop.html');
expect(page.isDragInterceptionEnabled()).toBe(false); expect(page.isDragInterceptionEnabled()).toBe(false);
@ -109,7 +103,7 @@ describe('Input.drag', function () {
).toBe(true); ).toBe(true);
}); });
it('can be dropped', async () => { it('can be dropped', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/drag-and-drop.html'); await page.goto(server.PREFIX + '/input/drag-and-drop.html');
expect(page.isDragInterceptionEnabled()).toBe(false); expect(page.isDragInterceptionEnabled()).toBe(false);
@ -144,7 +138,7 @@ describe('Input.drag', function () {
).toBe(true); ).toBe(true);
}); });
it('can be dragged and dropped with a single function', async () => { 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'); await page.goto(server.PREFIX + '/input/drag-and-drop.html');
expect(page.isDragInterceptionEnabled()).toBe(false); expect(page.isDragInterceptionEnabled()).toBe(false);
@ -176,7 +170,7 @@ describe('Input.drag', function () {
).toBe(true); ).toBe(true);
}); });
it('can be disabled', async () => { it('can be disabled', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/drag-and-drop.html'); await page.goto(server.PREFIX + '/input/drag-and-drop.html');
expect(page.isDragInterceptionEnabled()).toBe(false); expect(page.isDragInterceptionEnabled()).toBe(false);

View File

@ -21,19 +21,14 @@ import sinon from 'sinon';
import { import {
getTestState, getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
shortWaitForArrayToHaveAtLeastNElements, shortWaitForArrayToHaveAtLeastNElements,
} from './mocha-utils.js'; } from './mocha-utils.js';
import {attachFrame} from './utils.js'; import {attachFrame} from './utils.js';
describe('ElementHandle specs', function () { describe('ElementHandle specs', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('ElementHandle.boundingBox', function () { describe('ElementHandle.boundingBox', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html'); 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}); expect(box).toEqual({x: 100, y: 50, width: 50, height: 50});
}); });
it('should handle nested frames', async () => { 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.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/frames/nested-frames.html'); 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 () => { it('should return null for invisible elements', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div style="display:none">hi</div>'); await page.setContent('<div style="display:none">hi</div>');
const element = (await page.$('div'))!; const element = (await page.$('div'))!;
expect(await element.boundingBox()).toBe(null); expect(await element.boundingBox()).toBe(null);
}); });
it('should force a layout', async () => { it('should force a layout', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.setContent( await page.setContent(
@ -77,7 +72,7 @@ describe('ElementHandle specs', function () {
expect(box).toEqual({x: 8, y: 8, width: 100, height: 200}); expect(box).toEqual({x: 8, y: 8, width: 100, height: 200});
}); });
it('should work with SVG nodes', async () => { it('should work with SVG nodes', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(` await page.setContent(`
<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500"> <svg xmlns="http://www.w3.org/2000/svg" width="500" height="500">
@ -98,7 +93,7 @@ describe('ElementHandle specs', function () {
describe('ElementHandle.boxModel', function () { describe('ElementHandle.boxModel', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/resetcss.html'); await page.goto(server.PREFIX + '/resetcss.html');
@ -153,7 +148,7 @@ describe('ElementHandle specs', function () {
}); });
it('should return null for invisible elements', async () => { it('should return null for invisible elements', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div style="display:none">hi</div>'); await page.setContent('<div style="display:none">hi</div>');
const element = (await page.$('div'))!; const element = (await page.$('div'))!;
@ -163,7 +158,7 @@ describe('ElementHandle specs', function () {
describe('ElementHandle.contentFrame', function () { describe('ElementHandle.contentFrame', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await attachFrame(page, 'frame1', 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 () { describe('ElementHandle.isVisible and ElementHandle.isHidden', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div style="display: none">text</div>'); await page.setContent('<div style="display: none">text</div>');
const element = (await page.waitForSelector('div'))!; const element = (await page.waitForSelector('div'))!;
await expect(element.isVisible()).resolves.toBeFalsy(); await expect(element.isVisible()).resolves.toBeFalsy();
@ -190,7 +185,7 @@ describe('ElementHandle specs', function () {
describe('ElementHandle.click', function () { describe('ElementHandle.click', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/button.html'); await page.goto(server.PREFIX + '/input/button.html');
const button = (await page.$('button'))!; const button = (await page.$('button'))!;
@ -202,7 +197,7 @@ describe('ElementHandle specs', function () {
).toBe('Clicked'); ).toBe('Clicked');
}); });
it('should return Point data', async () => { it('should return Point data', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const clicks: Array<[x: number, y: number]> = []; const clicks: Array<[x: number, y: number]> = [];
@ -236,7 +231,7 @@ describe('ElementHandle specs', function () {
]); ]);
}); });
it('should work for Shadow DOM v1', async () => { it('should work for Shadow DOM v1', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/shadow.html'); await page.goto(server.PREFIX + '/shadow.html');
const buttonHandle = await page.evaluateHandle(() => { const buttonHandle = await page.evaluateHandle(() => {
@ -252,7 +247,7 @@ describe('ElementHandle specs', function () {
).toBe(true); ).toBe(true);
}); });
it('should not work for TextNodes', async () => { it('should not work for TextNodes', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/button.html'); await page.goto(server.PREFIX + '/input/button.html');
const buttonTextNode = await page.evaluateHandle(() => { const buttonTextNode = await page.evaluateHandle(() => {
@ -268,7 +263,7 @@ describe('ElementHandle specs', function () {
]); ]);
}); });
it('should throw for detached nodes', async () => { it('should throw for detached nodes', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/button.html'); await page.goto(server.PREFIX + '/input/button.html');
const button = (await page.$('button'))!; const button = (await page.$('button'))!;
@ -285,7 +280,7 @@ describe('ElementHandle specs', function () {
]); ]);
}); });
it('should throw for hidden nodes', async () => { it('should throw for hidden nodes', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/button.html'); await page.goto(server.PREFIX + '/input/button.html');
const button = (await page.$('button'))!; const button = (await page.$('button'))!;
@ -301,7 +296,7 @@ describe('ElementHandle specs', function () {
]); ]);
}); });
it('should throw for recursively hidden nodes', async () => { 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'); await page.goto(server.PREFIX + '/input/button.html');
const button = (await page.$('button'))!; const button = (await page.$('button'))!;
@ -317,7 +312,7 @@ describe('ElementHandle specs', function () {
]); ]);
}); });
it('should throw for <br> elements', async () => { it('should throw for <br> elements', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('hello<br>goodbye'); await page.setContent('hello<br>goodbye');
const br = (await page.$('br'))!; const br = (await page.$('br'))!;
@ -333,7 +328,7 @@ describe('ElementHandle specs', function () {
describe('ElementHandle.clickablePoint', function () { describe('ElementHandle.clickablePoint', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.evaluate(() => { await page.evaluate(() => {
document.body.style.padding = '0'; document.body.style.padding = '0';
@ -364,7 +359,7 @@ describe('ElementHandle specs', function () {
}); });
it('should work for iframes', async () => { it('should work for iframes', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.evaluate(() => { await page.evaluate(() => {
document.body.style.padding = '10px'; document.body.style.padding = '10px';
document.body.style.margin = '10px'; document.body.style.margin = '10px';
@ -397,7 +392,7 @@ describe('ElementHandle specs', function () {
describe('Element.waitForSelector', () => { describe('Element.waitForSelector', () => {
it('should wait correctly with waitForSelector on an element', async () => { it('should wait correctly with waitForSelector on an element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const waitFor = page.waitForSelector('.foo').catch(err => { const waitFor = page.waitForSelector('.foo').catch(err => {
return err; return err;
}) as Promise<ElementHandle<HTMLDivElement>>; }) as Promise<ElementHandle<HTMLDivElement>>;
@ -432,7 +427,7 @@ describe('ElementHandle specs', function () {
describe('Element.waitForXPath', () => { describe('Element.waitForXPath', () => {
it('should wait correctly with waitForXPath on an element', async () => { 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. // Set the page content after the waitFor has been started.
await page.setContent( await page.setContent(
`<div id=el1> `<div id=el1>
@ -465,7 +460,7 @@ describe('ElementHandle specs', function () {
describe('ElementHandle.hover', function () { describe('ElementHandle.hover', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/scrollable.html'); await page.goto(server.PREFIX + '/input/scrollable.html');
const button = (await page.$('#button-6'))!; const button = (await page.$('#button-6'))!;
@ -480,7 +475,7 @@ describe('ElementHandle specs', function () {
describe('ElementHandle.isIntersectingViewport', function () { describe('ElementHandle.isIntersectingViewport', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
async function getVisibilityForButton(selector: string) { async function getVisibilityForButton(selector: string) {
const button = (await page.$(selector))!; const button = (await page.$(selector))!;
@ -502,7 +497,7 @@ describe('ElementHandle specs', function () {
} }
}); });
it('should work with threshold', async () => { it('should work with threshold', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/offscreenbuttons.html'); await page.goto(server.PREFIX + '/offscreenbuttons.html');
// a button almost cannot be seen // a button almost cannot be seen
@ -515,7 +510,7 @@ describe('ElementHandle specs', function () {
).toBe(false); ).toBe(false);
}); });
it('should work with threshold of 1', async () => { it('should work with threshold of 1', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/offscreenbuttons.html'); await page.goto(server.PREFIX + '/offscreenbuttons.html');
// a button almost cannot be seen // a button almost cannot be seen
@ -528,7 +523,7 @@ describe('ElementHandle specs', function () {
).toBe(true); ).toBe(true);
}); });
it('should work with svg elements', async () => { it('should work with svg elements', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/inline-svg.html'); await page.goto(server.PREFIX + '/inline-svg.html');
const [visibleCircle, visibleSvg] = await Promise.all([ const [visibleCircle, visibleSvg] = await Promise.all([
@ -602,7 +597,7 @@ describe('ElementHandle specs', function () {
Puppeteer.clearCustomQueryHandlers(); Puppeteer.clearCustomQueryHandlers();
}); });
it('should register and unregister', async () => { 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>'); await page.setContent('<div id="not-foo"></div><div id="foo"></div>');
// Register. // Register.
@ -653,7 +648,7 @@ describe('ElementHandle specs', function () {
} }
}); });
it('should work for multiple elements', async () => { it('should work for multiple elements', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div id="not-foo"></div><div class="foo">Foo1</div><div class="foo baz">Foo2</div>' '<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']); expect(classNames).toStrictEqual(['foo', 'foo baz']);
}); });
it('should eval correctly', async () => { it('should eval correctly', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div id="not-foo"></div><div class="foo">Foo1</div><div class="foo baz">Foo2</div>' '<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); expect(elements).toBe(2);
}); });
it('should wait correctly with waitForSelector', async () => { it('should wait correctly with waitForSelector', async () => {
const {page} = getTestState(); const {page} = await getTestState();
Puppeteer.registerCustomQueryHandler('getByClass', { Puppeteer.registerCustomQueryHandler('getByClass', {
queryOne: (element, selector) => { queryOne: (element, selector) => {
return (element as Element).querySelector(`.${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 () => { it('should wait correctly with waitForSelector on an element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
Puppeteer.registerCustomQueryHandler('getByClass', { Puppeteer.registerCustomQueryHandler('getByClass', {
queryOne: (element, selector) => { queryOne: (element, selector) => {
return (element as Element).querySelector(`.${selector}`); return (element as Element).querySelector(`.${selector}`);
@ -761,7 +756,7 @@ describe('ElementHandle specs', function () {
it('should wait correctly with waitFor', async () => { it('should wait correctly with waitFor', async () => {
/* page.waitFor is deprecated so we silence the warning to avoid test noise */ /* page.waitFor is deprecated so we silence the warning to avoid test noise */
sinon.stub(console, 'warn').callsFake(() => {}); sinon.stub(console, 'warn').callsFake(() => {});
const {page} = getTestState(); const {page} = await getTestState();
Puppeteer.registerCustomQueryHandler('getByClass', { Puppeteer.registerCustomQueryHandler('getByClass', {
queryOne: (element, selector) => { queryOne: (element, selector) => {
return (element as Element).querySelector(`.${selector}`); return (element as Element).querySelector(`.${selector}`);
@ -784,7 +779,7 @@ describe('ElementHandle specs', function () {
expect(element).toBeDefined(); expect(element).toBeDefined();
}); });
it('should work when both queryOne and queryAll are registered', async () => { it('should work when both queryOne and queryAll are registered', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div id="not-foo"></div><div class="foo"><div id="nested-foo" class="foo"/></div><div class="foo baz">Foo2</div>' '<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); expect(elements).toHaveLength(3);
}); });
it('should eval when both queryOne and queryAll are registered', async () => { it('should eval when both queryOne and queryAll are registered', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div id="not-foo"></div><div class="foo">text</div><div class="foo baz">content</div>' '<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 () => { 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>'); await page.setContent('<div id="not-foo"></div><div id="foo"></div>');
Puppeteer.registerCustomQueryHandler('getById', { Puppeteer.registerCustomQueryHandler('getById', {
@ -856,7 +851,7 @@ describe('ElementHandle specs', function () {
describe('Element.toElement', () => { describe('Element.toElement', () => {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div class="foo">Foo1</div>'); await page.setContent('<div class="foo">Foo1</div>');
const element = await page.$('.foo'); const element = await page.$('.foo');
const div = await element?.toElement('div'); const div = await element?.toElement('div');

View File

@ -17,29 +17,22 @@
import expect from 'expect'; import expect from 'expect';
import {KnownDevices, PredefinedNetworkConditions} from 'puppeteer'; import {KnownDevices, PredefinedNetworkConditions} from 'puppeteer';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
const iPhone = KnownDevices['iPhone 6']; const iPhone = KnownDevices['iPhone 6'];
const iPhoneLandscape = KnownDevices['iPhone 6 landscape']; const iPhoneLandscape = KnownDevices['iPhone 6 landscape'];
describe('Emulation', () => { describe('Emulation', () => {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Page.viewport', function () { describe('Page.viewport', function () {
it('should get the proper viewport size', async () => { it('should get the proper viewport size', async () => {
const {page} = getTestState(); const {page} = await getTestState();
expect(page.viewport()).toEqual({width: 800, height: 600}); expect(page.viewport()).toEqual({width: 800, height: 600});
await page.setViewport({width: 123, height: 456}); await page.setViewport({width: 123, height: 456});
expect(page.viewport()).toEqual({width: 123, height: 456}); expect(page.viewport()).toEqual({width: 123, height: 456});
}); });
it('should support mobile emulation', async () => { it('should support mobile emulation', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/mobile.html'); await page.goto(server.PREFIX + '/mobile.html');
expect( expect(
@ -61,7 +54,7 @@ describe('Emulation', () => {
).toBe(400); ).toBe(400);
}); });
it('should support touch emulation', async () => { it('should support touch emulation', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/mobile.html'); await page.goto(server.PREFIX + '/mobile.html');
expect( expect(
@ -99,7 +92,7 @@ describe('Emulation', () => {
} }
}); });
it('should be detectable by Modernizr', async () => { it('should be detectable by Modernizr', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/detect-touch.html'); await page.goto(server.PREFIX + '/detect-touch.html');
expect( expect(
@ -116,7 +109,7 @@ describe('Emulation', () => {
).toBe('YES'); ).toBe('YES');
}); });
it('should detect touch when applying viewport with touches', async () => { 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.setViewport({width: 800, height: 600, hasTouch: true});
await page.addScriptTag({url: server.PREFIX + '/modernizr.js'}); await page.addScriptTag({url: server.PREFIX + '/modernizr.js'});
@ -127,7 +120,7 @@ describe('Emulation', () => {
).toBe(true); ).toBe(true);
}); });
it('should support landscape emulation', async () => { it('should support landscape emulation', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/mobile.html'); await page.goto(server.PREFIX + '/mobile.html');
expect( expect(
@ -152,7 +145,7 @@ describe('Emulation', () => {
describe('Page.emulate', function () { describe('Page.emulate', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/mobile.html'); await page.goto(server.PREFIX + '/mobile.html');
await page.emulate(iPhone); await page.emulate(iPhone);
@ -168,7 +161,7 @@ describe('Emulation', () => {
).toContain('iPhone'); ).toContain('iPhone');
}); });
it('should support clicking', async () => { it('should support clicking', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.emulate(iPhone); await page.emulate(iPhone);
await page.goto(server.PREFIX + '/input/button.html'); await page.goto(server.PREFIX + '/input/button.html');
@ -187,7 +180,7 @@ describe('Emulation', () => {
describe('Page.emulateMediaType', function () { describe('Page.emulateMediaType', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
expect( expect(
await page.evaluate(() => { await page.evaluate(() => {
@ -223,7 +216,7 @@ describe('Emulation', () => {
).toBe(false); ).toBe(false);
}); });
it('should throw in case of bad argument', async () => { it('should throw in case of bad argument', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page.emulateMediaType('bad').catch(error_ => { await page.emulateMediaType('bad').catch(error_ => {
@ -235,7 +228,7 @@ describe('Emulation', () => {
describe('Page.emulateMediaFeatures', function () { describe('Page.emulateMediaFeatures', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.emulateMediaFeatures([ await page.emulateMediaFeatures([
{name: 'prefers-reduced-motion', value: 'reduce'}, {name: 'prefers-reduced-motion', value: 'reduce'},
@ -352,7 +345,7 @@ describe('Emulation', () => {
).toBe(true); ).toBe(true);
}); });
it('should throw in case of bad argument', async () => { it('should throw in case of bad argument', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page await page
@ -366,7 +359,7 @@ describe('Emulation', () => {
describe('Page.emulateTimezone', function () { describe('Page.emulateTimezone', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.evaluate(() => { await page.evaluate(() => {
(globalThis as any).date = new Date(1479579154987); (globalThis as any).date = new Date(1479579154987);
@ -405,7 +398,7 @@ describe('Emulation', () => {
}); });
it('should throw for invalid timezone IDs', async () => { it('should throw for invalid timezone IDs', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page.emulateTimezone('Foo/Bar').catch(error_ => { await page.emulateTimezone('Foo/Bar').catch(error_ => {
@ -421,7 +414,7 @@ describe('Emulation', () => {
describe('Page.emulateVisionDeficiency', function () { describe('Page.emulateVisionDeficiency', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html'); await page.goto(server.PREFIX + '/grid.html');
@ -470,7 +463,7 @@ describe('Emulation', () => {
}); });
it('should throw for invalid vision deficiencies', async () => { it('should throw for invalid vision deficiencies', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page await page
@ -485,7 +478,7 @@ describe('Emulation', () => {
describe('Page.emulateNetworkConditions', function () { describe('Page.emulateNetworkConditions', function () {
it('should change navigator.connection.effectiveType', async () => { it('should change navigator.connection.effectiveType', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const slow3G = PredefinedNetworkConditions['Slow 3G']!; const slow3G = PredefinedNetworkConditions['Slow 3G']!;
const fast3G = PredefinedNetworkConditions['Fast 3G']!; const fast3G = PredefinedNetworkConditions['Fast 3G']!;
@ -507,7 +500,7 @@ describe('Emulation', () => {
describe('Page.emulateCPUThrottling', function () { describe('Page.emulateCPUThrottling', function () {
it('should change the CPU throttling rate successfully', async () => { it('should change the CPU throttling rate successfully', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.emulateCPUThrottling(100); await page.emulateCPUThrottling(100);
await page.emulateCPUThrottling(null); await page.emulateCPUThrottling(null);

View File

@ -16,20 +16,13 @@
import expect from 'expect'; import expect from 'expect';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {attachFrame} from './utils.js'; import {attachFrame} from './utils.js';
describe('Evaluation specs', function () { describe('Evaluation specs', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Page.evaluate', function () { describe('Page.evaluate', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate(() => { const result = await page.evaluate(() => {
return 7 * 3; return 7 * 3;
@ -37,7 +30,7 @@ describe('Evaluation specs', function () {
expect(result).toBe(21); expect(result).toBe(21);
}); });
it('should transfer BigInt', async () => { it('should transfer BigInt', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate((a: bigint) => { const result = await page.evaluate((a: bigint) => {
return a; return a;
@ -45,7 +38,7 @@ describe('Evaluation specs', function () {
expect(result).toBe(BigInt(42)); expect(result).toBe(BigInt(42));
}); });
it('should transfer NaN', async () => { it('should transfer NaN', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate(a => { const result = await page.evaluate(a => {
return a; return a;
@ -53,7 +46,7 @@ describe('Evaluation specs', function () {
expect(Object.is(result, NaN)).toBe(true); expect(Object.is(result, NaN)).toBe(true);
}); });
it('should transfer -0', async () => { it('should transfer -0', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate(a => { const result = await page.evaluate(a => {
return a; return a;
@ -61,7 +54,7 @@ describe('Evaluation specs', function () {
expect(Object.is(result, -0)).toBe(true); expect(Object.is(result, -0)).toBe(true);
}); });
it('should transfer Infinity', async () => { it('should transfer Infinity', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate(a => { const result = await page.evaluate(a => {
return a; return a;
@ -69,7 +62,7 @@ describe('Evaluation specs', function () {
expect(Object.is(result, Infinity)).toBe(true); expect(Object.is(result, Infinity)).toBe(true);
}); });
it('should transfer -Infinity', async () => { it('should transfer -Infinity', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate(a => { const result = await page.evaluate(a => {
return a; return a;
@ -77,7 +70,7 @@ describe('Evaluation specs', function () {
expect(Object.is(result, -Infinity)).toBe(true); expect(Object.is(result, -Infinity)).toBe(true);
}); });
it('should transfer arrays', async () => { it('should transfer arrays', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate( const result = await page.evaluate(
a => { a => {
@ -88,7 +81,7 @@ describe('Evaluation specs', function () {
expect(result).toEqual([1, 2, 3]); expect(result).toEqual([1, 2, 3]);
}); });
it('should transfer arrays as arrays, not objects', async () => { it('should transfer arrays as arrays, not objects', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate( const result = await page.evaluate(
a => { a => {
@ -99,7 +92,7 @@ describe('Evaluation specs', function () {
expect(result).toBe(true); expect(result).toBe(true);
}); });
it('should modify global environment', async () => { it('should modify global environment', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.evaluate(() => { await page.evaluate(() => {
return ((globalThis as any).globalVar = 123); return ((globalThis as any).globalVar = 123);
@ -107,13 +100,13 @@ describe('Evaluation specs', function () {
expect(await page.evaluate('globalVar')).toBe(123); expect(await page.evaluate('globalVar')).toBe(123);
}); });
it('should evaluate in the page context', async () => { 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'); await page.goto(server.PREFIX + '/global-var.html');
expect(await page.evaluate('globalVar')).toBe(123); expect(await page.evaluate('globalVar')).toBe(123);
}); });
it('should return undefined for objects with symbols', async () => { it('should return undefined for objects with symbols', async () => {
const {page} = getTestState(); const {page} = await getTestState();
expect( expect(
await page.evaluate(() => { await page.evaluate(() => {
@ -122,7 +115,7 @@ describe('Evaluation specs', function () {
).toBe(undefined); ).toBe(undefined);
}); });
it('should work with function shorthands', async () => { it('should work with function shorthands', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const a = { const a = {
sum(a: number, b: number) { sum(a: number, b: number) {
@ -137,7 +130,7 @@ describe('Evaluation specs', function () {
expect(await page.evaluate(a.mult, 2, 4)).toBe(8); expect(await page.evaluate(a.mult, 2, 4)).toBe(8);
}); });
it('should work with unicode chars', async () => { it('should work with unicode chars', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate( const result = await page.evaluate(
a => { a => {
@ -150,7 +143,7 @@ describe('Evaluation specs', function () {
expect(result).toBe(42); expect(result).toBe(42);
}); });
it('should throw when evaluation triggers reload', async () => { it('should throw when evaluation triggers reload', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page await page
@ -164,7 +157,7 @@ describe('Evaluation specs', function () {
expect(error.message).toContain('Protocol error'); expect(error.message).toContain('Protocol error');
}); });
it('should await promise', async () => { it('should await promise', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate(() => { const result = await page.evaluate(() => {
return Promise.resolve(8 * 7); return Promise.resolve(8 * 7);
@ -172,7 +165,7 @@ describe('Evaluation specs', function () {
expect(result).toBe(56); expect(result).toBe(56);
}); });
it('should work right after framenavigated', async () => { it('should work right after framenavigated', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
let frameEvaluation = null; let frameEvaluation = null;
page.on('framenavigated', async frame => { page.on('framenavigated', async frame => {
@ -184,7 +177,7 @@ describe('Evaluation specs', function () {
expect(await frameEvaluation).toBe(42); expect(await frameEvaluation).toBe(42);
}); });
it('should work from-inside an exposed function', async () => { it('should work from-inside an exposed function', async () => {
const {page} = getTestState(); const {page} = await getTestState();
// Setup inpage callback, which calls Page.evaluate // Setup inpage callback, which calls Page.evaluate
await page.exposeFunction( await page.exposeFunction(
@ -205,7 +198,7 @@ describe('Evaluation specs', function () {
expect(result).toBe(27); expect(result).toBe(27);
}); });
it('should reject promise with exception', async () => { it('should reject promise with exception', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page await page
@ -220,7 +213,7 @@ describe('Evaluation specs', function () {
expect(error.message).toContain('notExistingObject'); expect(error.message).toContain('notExistingObject');
}); });
it('should support thrown strings as error messages', async () => { it('should support thrown strings as error messages', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page await page
@ -233,7 +226,7 @@ describe('Evaluation specs', function () {
expect(error).toEqual('qwerty'); expect(error).toEqual('qwerty');
}); });
it('should support thrown numbers as error messages', async () => { it('should support thrown numbers as error messages', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page await page
@ -246,7 +239,7 @@ describe('Evaluation specs', function () {
expect(error).toEqual(100500); expect(error).toEqual(100500);
}); });
it('should return complex objects', async () => { it('should return complex objects', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const object = {foo: 'bar!'}; const object = {foo: 'bar!'};
const result = await page.evaluate(a => { const result = await page.evaluate(a => {
@ -256,7 +249,7 @@ describe('Evaluation specs', function () {
expect(result).toEqual(object); expect(result).toEqual(object);
}); });
it('should return BigInt', async () => { it('should return BigInt', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate(() => { const result = await page.evaluate(() => {
return BigInt(42); return BigInt(42);
@ -264,7 +257,7 @@ describe('Evaluation specs', function () {
expect(result).toBe(BigInt(42)); expect(result).toBe(BigInt(42));
}); });
it('should return NaN', async () => { it('should return NaN', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate(() => { const result = await page.evaluate(() => {
return NaN; return NaN;
@ -272,7 +265,7 @@ describe('Evaluation specs', function () {
expect(Object.is(result, NaN)).toBe(true); expect(Object.is(result, NaN)).toBe(true);
}); });
it('should return -0', async () => { it('should return -0', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate(() => { const result = await page.evaluate(() => {
return -0; return -0;
@ -280,7 +273,7 @@ describe('Evaluation specs', function () {
expect(Object.is(result, -0)).toBe(true); expect(Object.is(result, -0)).toBe(true);
}); });
it('should return Infinity', async () => { it('should return Infinity', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate(() => { const result = await page.evaluate(() => {
return Infinity; return Infinity;
@ -288,7 +281,7 @@ describe('Evaluation specs', function () {
expect(Object.is(result, Infinity)).toBe(true); expect(Object.is(result, Infinity)).toBe(true);
}); });
it('should return -Infinity', async () => { it('should return -Infinity', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate(() => { const result = await page.evaluate(() => {
return -Infinity; return -Infinity;
@ -296,7 +289,7 @@ describe('Evaluation specs', function () {
expect(Object.is(result, -Infinity)).toBe(true); expect(Object.is(result, -Infinity)).toBe(true);
}); });
it('should accept "null" as one of multiple parameters', async () => { it('should accept "null" as one of multiple parameters', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate( const result = await page.evaluate(
(a, b) => { (a, b) => {
@ -308,7 +301,7 @@ describe('Evaluation specs', function () {
expect(result).toBe(true); expect(result).toBe(true);
}); });
it('should properly serialize null fields', async () => { it('should properly serialize null fields', async () => {
const {page} = getTestState(); const {page} = await getTestState();
expect( expect(
await page.evaluate(() => { await page.evaluate(() => {
@ -317,7 +310,7 @@ describe('Evaluation specs', function () {
).toEqual({}); ).toEqual({});
}); });
it('should return undefined for non-serializable objects', async () => { it('should return undefined for non-serializable objects', async () => {
const {page} = getTestState(); const {page} = await getTestState();
expect( expect(
await page.evaluate(() => { await page.evaluate(() => {
@ -326,7 +319,7 @@ describe('Evaluation specs', function () {
).toBe(undefined); ).toBe(undefined);
}); });
it('should return promise as empty object', async () => { it('should return promise as empty object', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate(() => { const result = await page.evaluate(() => {
return { return {
@ -340,7 +333,7 @@ describe('Evaluation specs', function () {
}); });
}); });
it('should fail for circular object', async () => { it('should fail for circular object', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate(() => { const result = await page.evaluate(() => {
const a: {[x: string]: any} = {}; const a: {[x: string]: any} = {};
@ -351,7 +344,7 @@ describe('Evaluation specs', function () {
expect(result).toBe(undefined); expect(result).toBe(undefined);
}); });
it('should be able to throw a tricky error', async () => { it('should be able to throw a tricky error', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const windowHandle = await page.evaluateHandle(() => { const windowHandle = await page.evaluateHandle(() => {
return window; return window;
@ -369,25 +362,25 @@ describe('Evaluation specs', function () {
expect(error.message).toContain(errorText); expect(error.message).toContain(errorText);
}); });
it('should accept a string', async () => { it('should accept a string', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate('1 + 2'); const result = await page.evaluate('1 + 2');
expect(result).toBe(3); expect(result).toBe(3);
}); });
it('should accept a string with semi colons', async () => { it('should accept a string with semi colons', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate('1 + 5;'); const result = await page.evaluate('1 + 5;');
expect(result).toBe(6); expect(result).toBe(6);
}); });
it('should accept a string with comments', async () => { 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!'); const result = await page.evaluate('2 + 5;\n// do some math!');
expect(result).toBe(7); expect(result).toBe(7);
}); });
it('should accept element handle as an argument', async () => { it('should accept element handle as an argument', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<section>42</section>'); await page.setContent('<section>42</section>');
const element = (await page.$('section'))!; const element = (await page.$('section'))!;
@ -397,7 +390,7 @@ describe('Evaluation specs', function () {
expect(text).toBe('42'); expect(text).toBe('42');
}); });
it('should throw if underlying element was disposed', async () => { it('should throw if underlying element was disposed', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<section>39</section>'); await page.setContent('<section>39</section>');
const element = (await page.$('section'))!; const element = (await page.$('section'))!;
@ -414,7 +407,7 @@ describe('Evaluation specs', function () {
expect(error.message).toContain('JSHandle is disposed'); expect(error.message).toContain('JSHandle is disposed');
}); });
it('should throw if elementHandles are from other frames', async () => { 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); await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const bodyHandle = await page.frames()[1]!.$('body'); const bodyHandle = await page.frames()[1]!.$('body');
@ -432,7 +425,7 @@ describe('Evaluation specs', function () {
); );
}); });
it('should simulate a user gesture', async () => { it('should simulate a user gesture', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const result = await page.evaluate(() => { const result = await page.evaluate(() => {
document.body.appendChild(document.createTextNode('test')); document.body.appendChild(document.createTextNode('test'));
@ -442,7 +435,7 @@ describe('Evaluation specs', function () {
expect(result).toBe(true); expect(result).toBe(true);
}); });
it('should throw a nice error after a navigation', async () => { it('should throw a nice error after a navigation', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const executionContext = await page.mainFrame().executionContext(); const executionContext = await page.mainFrame().executionContext();
@ -462,7 +455,7 @@ describe('Evaluation specs', function () {
expect((error as Error).message).toContain('navigation'); expect((error as Error).message).toContain('navigation');
}); });
it('should not throw an error when evaluation does a navigation', async () => { 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'); await page.goto(server.PREFIX + '/one-style.html');
const result = await page.evaluate(() => { 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 () { it('should transfer 100Mb of data from page to node.js', async function () {
this.timeout(25_000); this.timeout(25_000);
const {page} = getTestState(); const {page} = await getTestState();
const a = await page.evaluate(() => { const a = await page.evaluate(() => {
return Array(100 * 1024 * 1024 + 1).join('a'); return Array(100 * 1024 * 1024 + 1).join('a');
@ -481,7 +474,7 @@ describe('Evaluation specs', function () {
expect(a.length).toBe(100 * 1024 * 1024); expect(a.length).toBe(100 * 1024 * 1024);
}); });
it('should throw error with detailed information on exception inside promise', async () => { it('should throw error with detailed information on exception inside promise', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page await page
@ -499,7 +492,7 @@ describe('Evaluation specs', function () {
describe('Page.evaluateOnNewDocument', function () { describe('Page.evaluateOnNewDocument', function () {
it('should evaluate before anything else on the page', async () => { it('should evaluate before anything else on the page', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.evaluateOnNewDocument(function () { await page.evaluateOnNewDocument(function () {
(globalThis as any).injected = 123; (globalThis as any).injected = 123;
@ -512,7 +505,7 @@ describe('Evaluation specs', function () {
).toBe(123); ).toBe(123);
}); });
it('should work with CSP', async () => { it('should work with CSP', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.setCSP('/empty.html', 'script-src ' + server.PREFIX); server.setCSP('/empty.html', 'script-src ' + server.PREFIX);
await page.evaluateOnNewDocument(function () { await page.evaluateOnNewDocument(function () {
@ -539,7 +532,7 @@ describe('Evaluation specs', function () {
describe('Page.removeScriptToEvaluateOnNewDocument', function () { describe('Page.removeScriptToEvaluateOnNewDocument', function () {
it('should remove new document script', async () => { it('should remove new document script', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const {identifier} = await page.evaluateOnNewDocument(function () { const {identifier} = await page.evaluateOnNewDocument(function () {
(globalThis as any).injected = 123; (globalThis as any).injected = 123;
@ -563,7 +556,7 @@ describe('Evaluation specs', function () {
describe('Frame.evaluate', function () { describe('Frame.evaluate', function () {
it('should have different execution contexts', async () => { it('should have different execution contexts', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE); await attachFrame(page, 'frame1', server.EMPTY_PAGE);
@ -586,7 +579,7 @@ describe('Evaluation specs', function () {
).toBe('bar'); ).toBe('bar');
}); });
it('should have correct execution contexts', async () => { 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'); await page.goto(server.PREFIX + '/frames/one-frame.html');
expect(page.frames()).toHaveLength(2); expect(page.frames()).toHaveLength(2);
@ -602,7 +595,7 @@ describe('Evaluation specs', function () {
).toBe(`Hi, I'm frame`); ).toBe(`Hi, I'm frame`);
}); });
it('should execute after cross-site navigation', async () => { it('should execute after cross-site navigation', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const mainFrame = page.mainFrame(); const mainFrame = page.mainFrame();

View File

@ -25,7 +25,8 @@ import {waitEvent} from './utils.js';
describe('Fixtures', function () { describe('Fixtures', function () {
it('dumpio option should work with pipe option', async () => { it('dumpio option should work with pipe option', async () => {
const {defaultBrowserOptions, puppeteerPath, headless} = getTestState(); const {defaultBrowserOptions, puppeteerPath, headless} =
await getTestState();
if (headless === 'new') { if (headless === 'new') {
// This test only works in the old headless mode. // This test only works in the old headless mode.
return; return;
@ -52,7 +53,7 @@ describe('Fixtures', function () {
expect(dumpioData).toContain('message from dumpio'); expect(dumpioData).toContain('message from dumpio');
}); });
it('should dump browser process stderr', async () => { it('should dump browser process stderr', async () => {
const {defaultBrowserOptions, puppeteerPath} = getTestState(); const {defaultBrowserOptions, puppeteerPath} = await getTestState();
let dumpioData = ''; let dumpioData = '';
const {spawn} = await import('child_process'); const {spawn} = await import('child_process');
@ -71,7 +72,8 @@ describe('Fixtures', function () {
expect(dumpioData).toContain('DevTools listening on ws://'); expect(dumpioData).toContain('DevTools listening on ws://');
}); });
it('should close the browser when the node process closes', async () => { 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 {spawn, execSync} = await import('child_process');
const options = Object.assign({}, defaultBrowserOptions, { 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 {Frame} from 'puppeteer-core/internal/api/Frame.js';
import {CDPSession} from 'puppeteer-core/internal/common/Connection.js'; import {CDPSession} from 'puppeteer-core/internal/common/Connection.js';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import { import {
attachFrame, attachFrame,
detachFrame, detachFrame,
@ -32,12 +28,9 @@ import {
} from './utils.js'; } from './utils.js';
describe('Frame specs', function () { describe('Frame specs', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Frame.executionContext', function () { describe('Frame.executionContext', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE); await attachFrame(page, 'frame1', server.EMPTY_PAGE);
@ -74,7 +67,7 @@ describe('Frame specs', function () {
describe('Frame.evaluateHandle', function () { describe('Frame.evaluateHandle', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const mainFrame = page.mainFrame(); const mainFrame = page.mainFrame();
@ -87,7 +80,7 @@ describe('Frame specs', function () {
describe('Frame.evaluate', function () { describe('Frame.evaluate', function () {
it('should throw for detached frames', async () => { 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))!; const frame1 = (await attachFrame(page, 'frame1', server.EMPTY_PAGE))!;
await detachFrame(page, 'frame1'); await detachFrame(page, 'frame1');
@ -105,7 +98,7 @@ describe('Frame specs', function () {
}); });
it('allows readonly array to be an argument', async () => { it('allows readonly array to be an argument', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const mainFrame = page.mainFrame(); const mainFrame = page.mainFrame();
@ -120,7 +113,7 @@ describe('Frame specs', function () {
describe('Frame.page', function () { describe('Frame.page', function () {
it('should retrieve the page from a frame', async () => { it('should retrieve the page from a frame', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const mainFrame = page.mainFrame(); const mainFrame = page.mainFrame();
expect(mainFrame.page()).toEqual(page); expect(mainFrame.page()).toEqual(page);
@ -129,7 +122,7 @@ describe('Frame specs', function () {
describe('Frame Management', function () { describe('Frame Management', function () {
it('should handle nested frames', async () => { it('should handle nested frames', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/frames/nested-frames.html'); await page.goto(server.PREFIX + '/frames/nested-frames.html');
expect(dumpFrames(page.mainFrame())).toEqual([ expect(dumpFrames(page.mainFrame())).toEqual([
@ -141,7 +134,7 @@ describe('Frame specs', function () {
]); ]);
}); });
it('should send events when frames are manipulated dynamically', async () => { 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); await page.goto(server.EMPTY_PAGE);
// validate frameattached events // validate frameattached events
@ -172,7 +165,7 @@ describe('Frame specs', function () {
expect(detachedFrames[0]!.isDetached()).toBe(true); expect(detachedFrames[0]!.isDetached()).toBe(true);
}); });
it('should send "framenavigated" when navigating on anchor URLs', async () => { 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 page.goto(server.EMPTY_PAGE);
await Promise.all([ await Promise.all([
@ -182,7 +175,7 @@ describe('Frame specs', function () {
expect(page.url()).toBe(server.EMPTY_PAGE + '#foo'); expect(page.url()).toBe(server.EMPTY_PAGE + '#foo');
}); });
it('should persist mainFrame on cross-process navigation', async () => { it('should persist mainFrame on cross-process navigation', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const mainFrame = page.mainFrame(); const mainFrame = page.mainFrame();
@ -190,7 +183,7 @@ describe('Frame specs', function () {
expect(page.mainFrame() === mainFrame).toBeTruthy(); expect(page.mainFrame() === mainFrame).toBeTruthy();
}); });
it('should not send attach/detach events for main frame', async () => { it('should not send attach/detach events for main frame', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
let hasEvents = false; let hasEvents = false;
page.on('frameattached', () => { page.on('frameattached', () => {
@ -203,7 +196,7 @@ describe('Frame specs', function () {
expect(hasEvents).toBe(false); expect(hasEvents).toBe(false);
}); });
it('should detach child frames on navigation', async () => { it('should detach child frames on navigation', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
let attachedFrames: Frame[] = []; let attachedFrames: Frame[] = [];
let detachedFrames: Frame[] = []; let detachedFrames: Frame[] = [];
@ -231,7 +224,7 @@ describe('Frame specs', function () {
expect(navigatedFrames).toHaveLength(1); expect(navigatedFrames).toHaveLength(1);
}); });
it('should support framesets', async () => { it('should support framesets', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
let attachedFrames: Frame[] = []; let attachedFrames: Frame[] = [];
let detachedFrames: Frame[] = []; let detachedFrames: Frame[] = [];
@ -259,7 +252,7 @@ describe('Frame specs', function () {
expect(navigatedFrames).toHaveLength(1); expect(navigatedFrames).toHaveLength(1);
}); });
it('should report frame from-inside shadow DOM', async () => { 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.goto(server.PREFIX + '/shadow.html');
await page.evaluate(async (url: string) => { await page.evaluate(async (url: string) => {
@ -274,7 +267,7 @@ describe('Frame specs', function () {
expect(page.frames()[1]!.url()).toBe(server.EMPTY_PAGE); expect(page.frames()[1]!.url()).toBe(server.EMPTY_PAGE);
}); });
it('should report frame.name()', async () => { it('should report frame.name()', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await attachFrame(page, 'theFrameId', server.EMPTY_PAGE); await attachFrame(page, 'theFrameId', server.EMPTY_PAGE);
await page.evaluate((url: string) => { await page.evaluate((url: string) => {
@ -291,7 +284,7 @@ describe('Frame specs', function () {
expect(page.frames()[2]!.name()).toBe('theFrameName'); expect(page.frames()[2]!.name()).toBe('theFrameName');
}); });
it('should report frame.parent()', async () => { 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, 'frame1', server.EMPTY_PAGE);
await attachFrame(page, 'frame2', 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()); expect(page.frames()[2]!.parentFrame()).toBe(page.mainFrame());
}); });
it('should report different frame instance when frame re-attaches', async () => { 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); const frame1 = await attachFrame(page, 'frame1', server.EMPTY_PAGE);
await page.evaluate(() => { await page.evaluate(() => {
@ -318,7 +311,7 @@ describe('Frame specs', function () {
expect(frame1).not.toBe(frame2); expect(frame1).not.toBe(frame2);
}); });
it('should support url fragment', async () => { 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'); 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 () => { it('should support lazy frames', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setViewport({width: 1000, height: 1000}); await page.setViewport({width: 1000, height: 1000});
await page.goto(server.PREFIX + '/frames/lazy-frame.html'); await page.goto(server.PREFIX + '/frames/lazy-frame.html');
@ -343,7 +336,7 @@ describe('Frame specs', function () {
describe('Frame.client', function () { describe('Frame.client', function () {
it('should return the client instance', async () => { it('should return the client instance', async () => {
const {page} = getTestState(); const {page} = await getTestState();
expect(page.mainFrame()._client()).toBeInstanceOf(CDPSession); expect(page.mainFrame()._client()).toBeInstanceOf(CDPSession);
}); });
}); });

View File

@ -58,8 +58,10 @@ describe('headful tests', function () {
}; };
const browsers: Array<() => Promise<void>> = []; const browsers: Array<() => Promise<void>> = [];
beforeEach(() => { beforeEach(async () => {
const {server, defaultBrowserOptions} = getTestState(); const {server, defaultBrowserOptions} = await getTestState({
skipLaunch: true,
});
headfulOptions = Object.assign({}, defaultBrowserOptions, { headfulOptions = Object.assign({}, defaultBrowserOptions, {
headless: false, headless: false,
}); });
@ -122,9 +124,7 @@ describe('headful tests', function () {
expect(backgroundPageTarget).toBeTruthy(); expect(backgroundPageTarget).toBeTruthy();
}); });
it('service_worker target type should be available', async () => { it('service_worker target type should be available', async () => {
const {defaultBrowserOptions} = getTestState();
const browserWithExtension = await launchBrowser({ const browserWithExtension = await launchBrowser({
...defaultBrowserOptions,
headless: false, headless: false,
args: [ args: [
`--disable-extensions-except=${serviceWorkerExtensionPath}`, `--disable-extensions-except=${serviceWorkerExtensionPath}`,
@ -162,7 +162,7 @@ describe('headful tests', function () {
await browserWithExtension.close(); await browserWithExtension.close();
}); });
it('target.page() should return a DevTools page if custom isPageTarget is provided', async function () { 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 originalBrowser = await launchBrowser(devtoolsOptions);
const browserWSEndpoint = originalBrowser.wsEndpoint(); const browserWSEndpoint = originalBrowser.wsEndpoint();
@ -195,7 +195,7 @@ describe('headful tests', function () {
}); });
it('headless should be able to read cookies written by headful', async () => { it('headless should be able to read cookies written by headful', async () => {
/* Needs investigation into why but this fails consistently on Windows CI. */ /* 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); const userDataDir = await mkdtemp(TMP_FOLDER);
// Write a cookie in headful chrome // 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 // TODO: Support OOOPIF. @see https://github.com/puppeteer/puppeteer/issues/2548
it.skip('OOPIF: should report google.com frame', async () => { 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. // https://google.com is isolated by default in Chromium embedder.
const browser = await launchBrowser(headfulOptions); const browser = await launchBrowser(headfulOptions);
@ -255,8 +255,7 @@ describe('headful tests', function () {
expect(urls).toEqual([server.EMPTY_PAGE, 'https://google.com/']); expect(urls).toEqual([server.EMPTY_PAGE, 'https://google.com/']);
}); });
it('OOPIF: should expose events within OOPIFs', async () => { it('OOPIF: should expose events within OOPIFs', async () => {
const {server} = getTestState(); const {server} = await getTestState({skipLaunch: true});
const browser = await launchBrowser(forcedOopifOptions); const browser = await launchBrowser(forcedOopifOptions);
const page = await browser.newPage(); const page = await browser.newPage();
@ -315,10 +314,10 @@ describe('headful tests', function () {
expect(requests).toContain(`http://oopifdomain:${server.PORT}/fetch`); expect(requests).toContain(`http://oopifdomain:${server.PORT}/fetch`);
}); });
it('should close browser with beforeunload page', async () => { it('should close browser with beforeunload page', async () => {
const {server} = getTestState(); const {server} = await getTestState({skipLaunch: true});
const browser = await launchBrowser(headfulOptions); const browser = await launchBrowser(headfulOptions);
const page = await browser.newPage(); const page = await browser.newPage();
await page.goto(server.PREFIX + '/beforeunload.html'); await page.goto(server.PREFIX + '/beforeunload.html');
// We have to interact with a page so that 'beforeunload' handlers // We have to interact with a page so that 'beforeunload' handlers
// fire. // fire.
@ -378,7 +377,7 @@ describe('headful tests', function () {
describe('Page.screenshot', function () { describe('Page.screenshot', function () {
it('should run in parallel in multiple pages', async () => { it('should run in parallel in multiple pages', async () => {
const {server} = getTestState(); const {server} = await getTestState({skipLaunch: true});
const browser = await launchBrowser(headfulOptions); const browser = await launchBrowser(headfulOptions);
const context = await browser.createIncognitoBrowserContext(); const context = await browser.createIncognitoBrowserContext();

View File

@ -16,33 +16,25 @@
import expect from 'expect'; import expect from 'expect';
import {ElementHandle} from 'puppeteer-core/internal/api/ElementHandle.js'; import {ElementHandle} from 'puppeteer-core/internal/api/ElementHandle.js';
import {Page} from 'puppeteer-core/internal/api/Page.js';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
describe('Emulate idle state', () => { describe('Emulate idle state', () => {
setupTestBrowserHooks(); async function getIdleState(page: Page) {
setupTestPageAndContextHooks();
async function getIdleState() {
const {page} = getTestState();
const stateElement = (await page.$('#state')) as ElementHandle<HTMLElement>; const stateElement = (await page.$('#state')) as ElementHandle<HTMLElement>;
return await page.evaluate(element => { return await page.evaluate(element => {
return element.innerText; return element.innerText;
}, stateElement); }, stateElement);
} }
async function verifyState(expectedState: string) { async function verifyState(page: Page, expectedState: string) {
const actualState = await getIdleState(); const actualState = await getIdleState(page);
expect(actualState).toEqual(expectedState); expect(actualState).toEqual(expectedState);
} }
it('changing idle state emulation causes change of the IdleDetector state', async () => { 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', [ await context.overridePermissions(server.PREFIX + '/idle-detector.html', [
'idle-detection', 'idle-detection',
]); ]);
@ -50,46 +42,46 @@ describe('Emulate idle state', () => {
await page.goto(server.PREFIX + '/idle-detector.html'); await page.goto(server.PREFIX + '/idle-detector.html');
// Store initial state, as soon as it is not guaranteed to be `active, unlocked`. // 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. // Emulate Idle states and verify IdleDetector updates state accordingly.
await page.emulateIdleState({ await page.emulateIdleState({
isUserActive: false, isUserActive: false,
isScreenUnlocked: false, isScreenUnlocked: false,
}); });
await verifyState('Idle state: idle, locked.'); await verifyState(page, 'Idle state: idle, locked.');
await page.emulateIdleState({ await page.emulateIdleState({
isUserActive: true, isUserActive: true,
isScreenUnlocked: false, isScreenUnlocked: false,
}); });
await verifyState('Idle state: active, locked.'); await verifyState(page, 'Idle state: active, locked.');
await page.emulateIdleState({ await page.emulateIdleState({
isUserActive: true, isUserActive: true,
isScreenUnlocked: true, isScreenUnlocked: true,
}); });
await verifyState('Idle state: active, unlocked.'); await verifyState(page, 'Idle state: active, unlocked.');
await page.emulateIdleState({ await page.emulateIdleState({
isUserActive: false, isUserActive: false,
isScreenUnlocked: true, 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. // Remove Idle emulation and verify IdleDetector is in initial state.
await page.emulateIdleState(); await page.emulateIdleState();
await verifyState(initialState); await verifyState(page, initialState);
// Emulate idle state again after removing emulation. // Emulate idle state again after removing emulation.
await page.emulateIdleState({ await page.emulateIdleState({
isUserActive: false, isUserActive: false,
isScreenUnlocked: false, isScreenUnlocked: false,
}); });
await verifyState('Idle state: idle, locked.'); await verifyState(page, 'Idle state: idle, locked.');
// Remove emulation second time. // Remove emulation second time.
await page.emulateIdleState(); await page.emulateIdleState();
await verifyState(initialState); await verifyState(page, initialState);
}); });
}); });

View File

@ -34,7 +34,7 @@ describe('ignoreHTTPSErrors', function () {
let page!: Page; let page!: Page;
before(async () => { before(async () => {
const {defaultBrowserOptions, puppeteer} = getTestState(); const {defaultBrowserOptions, puppeteer} = await getTestState();
const options = Object.assign( const options = Object.assign(
{ignoreHTTPSErrors: true}, {ignoreHTTPSErrors: true},
defaultBrowserOptions defaultBrowserOptions
@ -58,7 +58,7 @@ describe('ignoreHTTPSErrors', function () {
describe('Response.securityDetails', function () { describe('Response.securityDetails', function () {
it('should work', async () => { it('should work', async () => {
const {httpsServer} = getTestState(); const {httpsServer} = await getTestState();
const [serverRequest, response] = await Promise.all([ const [serverRequest, response] = await Promise.all([
httpsServer.waitForRequest('/empty.html'), httpsServer.waitForRequest('/empty.html'),
@ -79,13 +79,13 @@ describe('ignoreHTTPSErrors', function () {
]); ]);
}); });
it('should be |null| for non-secure requests', async () => { it('should be |null| for non-secure requests', async () => {
const {server} = getTestState(); const {server} = await getTestState();
const response = (await page.goto(server.EMPTY_PAGE))!; const response = (await page.goto(server.EMPTY_PAGE))!;
expect(response.securityDetails()).toBe(null); expect(response.securityDetails()).toBe(null);
}); });
it('Network redirects should report SecurityDetails', async () => { it('Network redirects should report SecurityDetails', async () => {
const {httpsServer} = getTestState(); const {httpsServer} = await getTestState();
httpsServer.setRedirect('/plzredirect', '/empty.html'); httpsServer.setRedirect('/plzredirect', '/empty.html');
const responses: HTTPResponse[] = []; const responses: HTTPResponse[] = [];
@ -107,7 +107,7 @@ describe('ignoreHTTPSErrors', function () {
}); });
it('should work', async () => { it('should work', async () => {
const {httpsServer} = getTestState(); const {httpsServer} = await getTestState();
let error!: Error; let error!: Error;
const response = await page.goto(httpsServer.EMPTY_PAGE).catch(error_ => { const response = await page.goto(httpsServer.EMPTY_PAGE).catch(error_ => {
@ -117,7 +117,7 @@ describe('ignoreHTTPSErrors', function () {
expect(response.ok()).toBe(true); expect(response.ok()).toBe(true);
}); });
it('should work with request interception', async () => { it('should work with request interception', async () => {
const {httpsServer} = getTestState(); const {httpsServer} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -127,7 +127,7 @@ describe('ignoreHTTPSErrors', function () {
expect(response.status()).toBe(200); expect(response.status()).toBe(200);
}); });
it('should work with mixed content', async () => { it('should work with mixed content', async () => {
const {server, httpsServer} = getTestState(); const {server, httpsServer} = await getTestState();
httpsServer.setRoute('/mixedcontent.html', (_req, res) => { httpsServer.setRoute('/mixedcontent.html', (_req, res) => {
res.end(`<iframe src=${server.EMPTY_PAGE}></iframe>`); 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 {PUPPETEER_WORLD} from 'puppeteer-core/internal/common/IsolatedWorlds.js';
import {LazyArg} from 'puppeteer-core/internal/common/LazyArg.js'; import {LazyArg} from 'puppeteer-core/internal/common/LazyArg.js';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
describe('PuppeteerUtil tests', function () { describe('PuppeteerUtil tests', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const world = page.mainFrame().worlds[PUPPETEER_WORLD]; const world = page.mainFrame().worlds[PUPPETEER_WORLD];
const value = await world.evaluate( const value = await world.evaluate(
@ -45,7 +38,7 @@ describe('PuppeteerUtil tests', function () {
describe('createFunction tests', function () { describe('createFunction tests', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const world = page.mainFrame().worlds[PUPPETEER_WORLD]; const world = page.mainFrame().worlds[PUPPETEER_WORLD];
const value = await world.evaluate( const value = await world.evaluate(

View File

@ -19,22 +19,15 @@ import path from 'path';
import expect from 'expect'; import expect from 'expect';
import {TimeoutError} from 'puppeteer'; import {TimeoutError} from 'puppeteer';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {waitEvent} from './utils.js'; import {waitEvent} from './utils.js';
const FILE_TO_UPLOAD = path.join(__dirname, '/../assets/file-to-upload.txt'); const FILE_TO_UPLOAD = path.join(__dirname, '/../assets/file-to-upload.txt');
describe('input tests', function () { describe('input tests', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('input', function () { describe('input', function () {
it('should upload the file', async () => { it('should upload the file', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/fileupload.html'); await page.goto(server.PREFIX + '/input/fileupload.html');
const filePath = path.relative(process.cwd(), FILE_TO_UPLOAD); const filePath = path.relative(process.cwd(), FILE_TO_UPLOAD);
@ -81,7 +74,7 @@ describe('input tests', function () {
describe('Page.waitForFileChooser', function () { describe('Page.waitForFileChooser', function () {
it('should work when file input is attached to DOM', async () => { it('should work when file input is attached to DOM', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(`<input type=file>`); await page.setContent(`<input type=file>`);
const [chooser] = await Promise.all([ const [chooser] = await Promise.all([
@ -91,7 +84,7 @@ describe('input tests', function () {
expect(chooser).toBeTruthy(); expect(chooser).toBeTruthy();
}); });
it('should work when file input is not attached to DOM', async () => { it('should work when file input is not attached to DOM', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const [chooser] = await Promise.all([ const [chooser] = await Promise.all([
page.waitForFileChooser(), page.waitForFileChooser(),
@ -104,7 +97,7 @@ describe('input tests', function () {
expect(chooser).toBeTruthy(); expect(chooser).toBeTruthy();
}); });
it('should respect timeout', async () => { it('should respect timeout', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page.waitForFileChooser({timeout: 1}).catch(error_ => { await page.waitForFileChooser({timeout: 1}).catch(error_ => {
@ -113,7 +106,7 @@ describe('input tests', function () {
expect(error).toBeInstanceOf(TimeoutError); expect(error).toBeInstanceOf(TimeoutError);
}); });
it('should respect default timeout when there is no custom timeout', async () => { it('should respect default timeout when there is no custom timeout', async () => {
const {page} = getTestState(); const {page} = await getTestState();
page.setDefaultTimeout(1); page.setDefaultTimeout(1);
let error!: Error; let error!: Error;
@ -123,7 +116,7 @@ describe('input tests', function () {
expect(error).toBeInstanceOf(TimeoutError); expect(error).toBeInstanceOf(TimeoutError);
}); });
it('should prioritize exact timeout over default timeout', async () => { it('should prioritize exact timeout over default timeout', async () => {
const {page} = getTestState(); const {page} = await getTestState();
page.setDefaultTimeout(0); page.setDefaultTimeout(0);
let error!: Error; let error!: Error;
@ -133,7 +126,7 @@ describe('input tests', function () {
expect(error).toBeInstanceOf(TimeoutError); expect(error).toBeInstanceOf(TimeoutError);
}); });
it('should work with no timeout', async () => { it('should work with no timeout', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const [chooser] = await Promise.all([ const [chooser] = await Promise.all([
page.waitForFileChooser({timeout: 0}), page.waitForFileChooser({timeout: 0}),
@ -148,7 +141,7 @@ describe('input tests', function () {
expect(chooser).toBeTruthy(); expect(chooser).toBeTruthy();
}); });
it('should return the same file chooser when there are many watchdogs simultaneously', async () => { 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>`); await page.setContent(`<input type=file>`);
const [fileChooser1, fileChooser2] = await Promise.all([ const [fileChooser1, fileChooser2] = await Promise.all([
@ -164,7 +157,7 @@ describe('input tests', function () {
describe('FileChooser.accept', function () { describe('FileChooser.accept', function () {
it('should accept single file', async () => { it('should accept single file', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
`<input type=file oninput='javascript:console.timeStamp()'>` `<input type=file oninput='javascript:console.timeStamp()'>`
@ -189,7 +182,7 @@ describe('input tests', function () {
).toBe('file-to-upload.txt'); ).toBe('file-to-upload.txt');
}); });
it('should be able to read selected file', async () => { it('should be able to read selected file', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(`<input type=file>`); await page.setContent(`<input type=file>`);
page.waitForFileChooser().then(chooser => { page.waitForFileChooser().then(chooser => {
@ -214,7 +207,7 @@ describe('input tests', function () {
).toBe('contents of the file'); ).toBe('contents of the file');
}); });
it('should be able to reset selected files with empty file list', async () => { 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>`); await page.setContent(`<input type=file>`);
page.waitForFileChooser().then(chooser => { page.waitForFileChooser().then(chooser => {
@ -245,7 +238,7 @@ describe('input tests', function () {
).toBe(0); ).toBe(0);
}); });
it('should not accept multiple files for single-file input', async () => { it('should not accept multiple files for single-file input', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(`<input type=file>`); await page.setContent(`<input type=file>`);
const [chooser] = await Promise.all([ const [chooser] = await Promise.all([
@ -267,7 +260,7 @@ describe('input tests', function () {
expect(error).not.toBe(null); expect(error).not.toBe(null);
}); });
it('should succeed even for non-existent files', async () => { it('should succeed even for non-existent files', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(`<input type=file>`); await page.setContent(`<input type=file>`);
const [chooser] = await Promise.all([ const [chooser] = await Promise.all([
@ -281,7 +274,7 @@ describe('input tests', function () {
expect(error).toBeUndefined(); expect(error).toBeUndefined();
}); });
it('should error on read of non-existent files', async () => { it('should error on read of non-existent files', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(`<input type=file>`); await page.setContent(`<input type=file>`);
page.waitForFileChooser().then(chooser => { page.waitForFileChooser().then(chooser => {
@ -306,7 +299,7 @@ describe('input tests', function () {
).toBeFalsy(); ).toBeFalsy();
}); });
it('should fail when accepting file chooser twice', async () => { it('should fail when accepting file chooser twice', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(`<input type=file>`); await page.setContent(`<input type=file>`);
const [fileChooser] = await Promise.all([ const [fileChooser] = await Promise.all([
@ -328,7 +321,7 @@ describe('input tests', function () {
describe('FileChooser.cancel', function () { describe('FileChooser.cancel', function () {
it('should cancel dialog', async () => { it('should cancel dialog', async () => {
const {page} = getTestState(); const {page} = await getTestState();
// Consider file chooser canceled if we can summon another one. // Consider file chooser canceled if we can summon another one.
// There's no reliable way in WebPlatform to see that FileChooser was // 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 () => { it('should fail when canceling file chooser twice', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(`<input type=file>`); await page.setContent(`<input type=file>`);
const [fileChooser] = await Promise.all([ const [fileChooser] = await Promise.all([
@ -376,7 +369,7 @@ describe('input tests', function () {
describe('FileChooser.isMultiple', () => { describe('FileChooser.isMultiple', () => {
it('should work for single file pick', async () => { it('should work for single file pick', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(`<input type=file>`); await page.setContent(`<input type=file>`);
const [chooser] = await Promise.all([ const [chooser] = await Promise.all([
@ -386,7 +379,7 @@ describe('input tests', function () {
expect(chooser.isMultiple()).toBe(false); expect(chooser.isMultiple()).toBe(false);
}); });
it('should work for "multiple"', async () => { it('should work for "multiple"', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(`<input multiple type=file>`); await page.setContent(`<input multiple type=file>`);
const [chooser] = await Promise.all([ const [chooser] = await Promise.all([
@ -396,7 +389,7 @@ describe('input tests', function () {
expect(chooser.isMultiple()).toBe(true); expect(chooser.isMultiple()).toBe(true);
}); });
it('should work for "webkitdirectory"', async () => { it('should work for "webkitdirectory"', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(`<input multiple webkitdirectory type=file>`); await page.setContent(`<input multiple webkitdirectory type=file>`);
const [chooser] = await Promise.all([ const [chooser] = await Promise.all([

View File

@ -16,19 +16,12 @@
import expect from 'expect'; import expect from 'expect';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
describe('JSHandle', function () { describe('JSHandle', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Page.evaluateHandle', function () { describe('Page.evaluateHandle', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const windowHandle = await page.evaluateHandle(() => { const windowHandle = await page.evaluateHandle(() => {
return window; return window;
@ -36,7 +29,7 @@ describe('JSHandle', function () {
expect(windowHandle).toBeTruthy(); expect(windowHandle).toBeTruthy();
}); });
it('should return the RemoteObject', async () => { it('should return the RemoteObject', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const windowHandle = await page.evaluateHandle(() => { const windowHandle = await page.evaluateHandle(() => {
return window; return window;
@ -44,7 +37,7 @@ describe('JSHandle', function () {
expect(windowHandle.remoteObject()).toBeTruthy(); expect(windowHandle.remoteObject()).toBeTruthy();
}); });
it('should accept object handle as an argument', async () => { it('should accept object handle as an argument', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const navigatorHandle = await page.evaluateHandle(() => { const navigatorHandle = await page.evaluateHandle(() => {
return navigator; return navigator;
@ -55,7 +48,7 @@ describe('JSHandle', function () {
expect(text).toContain('Mozilla'); expect(text).toContain('Mozilla');
}); });
it('should accept object handle to primitive types', async () => { it('should accept object handle to primitive types', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const aHandle = await page.evaluateHandle(() => { const aHandle = await page.evaluateHandle(() => {
return 5; return 5;
@ -66,7 +59,7 @@ describe('JSHandle', function () {
expect(isFive).toBeTruthy(); expect(isFive).toBeTruthy();
}); });
it('should warn about recursive objects', async () => { it('should warn about recursive objects', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const test: {obj?: unknown} = {}; const test: {obj?: unknown} = {};
test.obj = test; test.obj = test;
@ -81,7 +74,7 @@ describe('JSHandle', function () {
expect(error.message).toContain('Recursive objects are not allowed.'); expect(error.message).toContain('Recursive objects are not allowed.');
}); });
it('should accept object handle to unserializable value', async () => { it('should accept object handle to unserializable value', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const aHandle = await page.evaluateHandle(() => { const aHandle = await page.evaluateHandle(() => {
return Infinity; return Infinity;
@ -93,7 +86,7 @@ describe('JSHandle', function () {
).toBe(true); ).toBe(true);
}); });
it('should use the same JS wrappers', async () => { it('should use the same JS wrappers', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const aHandle = await page.evaluateHandle(() => { const aHandle = await page.evaluateHandle(() => {
(globalThis as any).FOO = 123; (globalThis as any).FOO = 123;
@ -109,7 +102,7 @@ describe('JSHandle', function () {
describe('JSHandle.getProperty', function () { describe('JSHandle.getProperty', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const aHandle = await page.evaluateHandle(() => { const aHandle = await page.evaluateHandle(() => {
return { return {
@ -125,7 +118,7 @@ describe('JSHandle', function () {
describe('JSHandle.jsonValue', function () { describe('JSHandle.jsonValue', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const aHandle = await page.evaluateHandle(() => { const aHandle = await page.evaluateHandle(() => {
return {foo: 'bar'}; return {foo: 'bar'};
@ -135,7 +128,7 @@ describe('JSHandle', function () {
}); });
it('works with jsonValues that are not objects', async () => { it('works with jsonValues that are not objects', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const aHandle = await page.evaluateHandle(() => { const aHandle = await page.evaluateHandle(() => {
return ['a', 'b']; return ['a', 'b'];
@ -145,7 +138,7 @@ describe('JSHandle', function () {
}); });
it('works with jsonValues that are primitives', async () => { it('works with jsonValues that are primitives', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const aHandle = await page.evaluateHandle(() => { const aHandle = await page.evaluateHandle(() => {
return 'foo'; return 'foo';
@ -159,7 +152,7 @@ describe('JSHandle', function () {
}); });
it('should work with dates', async () => { it('should work with dates', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const dateHandle = await page.evaluateHandle(() => { const dateHandle = await page.evaluateHandle(() => {
return new Date('2017-09-26T00:00:00.000Z'); 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'); expect(date.toISOString()).toEqual('2017-09-26T00:00:00.000Z');
}); });
it('should throw for circular objects', async () => { it('should throw for circular objects', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const handle = await page.evaluateHandle(() => { const handle = await page.evaluateHandle(() => {
const t: {t?: unknown; g: number} = {g: 1}; const t: {t?: unknown; g: number} = {g: 1};
@ -185,7 +178,7 @@ describe('JSHandle', function () {
describe('JSHandle.getProperties', function () { describe('JSHandle.getProperties', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const aHandle = await page.evaluateHandle(() => { const aHandle = await page.evaluateHandle(() => {
return { return {
@ -198,7 +191,7 @@ describe('JSHandle', function () {
expect(await foo.jsonValue()).toBe('bar'); expect(await foo.jsonValue()).toBe('bar');
}); });
it('should return even non-own properties', async () => { it('should return even non-own properties', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const aHandle = await page.evaluateHandle(() => { const aHandle = await page.evaluateHandle(() => {
class A { class A {
@ -224,7 +217,7 @@ describe('JSHandle', function () {
describe('JSHandle.asElement', function () { describe('JSHandle.asElement', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const aHandle = await page.evaluateHandle(() => { const aHandle = await page.evaluateHandle(() => {
return document.body; return document.body;
@ -233,7 +226,7 @@ describe('JSHandle', function () {
expect(element).toBeTruthy(); expect(element).toBeTruthy();
}); });
it('should return null for non-elements', async () => { it('should return null for non-elements', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const aHandle = await page.evaluateHandle(() => { const aHandle = await page.evaluateHandle(() => {
return 2; return 2;
@ -242,7 +235,7 @@ describe('JSHandle', function () {
expect(element).toBeFalsy(); expect(element).toBeFalsy();
}); });
it('should return ElementHandle for TextNodes', async () => { it('should return ElementHandle for TextNodes', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div>ee!</div>'); await page.setContent('<div>ee!</div>');
const aHandle = await page.evaluateHandle(() => { const aHandle = await page.evaluateHandle(() => {
@ -260,7 +253,7 @@ describe('JSHandle', function () {
describe('JSHandle.toString', function () { describe('JSHandle.toString', function () {
it('should work for primitives', async () => { it('should work for primitives', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const numberHandle = await page.evaluateHandle(() => { const numberHandle = await page.evaluateHandle(() => {
return 2; return 2;
@ -272,7 +265,7 @@ describe('JSHandle', function () {
expect(stringHandle.toString()).toBe('JSHandle:a'); expect(stringHandle.toString()).toBe('JSHandle:a');
}); });
it('should work for complicated objects', async () => { it('should work for complicated objects', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const aHandle = await page.evaluateHandle(() => { const aHandle = await page.evaluateHandle(() => {
return window; return window;
@ -283,7 +276,7 @@ describe('JSHandle', function () {
]); ]);
}); });
it('should work with different subtypes', async () => { it('should work with different subtypes', async () => {
const {page} = getTestState(); const {page} = await getTestState();
expect((await page.evaluateHandle('(function(){})')).toString()).toBe( expect((await page.evaluateHandle('(function(){})')).toString()).toBe(
'JSHandle@function' 'JSHandle@function'

View File

@ -19,19 +19,12 @@ import os from 'os';
import expect from 'expect'; import expect from 'expect';
import {KeyInput} from 'puppeteer-core/internal/common/USKeyboardLayout.js'; import {KeyInput} from 'puppeteer-core/internal/common/USKeyboardLayout.js';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {attachFrame} from './utils.js'; import {attachFrame} from './utils.js';
describe('Keyboard', function () { describe('Keyboard', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('should type into a textarea', async () => { it('should type into a textarea', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.evaluate(() => { await page.evaluate(() => {
const textarea = document.createElement('textarea'); const textarea = document.createElement('textarea');
@ -47,7 +40,7 @@ describe('Keyboard', function () {
).toBe(text); ).toBe(text);
}); });
it('should press the metaKey', async () => { it('should press the metaKey', async () => {
const {page, isFirefox} = getTestState(); const {page, isFirefox} = await getTestState();
await page.evaluate(() => { await page.evaluate(() => {
(window as any).keyPromise = new Promise(resolve => { (window as any).keyPromise = new Promise(resolve => {
@ -62,7 +55,7 @@ describe('Keyboard', function () {
); );
}); });
it('should move with the arrow keys', async () => { 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.goto(server.PREFIX + '/input/textarea.html');
await page.type('textarea', 'Hello World!'); await page.type('textarea', 'Hello World!');
@ -94,7 +87,7 @@ describe('Keyboard', function () {
}); });
// @see https://github.com/puppeteer/puppeteer/issues/1313 // @see https://github.com/puppeteer/puppeteer/issues/1313
it('should trigger commands of keyboard shortcuts', async () => { it('should trigger commands of keyboard shortcuts', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const cmdKey = os.platform() !== 'darwin' ? 'Meta' : 'Control'; const cmdKey = os.platform() !== 'darwin' ? 'Meta' : 'Control';
await page.goto(server.PREFIX + '/input/textarea.html'); await page.goto(server.PREFIX + '/input/textarea.html');
@ -123,7 +116,7 @@ describe('Keyboard', function () {
).toBe('hellohello'); ).toBe('hellohello');
}); });
it('should send a character with ElementHandle.press', async () => { 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'); await page.goto(server.PREFIX + '/input/textarea.html');
const textarea = (await page.$('textarea'))!; const textarea = (await page.$('textarea'))!;
@ -152,7 +145,7 @@ describe('Keyboard', function () {
).toBe('a'); ).toBe('a');
}); });
it('ElementHandle.press should support |text| option', async () => { 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'); await page.goto(server.PREFIX + '/input/textarea.html');
const textarea = (await page.$('textarea'))!; const textarea = (await page.$('textarea'))!;
@ -164,7 +157,7 @@ describe('Keyboard', function () {
).toBe('ё'); ).toBe('ё');
}); });
it('should send a character with sendCharacter', async () => { 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.goto(server.PREFIX + '/input/textarea.html');
await page.focus('textarea'); await page.focus('textarea');
@ -191,7 +184,7 @@ describe('Keyboard', function () {
).toBe('嗨a'); ).toBe('嗨a');
}); });
it('should report shiftKey', async () => { it('should report shiftKey', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/keyboard.html'); await page.goto(server.PREFIX + '/input/keyboard.html');
const keyboard = page.keyboard; const keyboard = page.keyboard;
@ -262,7 +255,7 @@ describe('Keyboard', function () {
} }
}); });
it('should report multiple modifiers', async () => { it('should report multiple modifiers', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/keyboard.html'); await page.goto(server.PREFIX + '/input/keyboard.html');
const keyboard = page.keyboard; const keyboard = page.keyboard;
@ -304,7 +297,7 @@ describe('Keyboard', function () {
).toBe('Keyup: Alt AltLeft 18 []'); ).toBe('Keyup: Alt AltLeft 18 []');
}); });
it('should send proper codes while typing', async () => { 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.goto(server.PREFIX + '/input/keyboard.html');
await page.keyboard.type('!'); await page.keyboard.type('!');
@ -333,7 +326,7 @@ describe('Keyboard', function () {
); );
}); });
it('should send proper codes while typing with shift', async () => { 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'); await page.goto(server.PREFIX + '/input/keyboard.html');
const keyboard = page.keyboard; const keyboard = page.keyboard;
@ -354,7 +347,7 @@ describe('Keyboard', function () {
await keyboard.up('Shift'); await keyboard.up('Shift');
}); });
it('should not type canceled events', async () => { 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.goto(server.PREFIX + '/input/textarea.html');
await page.focus('textarea'); await page.focus('textarea');
@ -382,7 +375,7 @@ describe('Keyboard', function () {
).toBe('He Wrd!'); ).toBe('He Wrd!');
}); });
it('should specify repeat property', async () => { 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.goto(server.PREFIX + '/input/textarea.html');
await page.focus('textarea'); await page.focus('textarea');
@ -430,7 +423,7 @@ describe('Keyboard', function () {
).toBe(false); ).toBe(false);
}); });
it('should type all kinds of characters', async () => { 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.goto(server.PREFIX + '/input/textarea.html');
await page.focus('textarea'); await page.focus('textarea');
@ -439,7 +432,7 @@ describe('Keyboard', function () {
expect(await page.evaluate('result')).toBe(text); expect(await page.evaluate('result')).toBe(text);
}); });
it('should specify location', async () => { it('should specify location', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/textarea.html'); await page.goto(server.PREFIX + '/input/textarea.html');
await page.evaluate(() => { await page.evaluate(() => {
@ -466,7 +459,7 @@ describe('Keyboard', function () {
expect(await page.evaluate('keyLocation')).toBe(3); expect(await page.evaluate('keyLocation')).toBe(3);
}); });
it('should throw on unknown keys', async () => { it('should throw on unknown keys', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error = await page.keyboard let error = await page.keyboard
// @ts-expect-error bad input // @ts-expect-error bad input
@ -489,7 +482,7 @@ describe('Keyboard', function () {
expect(error && error.message).toBe('Unknown key: "😊"'); expect(error && error.message).toBe('Unknown key: "😊"');
}); });
it('should type emoji', async () => { it('should type emoji', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/textarea.html'); await page.goto(server.PREFIX + '/input/textarea.html');
await page.type('textarea', '👹 Tokyo street Japan 🇯🇵'); await page.type('textarea', '👹 Tokyo street Japan 🇯🇵');
@ -500,7 +493,7 @@ describe('Keyboard', function () {
).toBe('👹 Tokyo street Japan 🇯🇵'); ).toBe('👹 Tokyo street Japan 🇯🇵');
}); });
it('should type emoji into an iframe', async () => { it('should type emoji into an iframe', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await attachFrame( await attachFrame(
@ -518,7 +511,7 @@ describe('Keyboard', function () {
).toBe('👹 Tokyo street Japan 🇯🇵'); ).toBe('👹 Tokyo street Japan 🇯🇵');
}); });
it('should press the meta key', async () => { it('should press the meta key', async () => {
const {page, isFirefox} = getTestState(); const {page, isFirefox} = await getTestState();
await page.evaluate(() => { await page.evaluate(() => {
(globalThis as any).result = null; (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 {rmSync} from 'puppeteer-core/internal/node/util/fs.js';
import sinon from 'sinon'; import sinon from 'sinon';
import { import {getTestState, itOnlyRegularInstall, launch} from './mocha-utils.js';
getTestState,
itOnlyRegularInstall,
launch,
setupTestBrowserHooks,
} from './mocha-utils.js';
import {dumpFrames, waitEvent} from './utils.js'; import {dumpFrames, waitEvent} from './utils.js';
const TMP_FOLDER = path.join(os.tmpdir(), 'pptr_tmp_folder-'); const TMP_FOLDER = path.join(os.tmpdir(), 'pptr_tmp_folder-');
const FIREFOX_TIMEOUT = 30_000; const FIREFOX_TIMEOUT = 30_000;
describe('Launcher specs', function () { describe('Launcher specs', function () {
setupTestBrowserHooks(); this.timeout(FIREFOX_TIMEOUT);
if (getTestState().isFirefox) {
this.timeout(FIREFOX_TIMEOUT);
}
describe('Puppeteer', function () { describe('Puppeteer', function () {
describe('Browser.disconnect', function () { describe('Browser.disconnect', function () {
it('should reject navigation when browser closes', async () => { 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', () => {}); server.setRoute('/one-style.css', () => {});
const {browser, close} = await launch(defaultBrowserOptions);
try { try {
const remote = await puppeteer.connect({ const remote = await puppeteer.connect({
browserWSEndpoint: browser.wsEndpoint(), browserWSEndpoint: browser.wsEndpoint(),
@ -74,9 +64,8 @@ describe('Launcher specs', function () {
} }
}); });
it('should reject waitForSelector when browser closes', async () => { it('should reject waitForSelector when browser closes', async () => {
const {server, puppeteer, defaultBrowserOptions} = getTestState(); const {browser, close, server, puppeteer} = await launch({});
server.setRoute('/empty.html', () => {}); server.setRoute('/empty.html', () => {});
const {browser, close} = await launch(defaultBrowserOptions);
try { try {
const remote = await puppeteer.connect({ const remote = await puppeteer.connect({
browserWSEndpoint: browser.wsEndpoint(), browserWSEndpoint: browser.wsEndpoint(),
@ -97,8 +86,7 @@ describe('Launcher specs', function () {
}); });
describe('Browser.close', function () { describe('Browser.close', function () {
it('should terminate network waiters', async () => { it('should terminate network waiters', async () => {
const {server, puppeteer, defaultBrowserOptions} = getTestState(); const {browser, close, server, puppeteer} = await launch({});
const {browser, close} = await launch(defaultBrowserOptions);
try { try {
const remote = await puppeteer.connect({ const remote = await puppeteer.connect({
browserWSEndpoint: browser.wsEndpoint(), browserWSEndpoint: browser.wsEndpoint(),
@ -125,13 +113,11 @@ describe('Launcher specs', function () {
}); });
describe('Puppeteer.launch', function () { describe('Puppeteer.launch', function () {
it('can launch and close the browser', async () => { it('can launch and close the browser', async () => {
const {defaultBrowserOptions} = getTestState(); const {close} = await launch({});
const {close} = await launch(defaultBrowserOptions);
await close(); await close();
}); });
it('should reject all promises when browser is closed', async () => { it('should reject all promises when browser is closed', async () => {
const {defaultBrowserOptions} = getTestState(); const {page, close} = await launch({});
const {page, close} = await launch(defaultBrowserOptions);
let error!: Error; let error!: Error;
const neverResolves = page const neverResolves = page
.evaluate(() => { .evaluate(() => {
@ -145,23 +131,17 @@ describe('Launcher specs', function () {
expect(error.message).toContain('Protocol error'); expect(error.message).toContain('Protocol error');
}); });
it('should reject if executable path is invalid', async () => { it('should reject if executable path is invalid', async () => {
const {defaultBrowserOptions} = getTestState();
let waitError!: Error; let waitError!: Error;
const options = Object.assign({}, defaultBrowserOptions, { await launch({
executablePath: 'random-invalid-path', executablePath: 'random-invalid-path',
}); }).catch(error => {
await launch(options).catch(error => {
return (waitError = error); return (waitError = error);
}); });
expect(waitError.message).toContain('Failed to launch'); expect(waitError.message).toContain('Failed to launch');
}); });
it('userDataDir option', async () => { it('userDataDir option', async () => {
const {defaultBrowserOptions} = getTestState();
const userDataDir = await mkdtemp(TMP_FOLDER); const userDataDir = await mkdtemp(TMP_FOLDER);
const options = Object.assign({userDataDir}, defaultBrowserOptions); const {context, close} = await launch({userDataDir});
const {context, close} = await launch(options);
// Open a page to make sure its functional. // Open a page to make sure its functional.
try { try {
await context.newPage(); await context.newPage();
@ -177,7 +157,7 @@ describe('Launcher specs', function () {
} catch {} } catch {}
}); });
it('tmp profile should be cleaned up', async () => { 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 // Set a custom test tmp dir so that we can validate that
// the profile dir is created and then cleaned up. // 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. // Path should be empty before starting the browser.
expect(fs.readdirSync(testTmpDir)).toHaveLength(0); expect(fs.readdirSync(testTmpDir)).toHaveLength(0);
const {context, close} = await launch(defaultBrowserOptions); const {context, close} = await launch({});
try { try {
// One profile folder should have been created at this moment. // One profile folder should have been created at this moment.
const profiles = fs.readdirSync(testTmpDir); const profiles = fs.readdirSync(testTmpDir);
@ -211,16 +191,13 @@ describe('Launcher specs', function () {
puppeteer.configuration.temporaryDirectory = oldTmpDir; puppeteer.configuration.temporaryDirectory = oldTmpDir;
}); });
it('userDataDir option restores preferences', async () => { it('userDataDir option restores preferences', async () => {
const {defaultBrowserOptions} = getTestState();
const userDataDir = await mkdtemp(TMP_FOLDER); const userDataDir = await mkdtemp(TMP_FOLDER);
const prefsJSPath = path.join(userDataDir, 'prefs.js'); const prefsJSPath = path.join(userDataDir, 'prefs.js');
const prefsJSContent = 'user_pref("browser.warnOnQuit", true)'; const prefsJSContent = 'user_pref("browser.warnOnQuit", true)';
await writeFile(prefsJSPath, prefsJSContent); await writeFile(prefsJSPath, prefsJSContent);
const options = Object.assign({userDataDir}, defaultBrowserOptions); const {context, close} = await launch({userDataDir});
const {context, close} = await launch(options);
try { try {
// Open a page to make sure its functional. // Open a page to make sure its functional.
await context.newPage(); await context.newPage();
@ -239,21 +216,18 @@ describe('Launcher specs', function () {
} catch {} } catch {}
}); });
it('userDataDir argument', async () => { it('userDataDir argument', async () => {
const {isChrome, defaultBrowserOptions} = getTestState(); const {isChrome, defaultBrowserOptions: options} = await getTestState({
skipLaunch: true,
});
const userDataDir = await mkdtemp(TMP_FOLDER); const userDataDir = await mkdtemp(TMP_FOLDER);
const options = Object.assign({}, defaultBrowserOptions);
if (isChrome) { if (isChrome) {
options.args = [ options.args = [
...(defaultBrowserOptions.args || []), ...(options.args || []),
`--user-data-dir=${userDataDir}`, `--user-data-dir=${userDataDir}`,
]; ];
} else { } else {
options.args = [ options.args = [...(options.args || []), '-profile', userDataDir];
...(defaultBrowserOptions.args || []),
'-profile',
userDataDir,
];
} }
const {close} = await launch(options); const {close} = await launch(options);
expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0); expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
@ -265,7 +239,9 @@ describe('Launcher specs', function () {
} catch {} } catch {}
}); });
it('userDataDir argument with non-existent dir', async () => { 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); const userDataDir = await mkdtemp(TMP_FOLDER);
rmSync(userDataDir); rmSync(userDataDir);
@ -292,10 +268,8 @@ describe('Launcher specs', function () {
} catch {} } catch {}
}); });
it('userDataDir option should restore state', async () => { it('userDataDir option should restore state', async () => {
const {server, defaultBrowserOptions} = getTestState();
const userDataDir = await mkdtemp(TMP_FOLDER); const userDataDir = await mkdtemp(TMP_FOLDER);
const options = Object.assign({userDataDir}, defaultBrowserOptions); const {server, browser, close} = await launch({userDataDir});
const {browser, close} = await launch(options);
try { try {
const page = await browser.newPage(); const page = await browser.newPage();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -306,7 +280,7 @@ describe('Launcher specs', function () {
await close(); await close();
} }
const {browser: browser2, close: close2} = await launch(options); const {browser: browser2, close: close2} = await launch({userDataDir});
try { try {
const page2 = await browser2.newPage(); const page2 = await browser2.newPage();
@ -326,11 +300,8 @@ describe('Launcher specs', function () {
} catch {} } catch {}
}); });
it('userDataDir option should restore cookies', async () => { it('userDataDir option should restore cookies', async () => {
const {server, defaultBrowserOptions} = getTestState();
const userDataDir = await mkdtemp(TMP_FOLDER); const userDataDir = await mkdtemp(TMP_FOLDER);
const options = Object.assign({userDataDir}, defaultBrowserOptions); const {server, browser, close} = await launch({userDataDir});
const {browser, close} = await launch(options);
try { try {
const page = await browser.newPage(); const page = await browser.newPage();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -342,7 +313,7 @@ describe('Launcher specs', function () {
await close(); await close();
} }
const {browser: browser2, close: close2} = await launch(options); const {browser: browser2, close: close2} = await launch({userDataDir});
try { try {
const page2 = await browser2.newPage(); const page2 = await browser2.newPage();
await page2.goto(server.EMPTY_PAGE); await page2.goto(server.EMPTY_PAGE);
@ -361,7 +332,7 @@ describe('Launcher specs', function () {
} catch {} } catch {}
}); });
it('should return the default arguments', async () => { it('should return the default arguments', async () => {
const {isChrome, isFirefox, puppeteer} = getTestState(); const {isChrome, isFirefox, puppeteer} = await getTestState();
if (isChrome) { if (isChrome) {
expect(puppeteer.defaultArgs()).toContain('--no-first-run'); expect(puppeteer.defaultArgs()).toContain('--no-first-run');
@ -401,7 +372,7 @@ describe('Launcher specs', function () {
} }
}); });
it('should report the correct product', async () => { it('should report the correct product', async () => {
const {isChrome, isFirefox, puppeteer} = getTestState(); const {isChrome, isFirefox, puppeteer} = await getTestState();
if (isChrome) { if (isChrome) {
expect(puppeteer.product).toBe('chrome'); expect(puppeteer.product).toBe('chrome');
} else if (isFirefox) { } else if (isFirefox) {
@ -409,10 +380,9 @@ describe('Launcher specs', function () {
} }
}); });
it('should work with no default arguments', async () => { it('should work with no default arguments', async () => {
const {defaultBrowserOptions} = getTestState(); const {context, close} = await launch({
const options = Object.assign({}, defaultBrowserOptions); ignoreDefaultArgs: true,
options.ignoreDefaultArgs = true; });
const {context, close} = await launch(options);
try { try {
const page = await context.newPage(); const page = await context.newPage();
expect(await page.evaluate('11 * 11')).toBe(121); 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 () => { 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. // Make sure we launch with `--enable-automation` by default.
const defaultArgs = puppeteer.defaultArgs(); const defaultArgs = puppeteer.defaultArgs();
const {browser, close} = await launch( const {browser, close} = await launch(
@ -444,7 +416,9 @@ describe('Launcher specs', function () {
} }
}); });
it('should filter out ignored default argument in Firefox', async () => { 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 defaultArgs = puppeteer.defaultArgs();
const {browser, close} = await launch( const {browser, close} = await launch(
@ -465,10 +439,12 @@ describe('Launcher specs', function () {
} }
}); });
it('should have default URL when launching browser', async function () { it('should have default URL when launching browser', async function () {
const {defaultBrowserOptions} = getTestState(); const {browser, close} = await launch(
const {browser, close} = await launch(defaultBrowserOptions, { {},
createContext: false, {
}); createContext: false,
}
);
try { try {
const pages = (await browser.pages()).map(page => { const pages = (await browser.pages()).map(page => {
return page.url(); return page.url();
@ -479,11 +455,15 @@ describe('Launcher specs', function () {
} }
}); });
it('should have custom URL when launching browser', async () => { 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); const options = Object.assign({}, defaultBrowserOptions);
options.args = [server.EMPTY_PAGE].concat(options.args || []); 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 { try {
const pages = await browser.pages(); const pages = await browser.pages();
expect(pages).toHaveLength(1); expect(pages).toHaveLength(1);
@ -497,7 +477,7 @@ describe('Launcher specs', function () {
} }
}); });
it('should pass the timeout parameter to browser.waitForTarget', async () => { it('should pass the timeout parameter to browser.waitForTarget', async () => {
const {defaultBrowserOptions} = getTestState(); const {defaultBrowserOptions} = await getTestState();
const options = Object.assign({}, defaultBrowserOptions, { const options = Object.assign({}, defaultBrowserOptions, {
timeout: 1, timeout: 1,
}); });
@ -508,22 +488,18 @@ describe('Launcher specs', function () {
expect(error).toBeInstanceOf(TimeoutError); expect(error).toBeInstanceOf(TimeoutError);
}); });
it('should work with timeout = 0', async () => { it('should work with timeout = 0', async () => {
const {defaultBrowserOptions} = getTestState(); const {close} = await launch({
const options = Object.assign({}, defaultBrowserOptions, {
timeout: 0, timeout: 0,
}); });
const {close} = await launch(options);
await close(); await close();
}); });
it('should set the default viewport', async () => { it('should set the default viewport', async () => {
const {defaultBrowserOptions} = getTestState(); const {context, close} = await launch({
const options = Object.assign({}, defaultBrowserOptions, {
defaultViewport: { defaultViewport: {
width: 456, width: 456,
height: 789, height: 789,
}, },
}); });
const {context, close} = await launch(options);
try { try {
const page = await context.newPage(); const page = await context.newPage();
@ -534,11 +510,9 @@ describe('Launcher specs', function () {
} }
}); });
it('should disable the default viewport', async () => { it('should disable the default viewport', async () => {
const {defaultBrowserOptions} = getTestState(); const {context, close} = await launch({
const options = Object.assign({}, defaultBrowserOptions, {
defaultViewport: null, defaultViewport: null,
}); });
const {context, close} = await launch(options);
try { try {
const page = await context.newPage(); const page = await context.newPage();
expect(page.viewport()).toBe(null); expect(page.viewport()).toBe(null);
@ -547,12 +521,9 @@ describe('Launcher specs', function () {
} }
}); });
it('should take fullPage screenshots when defaultViewport is null', async () => { it('should take fullPage screenshots when defaultViewport is null', async () => {
const {server, defaultBrowserOptions} = getTestState(); const {server, context, close} = await launch({
const options = Object.assign({}, defaultBrowserOptions, {
defaultViewport: null, defaultViewport: null,
}); });
const {context, close} = await launch(options);
try { try {
const page = await context.newPage(); const page = await context.newPage();
await page.goto(server.PREFIX + '/grid.html'); await page.goto(server.PREFIX + '/grid.html');
@ -565,13 +536,10 @@ describe('Launcher specs', function () {
} }
}); });
it('should set the debugging port', async () => { it('should set the debugging port', async () => {
const {defaultBrowserOptions} = getTestState(); const {browser, close} = await launch({
const options = Object.assign({}, defaultBrowserOptions, {
defaultViewport: null, defaultViewport: null,
debuggingPort: 9999, debuggingPort: 9999,
}); });
const {browser, close} = await launch(options);
try { try {
const url = new URL(browser.wsEndpoint()); const url = new URL(browser.wsEndpoint());
expect(url.port).toBe('9999'); expect(url.port).toBe('9999');
@ -580,7 +548,7 @@ describe('Launcher specs', function () {
} }
}); });
it('should not allow setting debuggingPort and pipe', async () => { it('should not allow setting debuggingPort and pipe', async () => {
const {defaultBrowserOptions} = getTestState(); const {defaultBrowserOptions} = await getTestState();
const options = Object.assign({}, defaultBrowserOptions, { const options = Object.assign({}, defaultBrowserOptions, {
defaultViewport: null, defaultViewport: null,
@ -595,7 +563,9 @@ describe('Launcher specs', function () {
expect(error.message).toContain('either pipe or debugging port'); expect(error.message).toContain('either pipe or debugging port');
}); });
it('should launch Chrome properly with --no-startup-window and waitForInitialPage=false', async () => { it('should launch Chrome properly with --no-startup-window and waitForInitialPage=false', async () => {
const {defaultBrowserOptions} = getTestState(); const {defaultBrowserOptions} = await getTestState({
skipLaunch: true,
});
const options = { const options = {
waitForInitialPage: false, waitForInitialPage: false,
// This is needed to prevent Puppeteer from adding an initial blank page. // This is needed to prevent Puppeteer from adding an initial blank page.
@ -639,8 +609,7 @@ describe('Launcher specs', function () {
describe('Puppeteer.connect', function () { describe('Puppeteer.connect', function () {
it('should be able to connect multiple times to the same browser', async () => { it('should be able to connect multiple times to the same browser', async () => {
const {puppeteer, defaultBrowserOptions} = getTestState(); const {puppeteer, browser, close} = await launch({});
const {browser, close} = await launch(defaultBrowserOptions);
try { try {
const otherBrowser = await puppeteer.connect({ const otherBrowser = await puppeteer.connect({
browserWSEndpoint: browser.wsEndpoint(), browserWSEndpoint: browser.wsEndpoint(),
@ -664,8 +633,7 @@ describe('Launcher specs', function () {
} }
}); });
it('should be able to close remote browser', async () => { it('should be able to close remote browser', async () => {
const {defaultBrowserOptions, puppeteer} = getTestState(); const {puppeteer, browser, close} = await launch({});
const {browser, close} = await launch(defaultBrowserOptions);
try { try {
const remoteBrowser = await puppeteer.connect({ const remoteBrowser = await puppeteer.connect({
browserWSEndpoint: browser.wsEndpoint(), 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 () => { it('should be able to connect to a browser with no page targets', async () => {
const {defaultBrowserOptions, puppeteer} = getTestState(); const {puppeteer, browser, close} = await launch({});
const {browser, close} = await launch(defaultBrowserOptions);
try { try {
const pages = await browser.pages(); const pages = await browser.pages();
@ -701,9 +668,8 @@ describe('Launcher specs', function () {
} }
}); });
it('should support ignoreHTTPSErrors option', async () => { it('should support ignoreHTTPSErrors option', async () => {
const {puppeteer, defaultBrowserOptions} = getTestState(); const {puppeteer, httpsServer, browser, close} = await launch(
const {httpsServer, browser, close} = await launch( {},
defaultBrowserOptions,
{ {
createContext: false, createContext: false,
} }
@ -738,10 +704,8 @@ describe('Launcher specs', function () {
}); });
it('should support targetFilter option in puppeteer.launch', async () => { it('should support targetFilter option in puppeteer.launch', async () => {
const {defaultBrowserOptions} = getTestState();
const {browser, close} = await launch( const {browser, close} = await launch(
{ {
...defaultBrowserOptions,
targetFilter: target => { targetFilter: target => {
return target.type !== 'page'; return target.type !== 'page';
}, },
@ -764,10 +728,12 @@ describe('Launcher specs', function () {
// @see https://github.com/puppeteer/puppeteer/issues/4197 // @see https://github.com/puppeteer/puppeteer/issues/4197
it('should support targetFilter option', async () => { it('should support targetFilter option', async () => {
const {puppeteer, defaultBrowserOptions} = getTestState(); const {puppeteer, server, browser, close} = await launch(
const {server, browser, close} = await launch(defaultBrowserOptions, { {},
createContext: false, {
}); createContext: false,
}
);
try { try {
const browserWSEndpoint = browser.wsEndpoint(); const browserWSEndpoint = browser.wsEndpoint();
const page1 = await browser.newPage(); const page1 = await browser.newPage();
@ -802,8 +768,7 @@ describe('Launcher specs', function () {
} }
}); });
it('should be able to reconnect to a disconnected browser', async () => { it('should be able to reconnect to a disconnected browser', async () => {
const {puppeteer, defaultBrowserOptions} = getTestState(); const {puppeteer, server, browser, close} = await launch({});
const {server, browser, close} = await launch(defaultBrowserOptions);
try { try {
const browserWSEndpoint = browser.wsEndpoint(); const browserWSEndpoint = browser.wsEndpoint();
const page = await browser.newPage(); const page = await browser.newPage();
@ -834,10 +799,7 @@ describe('Launcher specs', function () {
}); });
// @see https://github.com/puppeteer/puppeteer/issues/4197#issuecomment-481793410 // @see https://github.com/puppeteer/puppeteer/issues/4197#issuecomment-481793410
it('should be able to connect to the same page simultaneously', async () => { it('should be able to connect to the same page simultaneously', async () => {
const {puppeteer, defaultBrowserOptions} = getTestState(); const {puppeteer, browser: browserOne, close} = await launch({});
const {browser: browserOne, close} = await launch(
defaultBrowserOptions
);
try { try {
const browserTwo = await puppeteer.connect({ const browserTwo = await puppeteer.connect({
@ -866,12 +828,12 @@ describe('Launcher specs', function () {
} }
}); });
it('should be able to reconnect', async () => { it('should be able to reconnect', async () => {
const {puppeteer, defaultBrowserOptions} = getTestState();
const { const {
puppeteer,
server, server,
browser: browserOne, browser: browserOne,
close, close,
} = await launch(defaultBrowserOptions); } = await launch({});
try { try {
const browserWSEndpoint = browserOne.wsEndpoint(); const browserWSEndpoint = browserOne.wsEndpoint();
const pageOne = await browserOne.newPage(); const pageOne = await browserOne.newPage();
@ -898,14 +860,14 @@ describe('Launcher specs', function () {
}); });
describe('Puppeteer.executablePath', function () { describe('Puppeteer.executablePath', function () {
itOnlyRegularInstall('should work', async () => { itOnlyRegularInstall('should work', async () => {
const {puppeteer} = getTestState(); const {puppeteer} = await getTestState();
const executablePath = puppeteer.executablePath(); const executablePath = puppeteer.executablePath();
expect(fs.existsSync(executablePath)).toBe(true); expect(fs.existsSync(executablePath)).toBe(true);
expect(fs.realpathSync(executablePath)).toBe(executablePath); expect(fs.realpathSync(executablePath)).toBe(executablePath);
}); });
it('returns executablePath for channel', () => { it('returns executablePath for channel', async () => {
const {puppeteer} = getTestState(); const {puppeteer} = await getTestState();
const executablePath = puppeteer.executablePath('chrome'); const executablePath = puppeteer.executablePath('chrome');
expect(executablePath).toBeTruthy(); expect(executablePath).toBeTruthy();
@ -913,8 +875,8 @@ describe('Launcher specs', function () {
describe('when executable path is configured', () => { describe('when executable path is configured', () => {
const sandbox = sinon.createSandbox(); const sandbox = sinon.createSandbox();
beforeEach(() => { beforeEach(async () => {
const {puppeteer} = getTestState(); const {puppeteer} = await getTestState();
sandbox sandbox
.stub(puppeteer.configuration, 'executablePath') .stub(puppeteer.configuration, 'executablePath')
.value('SOME_CUSTOM_EXECUTABLE'); .value('SOME_CUSTOM_EXECUTABLE');
@ -925,7 +887,7 @@ describe('Launcher specs', function () {
}); });
it('its value is used', async () => { it('its value is used', async () => {
const {puppeteer} = getTestState(); const {puppeteer} = await getTestState();
try { try {
puppeteer.executablePath(); puppeteer.executablePath();
} catch (error) { } catch (error) {
@ -940,8 +902,7 @@ describe('Launcher specs', function () {
describe('Browser target events', function () { describe('Browser target events', function () {
it('should work', async () => { it('should work', async () => {
const {defaultBrowserOptions} = getTestState(); const {browser, server, close} = await launch({});
const {browser, server, close} = await launch(defaultBrowserOptions);
try { try {
const events: string[] = []; const events: string[] = [];
@ -966,8 +927,7 @@ describe('Launcher specs', function () {
describe('Browser.Events.disconnected', function () { describe('Browser.Events.disconnected', function () {
it('should be emitted when: browser gets closed, disconnected or underlying websocket gets closed', async () => { it('should be emitted when: browser gets closed, disconnected or underlying websocket gets closed', async () => {
const {puppeteer, defaultBrowserOptions} = getTestState(); const {puppeteer, browser, close} = await launch({});
const {browser, close} = await launch(defaultBrowserOptions);
try { try {
const browserWSEndpoint = browser.wsEndpoint(); const browserWSEndpoint = browser.wsEndpoint();
const remoteBrowser1 = await puppeteer.connect({ const remoteBrowser1 = await puppeteer.connect({

View File

@ -22,18 +22,11 @@ import {
} from 'puppeteer-core/internal/api/Locator.js'; } from 'puppeteer-core/internal/api/Locator.js';
import sinon from 'sinon'; import sinon from 'sinon';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
describe('Locator', function () { describe('Locator', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('should work with a frame', async () => { it('should work with a frame', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.setContent(` await page.setContent(`
@ -56,7 +49,7 @@ describe('Locator', function () {
}); });
it('should work without preconditions', async () => { it('should work without preconditions', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.setContent(` await page.setContent(`
@ -84,7 +77,7 @@ describe('Locator', function () {
describe('Locator.click', function () { describe('Locator.click', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.setContent(` await page.setContent(`
@ -106,7 +99,7 @@ describe('Locator', function () {
}); });
it('should work for multiple selectors', async () => { it('should work for multiple selectors', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.setContent(` await page.setContent(`
@ -128,7 +121,7 @@ describe('Locator', function () {
}); });
it('should work if the element is out of viewport', async () => { 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.setViewport({width: 500, height: 500});
await page.setContent(` await page.setContent(`
@ -143,7 +136,7 @@ describe('Locator', function () {
}); });
it('should work if the element becomes visible later', async () => { 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.setViewport({width: 500, height: 500});
await page.setContent(` await page.setContent(`
@ -176,7 +169,7 @@ describe('Locator', function () {
}); });
it('should work if the element becomes enabled later', async () => { 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.setViewport({width: 500, height: 500});
await page.setContent(` await page.setContent(`
@ -201,7 +194,7 @@ describe('Locator', function () {
}); });
it('should work if multiple conditions are satisfied later', async () => { 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.setViewport({width: 500, height: 500});
await page.setContent(` await page.setContent(`
@ -229,7 +222,7 @@ describe('Locator', function () {
it('should time out', async () => { it('should time out', async () => {
const clock = sinon.useFakeTimers(); const clock = sinon.useFakeTimers();
try { try {
const {page} = getTestState(); const {page} = await getTestState();
page.setDefaultTimeout(5000); page.setDefaultTimeout(5000);
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
@ -247,7 +240,7 @@ describe('Locator', function () {
}); });
it('should retry clicks on errors', async () => { it('should retry clicks on errors', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const clock = sinon.useFakeTimers(); const clock = sinon.useFakeTimers();
try { try {
page.setDefaultTimeout(5000); page.setDefaultTimeout(5000);
@ -266,7 +259,7 @@ describe('Locator', function () {
}); });
it('can be aborted', async () => { it('can be aborted', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const clock = sinon.useFakeTimers(); const clock = sinon.useFakeTimers();
try { try {
page.setDefaultTimeout(5000); page.setDefaultTimeout(5000);
@ -290,7 +283,7 @@ describe('Locator', function () {
describe('Locator.hover', function () { describe('Locator.hover', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.setContent(` await page.setContent(`
@ -314,7 +307,7 @@ describe('Locator', function () {
describe('Locator.scroll', function () { describe('Locator.scroll', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.setContent(` await page.setContent(`
@ -343,7 +336,7 @@ describe('Locator', function () {
describe('Locator.change', function () { describe('Locator.change', function () {
it('should work for selects', async () => { it('should work for selects', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(` await page.setContent(`
<select> <select>
@ -367,7 +360,7 @@ describe('Locator', function () {
}); });
it('should work for inputs', async () => { it('should work for inputs', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(` await page.setContent(`
<input> <input>
`); `);
@ -380,7 +373,7 @@ describe('Locator', function () {
}); });
it('should work if the input becomes enabled later', async () => { it('should work if the input becomes enabled later', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(` await page.setContent(`
<input disabled> <input disabled>
@ -404,7 +397,7 @@ describe('Locator', function () {
}); });
it('should work for contenteditable', async () => { it('should work for contenteditable', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(` await page.setContent(`
<div contenteditable="true"> <div contenteditable="true">
`); `);
@ -417,7 +410,7 @@ describe('Locator', function () {
}); });
it('should work for pre-filled inputs', async () => { it('should work for pre-filled inputs', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(` await page.setContent(`
<input value="te"> <input value="te">
`); `);
@ -430,7 +423,7 @@ describe('Locator', function () {
}); });
it('should override pre-filled inputs', async () => { it('should override pre-filled inputs', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(` await page.setContent(`
<input value="wrong prefix"> <input value="wrong prefix">
`); `);
@ -443,7 +436,7 @@ describe('Locator', function () {
}); });
it('should work for non-text inputs', async () => { it('should work for non-text inputs', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(` await page.setContent(`
<input type="color"> <input type="color">
`); `);
@ -458,7 +451,7 @@ describe('Locator', function () {
describe('Locator.race', () => { describe('Locator.race', () => {
it('races multiple locators', async () => { it('races multiple locators', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.setContent(` await page.setContent(`
@ -480,7 +473,7 @@ describe('Locator', function () {
}); });
it('can be aborted', async () => { it('can be aborted', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const clock = sinon.useFakeTimers(); const clock = sinon.useFakeTimers();
try { try {
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});

View File

@ -39,6 +39,87 @@ import sinon from 'sinon';
import {extendExpectWithToBeGolden} from './utils.js'; 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 setupServer = async () => {
const assetsPath = path.join(__dirname, '../assets'); const assetsPath = path.join(__dirname, '../assets');
const cachedPath = path.join(__dirname, '../assets', 'cached'); const cachedPath = path.join(__dirname, '../assets', 'cached');
@ -62,65 +143,58 @@ const setupServer = async () => {
return {server, httpsServer}; 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; 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 setupGoldenAssertions = (): void => {
const suffix = product.toLowerCase(); const suffix = processVariables.product.toLowerCase();
const GOLDEN_DIR = path.join(__dirname, `../golden-${suffix}`); const GOLDEN_DIR = path.join(__dirname, `../golden-${suffix}`);
const OUTPUT_DIR = path.join(__dirname, `../output-${suffix}`); const OUTPUT_DIR = path.join(__dirname, `../output-${suffix}`);
if (fs.existsSync(OUTPUT_DIR)) { if (fs.existsSync(OUTPUT_DIR)) {
@ -151,7 +225,7 @@ export const itOnlyRegularInstall = (
description: string, description: string,
body: Mocha.AsyncFunc body: Mocha.AsyncFunc
): Mocha.Test => { ): Mocha.Test => {
if (alternativeInstall || process.env['BINARY']) { if (processVariables.alternativeInstall || process.env['BINARY']) {
return it.skip(description, body); return it.skip(description, body);
} else { } else {
return it(description, body); return it(description, body);
@ -164,14 +238,14 @@ if (
) { ) {
console.log( console.log(
`Running unit tests with: `Running unit tests with:
-> product: ${product} -> product: ${processVariables.product}
-> binary: ${ -> binary: ${
defaultBrowserOptions.executablePath || processVariables.defaultBrowserOptions.executablePath ||
path.relative(process.cwd(), puppeteer.executablePath()) path.relative(process.cwd(), puppeteer.executablePath())
} }
-> mode: ${ -> mode: ${
isHeadless processVariables.isHeadless
? headless === 'new' ? processVariables.headless === 'new'
? '--headless=new' ? '--headless=new'
: '--headless' : '--headless'
: 'headful' : 'headful'
@ -183,69 +257,21 @@ process.on('unhandledRejection', reason => {
throw reason; throw reason;
}); });
export const setupTestBrowserHooks = (): void => { const browserNotClosedError = new Error(
before(async () => { 'A manually launched browser was not closed!'
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;
});
};
export const mochaHooks = { export const mochaHooks = {
beforeAll: [ async afterAll(): Promise<void> {
async (): Promise<void> => { await state.browser?.close();
const {server, httpsServer} = await setupServer(); await state.server?.stop();
await state.httpsServer?.stop();
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();
}, },
afterAll: [ async afterEach(): Promise<void> {
async (): Promise<void> => {
await state.server!.stop();
state.server = undefined;
await state.httpsServer!.stop();
state.httpsServer = undefined;
},
],
afterEach: (): void => {
if (browserCleanups.length > 0) { if (browserCleanups.length > 0) {
throw new Error('A manually launched browser was not closed!'); await closeLaunched();
(this as any).test.error(browserNotClosedError);
} }
sinon.restore(); sinon.restore();
}, },
}; };
@ -281,12 +307,11 @@ expect.extend({
}, },
}); });
export const expectCookieEquals = ( export const expectCookieEquals = async (
cookies: Protocol.Network.Cookie[], cookies: Protocol.Network.Cookie[],
expectedCookies: Array<Partial<Protocol.Network.Cookie>> expectedCookies: Array<Partial<Protocol.Network.Cookie>>
): void => { ): Promise<void> => {
const {isChrome} = getTestState(); if (!processVariables.isChrome) {
if (!isChrome) {
// Only keep standard properties when testing on a browser other than Chrome. // Only keep standard properties when testing on a browser other than Chrome.
expectedCookies = expectedCookies.map(cookie => { expectedCookies = expectedCookies.map(cookie => {
return { 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++) { for (let i = 0; i < cookies.length; i++) {
expect(cookies[i]).toMatchObject(expectedCookies[i]!); expect(cookies[i]).toMatchObject(expectedCookies[i]!);
} }
@ -366,6 +391,25 @@ export const createTimeout = <T>(
let browserCleanups: Array<() => Promise<void>> = []; 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 ( export const launch = async (
launchOptions: PuppeteerLaunchOptions, launchOptions: PuppeteerLaunchOptions,
options: { options: {
@ -378,28 +422,13 @@ export const launch = async (
} }
> => { > => {
const {createContext = true, createPage = true} = options; const {createContext = true, createPage = true} = options;
const close = async () => { const initState = await getTestState({
let cleanup = browserCleanups.pop(); skipLaunch: true,
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;
}
};
try { try {
const browser = await puppeteer.launch({ const browser = await puppeteer.launch({
...defaultBrowserOptions, ...initState.defaultBrowserOptions,
...launchOptions, ...launchOptions,
}); });
browserCleanups.push(() => { browserCleanups.push(() => {
@ -423,14 +452,14 @@ export const launch = async (
} }
return { return {
...getTestState(), ...initState,
browser, browser,
context: context!, context: context!,
page: page!, page: page!,
close, close: closeLaunched,
}; };
} catch (error) { } catch (error) {
await close(); await closeLaunched();
throw error; 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 {Page} from 'puppeteer-core/internal/api/Page.js';
import {KeyInput} from 'puppeteer-core/internal/common/USKeyboardLayout.js'; import {KeyInput} from 'puppeteer-core/internal/common/USKeyboardLayout.js';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
interface ClickData { interface ClickData {
type: string; type: string;
@ -54,10 +50,8 @@ function dimensions(): Dimensions {
} }
describe('Mouse', function () { describe('Mouse', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('should click the document', async () => { it('should click the document', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.evaluate(() => { await page.evaluate(() => {
(globalThis as any).clickPromise = new Promise(resolve => { (globalThis as any).clickPromise = new Promise(resolve => {
@ -85,7 +79,7 @@ describe('Mouse', function () {
expect(event.button).toBe(0); expect(event.button).toBe(0);
}); });
it('should resize the textarea', async () => { it('should resize the textarea', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/textarea.html'); await page.goto(server.PREFIX + '/input/textarea.html');
const {x, y, width, height} = await page.evaluate(dimensions); const {x, y, width, height} = await page.evaluate(dimensions);
@ -99,7 +93,7 @@ describe('Mouse', function () {
expect(newDimensions.height).toBe(Math.round(height + 104)); expect(newDimensions.height).toBe(Math.round(height + 104));
}); });
it('should select the text with mouse', async () => { 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.goto(server.PREFIX + '/input/textarea.html');
await page.focus('textarea'); await page.focus('textarea');
@ -129,7 +123,7 @@ describe('Mouse', function () {
).toBe(text); ).toBe(text);
}); });
it('should trigger hover state', async () => { 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.goto(server.PREFIX + '/input/scrollable.html');
await page.hover('#button-6'); await page.hover('#button-6');
@ -152,7 +146,7 @@ describe('Mouse', function () {
).toBe('button-91'); ).toBe('button-91');
}); });
it('should trigger hover state with removed window.Node', async () => { 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.goto(server.PREFIX + '/input/scrollable.html');
await page.evaluate(() => { await page.evaluate(() => {
@ -167,7 +161,7 @@ describe('Mouse', function () {
).toBe('button-6'); ).toBe('button-6');
}); });
it('should set modifier keys on click', async () => { 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.goto(server.PREFIX + '/input/scrollable.html');
await page.evaluate(() => { await page.evaluate(() => {
@ -213,7 +207,7 @@ describe('Mouse', function () {
} }
}); });
it('should send mouse wheel events', async () => { it('should send mouse wheel events', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/input/wheel.html'); await page.goto(server.PREFIX + '/input/wheel.html');
const elem = (await page.$('div'))!; const elem = (await page.$('div'))!;
@ -236,7 +230,7 @@ describe('Mouse', function () {
}); });
}); });
it('should tween mouse movement', async () => { it('should tween mouse movement', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.mouse.move(100, 100); await page.mouse.move(100, 100);
await page.evaluate(() => { await page.evaluate(() => {
@ -256,7 +250,7 @@ describe('Mouse', function () {
}); });
// @see https://crbug.com/929806 // @see https://crbug.com/929806
it('should work with mobile viewports and cross process navigations', async () => { 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.goto(server.EMPTY_PAGE);
await page.setViewport({width: 360, height: 640, isMobile: true}); 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}); expect(await page.evaluate('result')).toEqual({x: 30, y: 40});
}); });
it('should throw if buttons are pressed incorrectly', async () => { it('should throw if buttons are pressed incorrectly', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -312,7 +306,7 @@ describe('Mouse', function () {
}; };
it('should not throw if clicking in parallel', async () => { 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 page.goto(server.EMPTY_PAGE);
await addMouseDataListeners(page); await addMouseDataListeners(page);
@ -370,7 +364,7 @@ describe('Mouse', function () {
}); });
it('should reset properly', async () => { it('should reset properly', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);

View File

@ -20,26 +20,19 @@ import expect from 'expect';
import {Frame, TimeoutError} from 'puppeteer'; import {Frame, TimeoutError} from 'puppeteer';
import {HTTPRequest} from 'puppeteer-core/internal/api/HTTPRequest.js'; import {HTTPRequest} from 'puppeteer-core/internal/api/HTTPRequest.js';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {attachFrame, isFavicon, waitEvent} from './utils.js'; import {attachFrame, isFavicon, waitEvent} from './utils.js';
describe('navigation', function () { describe('navigation', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Page.goto', function () { describe('Page.goto', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
expect(page.url()).toBe(server.EMPTY_PAGE); expect(page.url()).toBe(server.EMPTY_PAGE);
}); });
it('should work with anchor navigation', async () => { it('should work with anchor navigation', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
expect(page.url()).toBe(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'); expect(page.url()).toBe(server.EMPTY_PAGE + '#bar');
}); });
it('should work with redirects', async () => { 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/1.html', '/redirect/2.html');
server.setRedirect('/redirect/2.html', '/empty.html'); server.setRedirect('/redirect/2.html', '/empty.html');
@ -57,19 +50,19 @@ describe('navigation', function () {
expect(page.url()).toBe(server.EMPTY_PAGE); expect(page.url()).toBe(server.EMPTY_PAGE);
}); });
it('should navigate to about:blank', async () => { it('should navigate to about:blank', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const response = await page.goto('about:blank'); const response = await page.goto('about:blank');
expect(response).toBe(null); expect(response).toBe(null);
}); });
it('should return response when page changes its URL after load', async () => { 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'); const response = await page.goto(server.PREFIX + '/historyapi.html');
expect(response!.status()).toBe(200); expect(response!.status()).toBe(200);
}); });
it('should work with subframes return 204', async () => { it('should work with subframes return 204', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.setRoute('/frames/frame.html', (_req, res) => { server.setRoute('/frames/frame.html', (_req, res) => {
res.statusCode = 204; res.statusCode = 204;
@ -84,7 +77,7 @@ describe('navigation', function () {
expect(error).toBeUndefined(); expect(error).toBeUndefined();
}); });
it('should fail when server returns 204', async () => { 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) => { server.setRoute('/empty.html', (_req, res) => {
res.statusCode = 204; res.statusCode = 204;
@ -102,7 +95,7 @@ describe('navigation', function () {
} }
}); });
it('should navigate to empty page with domcontentloaded', async () => { 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, { const response = await page.goto(server.EMPTY_PAGE, {
waitUntil: 'domcontentloaded', waitUntil: 'domcontentloaded',
@ -110,7 +103,7 @@ describe('navigation', function () {
expect(response!.status()).toBe(200); expect(response!.status()).toBe(200);
}); });
it('should work when page calls history API in beforeunload', async () => { 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.goto(server.EMPTY_PAGE);
await page.evaluate(() => { await page.evaluate(() => {
@ -126,7 +119,7 @@ describe('navigation', function () {
expect(response!.status()).toBe(200); expect(response!.status()).toBe(200);
}); });
it('should navigate to empty page with networkidle0', async () => { 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, { const response = await page.goto(server.EMPTY_PAGE, {
waitUntil: 'networkidle0', waitUntil: 'networkidle0',
@ -134,7 +127,7 @@ describe('navigation', function () {
expect(response!.status()).toBe(200); expect(response!.status()).toBe(200);
}); });
it('should navigate to empty page with networkidle2', async () => { 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, { const response = await page.goto(server.EMPTY_PAGE, {
waitUntil: 'networkidle2', waitUntil: 'networkidle2',
@ -142,7 +135,7 @@ describe('navigation', function () {
expect(response!.status()).toBe(200); expect(response!.status()).toBe(200);
}); });
it('should fail when navigating to bad url', async () => { it('should fail when navigating to bad url', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page.goto('asdfasdf').catch(error_ => { await page.goto('asdfasdf').catch(error_ => {
@ -159,7 +152,7 @@ describe('navigation', function () {
/net::ERR_CERT_INVALID|net::ERR_CERT_AUTHORITY_INVALID/; /net::ERR_CERT_INVALID|net::ERR_CERT_AUTHORITY_INVALID/;
it('should fail when navigating to bad SSL', async () => { 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'. // Make sure that network events do not emit 'undefined'.
// @see https://crbug.com/750469 // @see https://crbug.com/750469
@ -189,7 +182,7 @@ describe('navigation', function () {
expect(requests[1]).toBe('requestfailed'); expect(requests[1]).toBe('requestfailed');
}); });
it('should fail when navigating to bad SSL after redirects', async () => { 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/1.html', '/redirect/2.html');
server.setRedirect('/redirect/2.html', '/empty.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 () => { it('should fail when main resources failed to load', async () => {
const {page, isChrome} = getTestState(); const {page, isChrome} = await getTestState();
let error!: Error; let error!: Error;
await page await page
@ -222,7 +215,7 @@ describe('navigation', function () {
} }
}); });
it('should fail when exceeding maximum navigation timeout', async () => { 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 // Hang for request to the empty.html
server.setRoute('/empty.html', () => {}); server.setRoute('/empty.html', () => {});
@ -236,7 +229,7 @@ describe('navigation', function () {
expect(error).toBeInstanceOf(TimeoutError); expect(error).toBeInstanceOf(TimeoutError);
}); });
it('should fail when exceeding default maximum navigation timeout', async () => { 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 // Hang for request to the empty.html
server.setRoute('/empty.html', () => {}); server.setRoute('/empty.html', () => {});
@ -249,7 +242,7 @@ describe('navigation', function () {
expect(error).toBeInstanceOf(TimeoutError); expect(error).toBeInstanceOf(TimeoutError);
}); });
it('should fail when exceeding default maximum timeout', async () => { 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 // Hang for request to the empty.html
server.setRoute('/empty.html', () => {}); server.setRoute('/empty.html', () => {});
@ -262,7 +255,7 @@ describe('navigation', function () {
expect(error).toBeInstanceOf(TimeoutError); expect(error).toBeInstanceOf(TimeoutError);
}); });
it('should prioritize default navigation timeout over default timeout', async () => { 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 // Hang for request to the empty.html
server.setRoute('/empty.html', () => {}); server.setRoute('/empty.html', () => {});
@ -276,7 +269,7 @@ describe('navigation', function () {
expect(error).toBeInstanceOf(TimeoutError); expect(error).toBeInstanceOf(TimeoutError);
}); });
it('should disable timeout when its set to 0', async () => { it('should disable timeout when its set to 0', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
let error!: Error; let error!: Error;
let loaded = false; let loaded = false;
@ -292,26 +285,26 @@ describe('navigation', function () {
expect(loaded).toBe(true); expect(loaded).toBe(true);
}); });
it('should work when navigating to valid url', async () => { 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))!; const response = (await page.goto(server.EMPTY_PAGE))!;
expect(response.ok()).toBe(true); expect(response.ok()).toBe(true);
}); });
it('should work when navigating to data url', async () => { 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'))!; const response = (await page.goto('data:text/html,hello'))!;
expect(response.ok()).toBe(true); expect(response.ok()).toBe(true);
}); });
it('should work when navigating to 404', async () => { 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'))!; const response = (await page.goto(server.PREFIX + '/not-found'))!;
expect(response.ok()).toBe(false); expect(response.ok()).toBe(false);
expect(response.status()).toBe(404); expect(response.status()).toBe(404);
}); });
it('should not throw an error for a 404 response with an empty body', async () => { 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) => { server.setRoute('/404-error', (_, res) => {
res.statusCode = 404; res.statusCode = 404;
@ -323,7 +316,7 @@ describe('navigation', function () {
expect(response.status()).toBe(404); expect(response.status()).toBe(404);
}); });
it('should not throw an error for a 500 response with an empty body', async () => { 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) => { server.setRoute('/500-error', (_, res) => {
res.statusCode = 500; res.statusCode = 500;
@ -335,7 +328,7 @@ describe('navigation', function () {
expect(response.status()).toBe(500); expect(response.status()).toBe(500);
}); });
it('should return last response in redirect chain', async () => { 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/1.html', '/redirect/2.html');
server.setRedirect('/redirect/2.html', '/redirect/3.html'); server.setRedirect('/redirect/2.html', '/redirect/3.html');
@ -345,7 +338,7 @@ describe('navigation', function () {
expect(response.url()).toBe(server.EMPTY_PAGE); expect(response.url()).toBe(server.EMPTY_PAGE);
}); });
it('should wait for network idle to succeed navigation', async () => { it('should wait for network idle to succeed navigation', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
let responses: ServerResponse[] = []; let responses: ServerResponse[] = [];
// Hold on to a bunch of requests without answering. // 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 () { it('should not leak listeners during navigation', async function () {
this.timeout(25_000); this.timeout(25_000);
const {page, server} = getTestState(); const {page, server} = await getTestState();
let warning = null; let warning = null;
const warningHandler: NodeJS.WarningListener = w => { const warningHandler: NodeJS.WarningListener = w => {
@ -458,7 +451,7 @@ describe('navigation', function () {
it('should not leak listeners during bad navigation', async function () { it('should not leak listeners during bad navigation', async function () {
this.timeout(25_000); this.timeout(25_000);
const {page} = getTestState(); const {page} = await getTestState();
let warning = null; let warning = null;
const warningHandler: NodeJS.WarningListener = w => { const warningHandler: NodeJS.WarningListener = w => {
@ -476,7 +469,7 @@ describe('navigation', function () {
it('should not leak listeners during navigation of 11 pages', async function () { it('should not leak listeners during navigation of 11 pages', async function () {
this.timeout(25_000); this.timeout(25_000);
const {context, server} = getTestState(); const {context, server} = await getTestState();
let warning = null; let warning = null;
const warningHandler: NodeJS.WarningListener = w => { const warningHandler: NodeJS.WarningListener = w => {
@ -494,7 +487,7 @@ describe('navigation', function () {
expect(warning).toBe(null); expect(warning).toBe(null);
}); });
it('should navigate to dataURL and fire dataURL requests', async () => { it('should navigate to dataURL and fire dataURL requests', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', request => { page.on('request', request => {
@ -507,7 +500,7 @@ describe('navigation', function () {
expect(requests[0]!.url()).toBe(dataURL); expect(requests[0]!.url()).toBe(dataURL);
}); });
it('should navigate to URL with hash and fire requests without hash', async () => { 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[] = []; const requests: HTTPRequest[] = [];
page.on('request', request => { page.on('request', request => {
@ -520,14 +513,14 @@ describe('navigation', function () {
expect(requests[0]!.url()).toBe(server.EMPTY_PAGE); expect(requests[0]!.url()).toBe(server.EMPTY_PAGE);
}); });
it('should work with self requesting page', async () => { 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'))!; const response = (await page.goto(server.PREFIX + '/self-request.html'))!;
expect(response.status()).toBe(200); expect(response.status()).toBe(200);
expect(response.url()).toContain('self-request.html'); expect(response.url()).toContain('self-request.html');
}); });
it('should fail when navigating and show the url at the error message', async () => { 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'; const url = httpsServer.PREFIX + '/redirect/1.html';
let error!: Error; let error!: Error;
@ -539,7 +532,7 @@ describe('navigation', function () {
expect(error.message).toContain(url); expect(error.message).toContain(url);
}); });
it('should send referer', async () => { it('should send referer', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const requests = Promise.all([ const requests = Promise.all([
server.waitForRequest('/grid.html'), server.waitForRequest('/grid.html'),
@ -558,7 +551,7 @@ describe('navigation', function () {
}); });
it('should send referer policy', async () => { it('should send referer policy', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const [request1, request2] = await Promise.all([ const [request1, request2] = await Promise.all([
server.waitForRequest('/grid.html'), server.waitForRequest('/grid.html'),
@ -576,7 +569,7 @@ describe('navigation', function () {
describe('Page.waitForNavigation', function () { describe('Page.waitForNavigation', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const [response] = await Promise.all([ const [response] = await Promise.all([
@ -589,7 +582,7 @@ describe('navigation', function () {
expect(response!.url()).toContain('grid.html'); expect(response!.url()).toContain('grid.html');
}); });
it('should work with both domcontentloaded and load', async () => { it('should work with both domcontentloaded and load', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
let response!: ServerResponse; let response!: ServerResponse;
server.setRoute('/one-style.css', (_req, res) => { server.setRoute('/one-style.css', (_req, res) => {
@ -630,7 +623,7 @@ describe('navigation', function () {
expect(error).toBeUndefined(); expect(error).toBeUndefined();
}); });
it('should work with clicking on anchor links', async () => { 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.goto(server.EMPTY_PAGE);
await page.setContent(`<a href='#foobar'>foobar</a>`); await page.setContent(`<a href='#foobar'>foobar</a>`);
@ -642,7 +635,7 @@ describe('navigation', function () {
expect(page.url()).toBe(server.EMPTY_PAGE + '#foobar'); expect(page.url()).toBe(server.EMPTY_PAGE + '#foobar');
}); });
it('should work with history.pushState()', async () => { it('should work with history.pushState()', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setContent(` await page.setContent(`
@ -659,7 +652,7 @@ describe('navigation', function () {
expect(page.url()).toBe(server.PREFIX + '/wow.html'); expect(page.url()).toBe(server.PREFIX + '/wow.html');
}); });
it('should work with history.replaceState()', async () => { it('should work with history.replaceState()', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setContent(` await page.setContent(`
@ -676,7 +669,7 @@ describe('navigation', function () {
expect(page.url()).toBe(server.PREFIX + '/replaced.html'); expect(page.url()).toBe(server.PREFIX + '/replaced.html');
}); });
it('should work with DOM history.back()/history.forward()', async () => { 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.goto(server.EMPTY_PAGE);
await page.setContent(` await page.setContent(`
@ -704,7 +697,7 @@ describe('navigation', function () {
expect(page.url()).toBe(server.PREFIX + '/second.html'); expect(page.url()).toBe(server.PREFIX + '/second.html');
}); });
it('should work when subframe issues window.stop()', async function () { it('should work when subframe issues window.stop()', async function () {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.setRoute('/frames/style.css', () => {}); server.setRoute('/frames/style.css', () => {});
let frame: Frame | undefined; let frame: Frame | undefined;
@ -745,7 +738,7 @@ describe('navigation', function () {
describe('Page.goBack', function () { describe('Page.goBack', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.goto(server.PREFIX + '/grid.html'); await page.goto(server.PREFIX + '/grid.html');
@ -762,7 +755,7 @@ describe('navigation', function () {
expect(response).toBe(null); expect(response).toBe(null);
}); });
it('should work with HistoryAPI', async () => { it('should work with HistoryAPI', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => { await page.evaluate(() => {
@ -782,7 +775,7 @@ describe('navigation', function () {
describe('Frame.goto', function () { describe('Frame.goto', function () {
it('should navigate subframes', async () => { it('should navigate subframes', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/frames/one-frame.html'); await page.goto(server.PREFIX + '/frames/one-frame.html');
expect(page.frames()[0]!.url()).toContain('/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]); expect(response.frame()).toBe(page.frames()[1]);
}); });
it('should reject when frame detaches', async () => { 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'); await page.goto(server.PREFIX + '/frames/one-frame.html');
@ -813,7 +806,7 @@ describe('navigation', function () {
expect(error.message).toBe('Navigating frame was detached'); expect(error.message).toBe('Navigating frame was detached');
}); });
it('should return matching responses', async () => { it('should return matching responses', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
// Disable cache: otherwise, the browser will cache similar requests. // Disable cache: otherwise, the browser will cache similar requests.
await page.setCacheEnabled(false); await page.setCacheEnabled(false);
@ -847,7 +840,7 @@ describe('navigation', function () {
describe('Frame.waitForNavigation', function () { describe('Frame.waitForNavigation', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/frames/one-frame.html'); await page.goto(server.PREFIX + '/frames/one-frame.html');
const frame = page.frames()[1]!; const frame = page.frames()[1]!;
@ -863,7 +856,7 @@ describe('navigation', function () {
expect(page.url()).toContain('/frames/one-frame.html'); expect(page.url()).toContain('/frames/one-frame.html');
}); });
it('should fail when frame detaches', async () => { 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'); await page.goto(server.PREFIX + '/frames/one-frame.html');
const frame = page.frames()[1]!; const frame = page.frames()[1]!;
@ -892,7 +885,7 @@ describe('navigation', function () {
describe('Page.reload', function () { describe('Page.reload', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => { await page.evaluate(() => {

View File

@ -22,21 +22,13 @@ import expect from 'expect';
import {HTTPRequest} from 'puppeteer-core/internal/api/HTTPRequest.js'; import {HTTPRequest} from 'puppeteer-core/internal/api/HTTPRequest.js';
import {HTTPResponse} from 'puppeteer-core/internal/api/HTTPResponse.js'; import {HTTPResponse} from 'puppeteer-core/internal/api/HTTPResponse.js';
import { import {getTestState, launch} from './mocha-utils.js';
getTestState,
launch,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {attachFrame, isFavicon, waitEvent} from './utils.js'; import {attachFrame, isFavicon, waitEvent} from './utils.js';
describe('network', function () { describe('network', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Page.Events.Request', function () { describe('Page.Events.Request', function () {
it('should fire for navigation requests', async () => { it('should fire for navigation requests', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', request => { page.on('request', request => {
@ -46,7 +38,7 @@ describe('network', function () {
expect(requests).toHaveLength(1); expect(requests).toHaveLength(1);
}); });
it('should fire for iframes', async () => { it('should fire for iframes', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', request => { page.on('request', request => {
@ -57,7 +49,7 @@ describe('network', function () {
expect(requests).toHaveLength(2); expect(requests).toHaveLength(2);
}); });
it('should fire for fetches', async () => { it('should fire for fetches', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', request => { page.on('request', request => {
@ -72,7 +64,7 @@ describe('network', function () {
}); });
describe('Request.frame', function () { describe('Request.frame', function () {
it('should work for main frame navigation request', async () => { it('should work for main frame navigation request', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', request => { page.on('request', request => {
@ -83,7 +75,7 @@ describe('network', function () {
expect(requests[0]!.frame()).toBe(page.mainFrame()); expect(requests[0]!.frame()).toBe(page.mainFrame());
}); });
it('should work for subframe navigation request', async () => { it('should work for subframe navigation request', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
@ -95,7 +87,7 @@ describe('network', function () {
expect(requests[0]!.frame()).toBe(page.frames()[1]); expect(requests[0]!.frame()).toBe(page.frames()[1]);
}); });
it('should work for fetch requests', async () => { it('should work for fetch requests', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
let requests: HTTPRequest[] = []; let requests: HTTPRequest[] = [];
@ -115,13 +107,13 @@ describe('network', function () {
describe('Request.headers', function () { describe('Request.headers', function () {
it('should define Chrome as user agent header', async () => { 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))!; const response = (await page.goto(server.EMPTY_PAGE))!;
expect(response.request().headers()['user-agent']).toContain('Chrome'); expect(response.request().headers()['user-agent']).toContain('Chrome');
}); });
it('should define Firefox as user agent header', async () => { 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))!; const response = (await page.goto(server.EMPTY_PAGE))!;
expect(response.request().headers()['user-agent']).toContain('Firefox'); expect(response.request().headers()['user-agent']).toContain('Firefox');
@ -130,7 +122,7 @@ describe('network', function () {
describe('Response.headers', function () { describe('Response.headers', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.setRoute('/empty.html', (_req, res) => { server.setRoute('/empty.html', (_req, res) => {
res.setHeader('foo', 'bar'); res.setHeader('foo', 'bar');
@ -143,7 +135,7 @@ describe('network', function () {
describe('Request.initiator', () => { describe('Request.initiator', () => {
it('should return the initiator', async () => { it('should return the initiator', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const initiators = new Map(); const initiators = new Map();
page.on('request', request => { page.on('request', request => {
@ -188,14 +180,14 @@ describe('network', function () {
describe('Response.fromCache', function () { describe('Response.fromCache', function () {
it('should return |false| for non-cached content', async () => { 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))!; const response = (await page.goto(server.EMPTY_PAGE))!;
expect(response.fromCache()).toBe(false); expect(response.fromCache()).toBe(false);
}); });
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const responses = new Map(); const responses = new Map();
page.on('response', r => { page.on('response', r => {
@ -218,14 +210,14 @@ describe('network', function () {
describe('Response.fromServiceWorker', function () { describe('Response.fromServiceWorker', function () {
it('should return |false| for non-service-worker content', async () => { 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))!; const response = (await page.goto(server.EMPTY_PAGE))!;
expect(response.fromServiceWorker()).toBe(false); expect(response.fromServiceWorker()).toBe(false);
}); });
it('Response.fromServiceWorker', async () => { it('Response.fromServiceWorker', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const responses = new Map(); const responses = new Map();
page.on('response', r => { page.on('response', r => {
@ -251,7 +243,7 @@ describe('network', function () {
describe('Request.postData', function () { describe('Request.postData', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
server.setRoute('/post', (_req, res) => { server.setRoute('/post', (_req, res) => {
@ -274,7 +266,7 @@ describe('network', function () {
expect(request.postData()).toBe('{"foo":"bar"}'); expect(request.postData()).toBe('{"foo":"bar"}');
}); });
it('should be |undefined| when there is no post data', async () => { 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))!; const response = (await page.goto(server.EMPTY_PAGE))!;
expect(response.request().postData()).toBe(undefined); expect(response.request().postData()).toBe(undefined);
@ -283,14 +275,14 @@ describe('network', function () {
describe('Response.text', function () { describe('Response.text', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const response = (await page.goto(server.PREFIX + '/simple.json'))!; const response = (await page.goto(server.PREFIX + '/simple.json'))!;
const responseText = (await response.text()).trimEnd(); const responseText = (await response.text()).trimEnd();
expect(responseText).toBe('{"foo": "bar"}'); expect(responseText).toBe('{"foo": "bar"}');
}); });
it('should return uncompressed text', async () => { it('should return uncompressed text', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.enableGzip('/simple.json'); server.enableGzip('/simple.json');
const response = (await page.goto(server.PREFIX + '/simple.json'))!; const response = (await page.goto(server.PREFIX + '/simple.json'))!;
@ -299,7 +291,7 @@ describe('network', function () {
expect(responseText).toBe('{"foo": "bar"}'); expect(responseText).toBe('{"foo": "bar"}');
}); });
it('should throw when requesting body of redirected response', async () => { 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'); server.setRedirect('/foo.html', '/empty.html');
const response = (await page.goto(server.PREFIX + '/foo.html'))!; const response = (await page.goto(server.PREFIX + '/foo.html'))!;
@ -316,7 +308,7 @@ describe('network', function () {
); );
}); });
it('should wait until response completes', async () => { it('should wait until response completes', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
// Setup server to trap request. // Setup server to trap request.
@ -366,7 +358,7 @@ describe('network', function () {
describe('Response.json', function () { describe('Response.json', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const response = (await page.goto(server.PREFIX + '/simple.json'))!; const response = (await page.goto(server.PREFIX + '/simple.json'))!;
expect(await response.json()).toEqual({foo: 'bar'}); expect(await response.json()).toEqual({foo: 'bar'});
@ -375,7 +367,7 @@ describe('network', function () {
describe('Response.buffer', function () { describe('Response.buffer', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const response = (await page.goto(server.PREFIX + '/pptr.png'))!; const response = (await page.goto(server.PREFIX + '/pptr.png'))!;
const imageBuffer = fs.readFileSync( const imageBuffer = fs.readFileSync(
@ -385,7 +377,7 @@ describe('network', function () {
expect(responseBuffer.equals(imageBuffer)).toBe(true); expect(responseBuffer.equals(imageBuffer)).toBe(true);
}); });
it('should work with compression', async () => { it('should work with compression', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.enableGzip('/pptr.png'); server.enableGzip('/pptr.png');
const response = (await page.goto(server.PREFIX + '/pptr.png'))!; const response = (await page.goto(server.PREFIX + '/pptr.png'))!;
@ -396,7 +388,7 @@ describe('network', function () {
expect(responseBuffer.equals(imageBuffer)).toBe(true); expect(responseBuffer.equals(imageBuffer)).toBe(true);
}); });
it('should throw if the response does not have a body', async () => { 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'); await page.goto(server.PREFIX + '/empty.html');
@ -435,7 +427,7 @@ describe('network', function () {
describe('Response.statusText', function () { describe('Response.statusText', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.setRoute('/cool', (_req, res) => { server.setRoute('/cool', (_req, res) => {
res.writeHead(200, 'cool!'); res.writeHead(200, 'cool!');
@ -446,7 +438,7 @@ describe('network', function () {
}); });
it('handles missing status text', async () => { it('handles missing status text', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.setRoute('/nostatus', (_req, res) => { server.setRoute('/nostatus', (_req, res) => {
res.writeHead(200, ''); res.writeHead(200, '');
@ -459,7 +451,7 @@ describe('network', function () {
describe('Response.timing', function () { describe('Response.timing', function () {
it('returns timing information', async () => { it('returns timing information', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const responses: HTTPResponse[] = []; const responses: HTTPResponse[] = [];
page.on('response', response => { page.on('response', response => {
return responses.push(response); return responses.push(response);
@ -472,7 +464,7 @@ describe('network', function () {
describe('Network Events', function () { describe('Network Events', function () {
it('Page.Events.Request', async () => { it('Page.Events.Request', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', request => { page.on('request', request => {
@ -488,7 +480,7 @@ describe('network', function () {
expect(requests[0]!.frame()!.url()).toBe(server.EMPTY_PAGE); expect(requests[0]!.frame()!.url()).toBe(server.EMPTY_PAGE);
}); });
it('Page.Events.RequestServedFromCache', async () => { it('Page.Events.RequestServedFromCache', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const cached: string[] = []; const cached: string[] = [];
page.on('requestservedfromcache', r => { page.on('requestservedfromcache', r => {
@ -502,7 +494,7 @@ describe('network', function () {
expect(cached).toEqual(['one-style.css']); expect(cached).toEqual(['one-style.css']);
}); });
it('Page.Events.Response', async () => { it('Page.Events.Response', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const responses: HTTPResponse[] = []; const responses: HTTPResponse[] = [];
page.on('response', response => { page.on('response', response => {
@ -523,7 +515,7 @@ describe('network', function () {
}); });
it('Page.Events.RequestFailed', async () => { it('Page.Events.RequestFailed', async () => {
const {page, server, isChrome} = getTestState(); const {page, server, isChrome} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -552,7 +544,7 @@ describe('network', function () {
expect(failedRequests[0]!.frame()).toBeTruthy(); expect(failedRequests[0]!.frame()).toBeTruthy();
}); });
it('Page.Events.RequestFinished', async () => { it('Page.Events.RequestFinished', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('requestfinished', request => { page.on('requestfinished', request => {
@ -567,7 +559,7 @@ describe('network', function () {
expect(request.frame()!.url()).toBe(server.EMPTY_PAGE); expect(request.frame()!.url()).toBe(server.EMPTY_PAGE);
}); });
it('should fire events in proper order', async () => { it('should fire events in proper order', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const events: string[] = []; const events: string[] = [];
page.on('request', () => { page.on('request', () => {
@ -588,7 +580,7 @@ describe('network', function () {
]); ]);
}); });
it('should support redirects', async () => { it('should support redirects', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const events: string[] = []; const events: string[] = [];
page.on('request', request => { page.on('request', request => {
@ -627,7 +619,7 @@ describe('network', function () {
describe('Request.isNavigationRequest', () => { describe('Request.isNavigationRequest', () => {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const requests = new Map(); const requests = new Map();
page.on('request', request => { page.on('request', request => {
@ -642,7 +634,7 @@ describe('network', function () {
expect(requests.get('style.css').isNavigationRequest()).toBe(false); expect(requests.get('style.css').isNavigationRequest()).toBe(false);
}); });
it('should work with request interception', async () => { it('should work with request interception', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const requests = new Map(); const requests = new Map();
page.on('request', request => { page.on('request', request => {
@ -659,7 +651,7 @@ describe('network', function () {
expect(requests.get('style.css').isNavigationRequest()).toBe(false); expect(requests.get('style.css').isNavigationRequest()).toBe(false);
}); });
it('should work when navigating to image', async () => { it('should work when navigating to image', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const [request] = await Promise.all([ const [request] = await Promise.all([
waitEvent<HTTPRequest>(page, 'request'), waitEvent<HTTPRequest>(page, 'request'),
@ -671,7 +663,7 @@ describe('network', function () {
describe('Page.setExtraHTTPHeaders', function () { describe('Page.setExtraHTTPHeaders', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setExtraHTTPHeaders({ await page.setExtraHTTPHeaders({
foo: 'bar', foo: 'bar',
@ -683,7 +675,7 @@ describe('network', function () {
expect(request.headers['foo']).toBe('bar'); expect(request.headers['foo']).toBe('bar');
}); });
it('should throw for non-string header values', async () => { it('should throw for non-string header values', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
try { try {
@ -700,7 +692,7 @@ describe('network', function () {
describe('Page.authenticate', function () { describe('Page.authenticate', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.setAuth('/empty.html', 'user', 'pass'); server.setAuth('/empty.html', 'user', 'pass');
let response; let response;
@ -725,7 +717,7 @@ describe('network', function () {
expect(response.status()).toBe(200); expect(response.status()).toBe(200);
}); });
it('should fail if wrong credentials', async () => { 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. // Use unique user/password since Chrome caches credentials per origin.
server.setAuth('/empty.html', 'user2', 'pass2'); server.setAuth('/empty.html', 'user2', 'pass2');
@ -737,7 +729,7 @@ describe('network', function () {
expect(response.status()).toBe(401); expect(response.status()).toBe(401);
}); });
it('should allow disable authentication', async () => { 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. // Use unique user/password since Chrome caches credentials per origin.
server.setAuth('/empty.html', 'user3', 'pass3'); server.setAuth('/empty.html', 'user3', 'pass3');
@ -769,7 +761,7 @@ describe('network', function () {
} }
}); });
it('should not disable caching', async () => { 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. // Use unique user/password since Chrome caches credentials per origin.
server.setAuth('/cached/one-style.css', 'user4', 'pass4'); server.setAuth('/cached/one-style.css', 'user4', 'pass4');
@ -797,7 +789,7 @@ describe('network', function () {
describe('raw network headers', () => { describe('raw network headers', () => {
it('Same-origin set-cookie navigation', async () => { it('Same-origin set-cookie navigation', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const setCookieString = 'foo=bar'; const setCookieString = 'foo=bar';
server.setRoute('/empty.html', (_req, res) => { server.setRoute('/empty.html', (_req, res) => {
@ -809,7 +801,7 @@ describe('network', function () {
}); });
it('Same-origin set-cookie subresource', async () => { it('Same-origin set-cookie subresource', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const setCookieString = 'foo=bar'; const setCookieString = 'foo=bar';
@ -865,7 +857,7 @@ describe('network', function () {
describe('Page.setBypassServiceWorker', () => { describe('Page.setBypassServiceWorker', () => {
it('bypass for network', async () => { it('bypass for network', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const responses = new Map(); const responses = new Map();
page.on('response', r => { page.on('response', r => {

View File

@ -29,7 +29,7 @@ describeWithDebugLogs('OOPIF', function () {
let page: Page; let page: Page;
before(async () => { before(async () => {
const {puppeteer, defaultBrowserOptions} = getTestState(); const {puppeteer, defaultBrowserOptions} = await getTestState();
// eslint-disable-next-line no-restricted-syntax // eslint-disable-next-line no-restricted-syntax
browser = await puppeteer.launch( browser = await puppeteer.launch(
Object.assign({}, defaultBrowserOptions, { Object.assign({}, defaultBrowserOptions, {
@ -56,7 +56,7 @@ describeWithDebugLogs('OOPIF', function () {
}); });
it('should treat OOP iframes and normal iframes the same', async () => { it('should treat OOP iframes and normal iframes the same', async () => {
const {server} = getTestState(); const {server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame(frame => { const framePromise = page.waitForFrame(frame => {
@ -72,7 +72,7 @@ describeWithDebugLogs('OOPIF', function () {
expect(page.mainFrame().childFrames()).toHaveLength(2); expect(page.mainFrame().childFrames()).toHaveLength(2);
}); });
it('should track navigations within OOP iframes', async () => { it('should track navigations within OOP iframes', async () => {
const {server} = getTestState(); const {server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame(frame => { const framePromise = page.waitForFrame(frame => {
@ -93,7 +93,7 @@ describeWithDebugLogs('OOPIF', function () {
expect(frame.url()).toContain('/assets/frame.html'); expect(frame.url()).toContain('/assets/frame.html');
}); });
it('should support OOP iframes becoming normal iframes again', async () => { it('should support OOP iframes becoming normal iframes again', async () => {
const {server} = getTestState(); const {server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame(frame => { const framePromise = page.waitForFrame(frame => {
@ -114,7 +114,7 @@ describeWithDebugLogs('OOPIF', function () {
expect(page.frames()).toHaveLength(2); expect(page.frames()).toHaveLength(2);
}); });
it('should support frames within OOP frames', async () => { it('should support frames within OOP frames', async () => {
const {server} = getTestState(); const {server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const frame1Promise = page.waitForFrame(frame => { const frame1Promise = page.waitForFrame(frame => {
@ -143,7 +143,7 @@ describeWithDebugLogs('OOPIF', function () {
).toMatch(/frames\/frame\.html$/); ).toMatch(/frames\/frame\.html$/);
}); });
it('should support OOP iframes getting detached', async () => { it('should support OOP iframes getting detached', async () => {
const {server} = getTestState(); const {server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame(frame => { 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 () => { 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); await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame(frame => { const framePromise = page.waitForFrame(frame => {
@ -187,7 +187,7 @@ describeWithDebugLogs('OOPIF', function () {
}); });
it('should keep track of a frames OOP state', async () => { it('should keep track of a frames OOP state', async () => {
const {server} = getTestState(); const {server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame(frame => { const framePromise = page.waitForFrame(frame => {
@ -205,7 +205,7 @@ describeWithDebugLogs('OOPIF', function () {
}); });
it('should support evaluating in oop iframes', async () => { it('should support evaluating in oop iframes', async () => {
const {server} = getTestState(); const {server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame(frame => { const framePromise = page.waitForFrame(frame => {
@ -230,7 +230,7 @@ describeWithDebugLogs('OOPIF', function () {
expect(result).toBe('Test 123!'); expect(result).toBe('Test 123!');
}); });
it('should provide access to elements', async () => { it('should provide access to elements', async () => {
const {server, isHeadless, headless} = getTestState(); const {server, isHeadless, headless} = await getTestState();
if (!isHeadless || headless === 'new') { if (!isHeadless || headless === 'new') {
// TODO: this test is partially blocked on crbug.com/1334119. Enable test once // TODO: this test is partially blocked on crbug.com/1334119. Enable test once
@ -276,7 +276,7 @@ describeWithDebugLogs('OOPIF', function () {
await frame.waitForSelector('#clicked'); await frame.waitForSelector('#clicked');
}); });
it('should report oopif frames', async () => { it('should report oopif frames', async () => {
const {server} = getTestState(); const {server} = await getTestState();
const frame = page.waitForFrame(frame => { const frame = page.waitForFrame(frame => {
return frame.url().endsWith('/oopif.html'); return frame.url().endsWith('/oopif.html');
@ -288,7 +288,7 @@ describeWithDebugLogs('OOPIF', function () {
}); });
it('should wait for inner OOPIFs', async () => { it('should wait for inner OOPIFs', async () => {
const {server} = getTestState(); const {server} = await getTestState();
await page.goto(`http://mainframe:${server.PORT}/main-frame.html`); await page.goto(`http://mainframe:${server.PORT}/main-frame.html`);
const frame2 = await page.waitForFrame(frame => { const frame2 = await page.waitForFrame(frame => {
return frame.url().endsWith('inner-frame2.html'); 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 () => { it('should load oopif iframes with subresources and request interception', async () => {
const {server} = getTestState(); const {server} = await getTestState();
const frame = page.waitForFrame(frame => { const frame = page.waitForFrame(frame => {
return frame.url().endsWith('/oopif.html'); return frame.url().endsWith('/oopif.html');
@ -321,7 +321,7 @@ describeWithDebugLogs('OOPIF', function () {
expect(oopifs(context)).toHaveLength(1); expect(oopifs(context)).toHaveLength(1);
}); });
it('should support frames within OOP iframes', async () => { it('should support frames within OOP iframes', async () => {
const {server} = getTestState(); const {server} = await getTestState();
const oopIframePromise = page.waitForFrame(frame => { const oopIframePromise = page.waitForFrame(frame => {
return frame.url().endsWith('/oopif.html'); return frame.url().endsWith('/oopif.html');
@ -352,7 +352,7 @@ describeWithDebugLogs('OOPIF', function () {
}); });
it('clickablePoint, boundingBox, boxModel should work for elements inside OOPIFs', async () => { it('clickablePoint, boundingBox, boxModel should work for elements inside OOPIFs', async () => {
const {server} = getTestState(); const {server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame(frame => { const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1; 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 () => { 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 => { const frame = page.waitForFrame(frame => {
return frame.url().endsWith('/oopif.html'); return frame.url().endsWith('/oopif.html');
@ -418,7 +418,7 @@ describeWithDebugLogs('OOPIF', function () {
}); });
it('should support lazy OOP frames', async () => { 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.goto(server.PREFIX + '/lazy-oopif-frame.html');
await page.setViewport({width: 1000, height: 1000}); await page.setViewport({width: 1000, height: 1000});
@ -432,7 +432,7 @@ describeWithDebugLogs('OOPIF', function () {
describe('waitForFrame', () => { describe('waitForFrame', () => {
it('should resolve immediately if the frame already exists', async () => { it('should resolve immediately if the frame already exists', async () => {
const {server} = getTestState(); const {server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await attachFrame( 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 () => { it('should proxy requests when configured', async () => {
const {defaultBrowserOptions, server} = getTestState(); const {server} = await getTestState({
skipLaunch: true,
});
const emptyPageUrl = getEmptyPageUrl(server); const emptyPageUrl = getEmptyPageUrl(server);
const {browser, close} = await launch({ const {browser, close} = await launch({
...defaultBrowserOptions,
args: [...defaultArgs, `--proxy-server=${proxyServerUrl}`], args: [...defaultArgs, `--proxy-server=${proxyServerUrl}`],
}); });
try { try {
@ -128,11 +128,11 @@ describe('request proxy', () => {
}); });
it('should respect proxy bypass list', async () => { it('should respect proxy bypass list', async () => {
const {defaultBrowserOptions, server} = getTestState(); const {server} = await getTestState({
skipLaunch: true,
});
const emptyPageUrl = getEmptyPageUrl(server); const emptyPageUrl = getEmptyPageUrl(server);
const {browser, close} = await launch({ const {browser, close} = await launch({
...defaultBrowserOptions,
args: [ args: [
...defaultArgs, ...defaultArgs,
`--proxy-server=${proxyServerUrl}`, `--proxy-server=${proxyServerUrl}`,
@ -152,11 +152,11 @@ describe('request proxy', () => {
describe('in incognito browser context', () => { describe('in incognito browser context', () => {
it('should proxy requests when configured at browser level', async () => { 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 emptyPageUrl = getEmptyPageUrl(server);
const {browser, close} = await launch({ const {browser, close} = await launch({
...defaultBrowserOptions,
args: [...defaultArgs, `--proxy-server=${proxyServerUrl}`], args: [...defaultArgs, `--proxy-server=${proxyServerUrl}`],
}); });
try { try {
@ -172,11 +172,11 @@ describe('request proxy', () => {
}); });
it('should respect proxy bypass list when configured at browser level', async () => { 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 emptyPageUrl = getEmptyPageUrl(server);
const {browser, close} = await launch({ const {browser, close} = await launch({
...defaultBrowserOptions,
args: [ args: [
...defaultArgs, ...defaultArgs,
`--proxy-server=${proxyServerUrl}`, `--proxy-server=${proxyServerUrl}`,
@ -199,11 +199,11 @@ describe('request proxy', () => {
* See issues #7873, #7719, and #7698. * See issues #7873, #7719, and #7698.
*/ */
it('should proxy requests when configured at context level', async () => { 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 emptyPageUrl = getEmptyPageUrl(server);
const {browser, close} = await launch({ const {browser, close} = await launch({
...defaultBrowserOptions,
args: defaultArgs, args: defaultArgs,
}); });
try { try {
@ -221,11 +221,11 @@ describe('request proxy', () => {
}); });
it('should respect proxy bypass list when configured at context level', async () => { 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 emptyPageUrl = getEmptyPageUrl(server);
const {browser, close} = await launch({ const {browser, close} = await launch({
...defaultBrowserOptions,
args: defaultArgs, args: defaultArgs,
}); });
try { try {

View File

@ -19,20 +19,13 @@ import expect from 'expect';
import {Puppeteer} from 'puppeteer-core'; import {Puppeteer} from 'puppeteer-core';
import {ElementHandle} from 'puppeteer-core/internal/api/ElementHandle.js'; import {ElementHandle} from 'puppeteer-core/internal/api/ElementHandle.js';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
describe('Query handler tests', function () { describe('Query handler tests', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Pierce selectors', function () { describe('Pierce selectors', function () {
beforeEach(async () => { async function setUpPage(): ReturnType<typeof getTestState> {
const {page} = getTestState(); const state = await getTestState();
await page.setContent( await state.page.setContent(
`<script> `<script>
const div = document.createElement('div'); const div = document.createElement('div');
const shadowRoot = div.attachShadow({mode: 'open'}); const shadowRoot = div.attachShadow({mode: 'open'});
@ -47,9 +40,10 @@ describe('Query handler tests', function () {
document.documentElement.appendChild(div); document.documentElement.appendChild(div);
</script>` </script>`
); );
}); return state;
}
it('should find first element in shadow', async () => { 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 div = (await page.$('pierce/.foo')) as ElementHandle<HTMLElement>;
const text = await div.evaluate(element => { const text = await div.evaluate(element => {
return element.textContent; return element.textContent;
@ -57,7 +51,7 @@ describe('Query handler tests', function () {
expect(text).toBe('Hello'); expect(text).toBe('Hello');
}); });
it('should find all elements in shadow', async () => { it('should find all elements in shadow', async () => {
const {page} = getTestState(); const {page} = await setUpPage();
const divs = (await page.$$('pierce/.foo')) as Array< const divs = (await page.$$('pierce/.foo')) as Array<
ElementHandle<HTMLElement> ElementHandle<HTMLElement>
>; >;
@ -71,7 +65,7 @@ describe('Query handler tests', function () {
expect(text.join(' ')).toBe('Hello World'); expect(text.join(' ')).toBe('Hello World');
}); });
it('should find first child element', async () => { it('should find first child element', async () => {
const {page} = getTestState(); const {page} = await setUpPage();
const parentElement = (await page.$('html > div'))!; const parentElement = (await page.$('html > div'))!;
const childElement = (await parentElement.$( const childElement = (await parentElement.$(
'pierce/div' 'pierce/div'
@ -82,7 +76,7 @@ describe('Query handler tests', function () {
expect(text).toBe('Hello'); expect(text).toBe('Hello');
}); });
it('should find all child elements', async () => { it('should find all child elements', async () => {
const {page} = getTestState(); const {page} = await setUpPage();
const parentElement = (await page.$('html > div'))!; const parentElement = (await page.$('html > div'))!;
const childElements = (await parentElement.$$('pierce/div')) as Array< const childElements = (await parentElement.$$('pierce/div')) as Array<
ElementHandle<HTMLElement> ElementHandle<HTMLElement>
@ -101,7 +95,7 @@ describe('Query handler tests', function () {
describe('Text selectors', function () { describe('Text selectors', function () {
describe('in Page', function () { describe('in Page', function () {
it('should query existing element', async () => { it('should query existing element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<section>test</section>'); await page.setContent('<section>test</section>');
@ -109,13 +103,13 @@ describe('Query handler tests', function () {
expect(await page.$$('text/test')).toHaveLength(1); expect(await page.$$('text/test')).toHaveLength(1);
}); });
it('should return empty array for non-existing element', async () => { 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')).toBeFalsy();
expect(await page.$$('text/test')).toHaveLength(0); expect(await page.$$('text/test')).toHaveLength(0);
}); });
it('should return first element', async () => { it('should return first element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div id="1">a</div><div>a</div>'); await page.setContent('<div id="1">a</div><div>a</div>');
@ -127,7 +121,7 @@ describe('Query handler tests', function () {
).toBe('1'); ).toBe('1');
}); });
it('should return multiple elements', async () => { it('should return multiple elements', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div>a</div><div>a</div>'); await page.setContent('<div>a</div><div>a</div>');
@ -135,7 +129,7 @@ describe('Query handler tests', function () {
expect(elements).toHaveLength(2); expect(elements).toHaveLength(2);
}); });
it('should pierce shadow DOM', async () => { it('should pierce shadow DOM', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.evaluate(() => { await page.evaluate(() => {
const div = document.createElement('div'); const div = document.createElement('div');
@ -157,7 +151,7 @@ describe('Query handler tests', function () {
).toBe('a'); ).toBe('a');
}); });
it('should query deeply nested text', async () => { 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>'); await page.setContent('<div><div>a</div><div>b</div></div>');
@ -169,7 +163,7 @@ describe('Query handler tests', function () {
).toBe('a'); ).toBe('a');
}); });
it('should query inputs', async () => { it('should query inputs', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<input value="a">'); await page.setContent('<input value="a">');
@ -183,14 +177,14 @@ describe('Query handler tests', function () {
).toBe('a'); ).toBe('a');
}); });
it('should not query radio', async () => { it('should not query radio', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<radio value="a">'); await page.setContent('<radio value="a">');
expect(await page.$('text/a')).toBeNull(); expect(await page.$('text/a')).toBeNull();
}); });
it('should query text spanning multiple elements', async () => { 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>'); await page.setContent('<div><span>a</span> <span>b</span><div>');
@ -202,7 +196,7 @@ describe('Query handler tests', function () {
).toBe('a b'); ).toBe('a b');
}); });
it('should clear caches', async () => { it('should clear caches', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div id=target1>text</div><input id=target2 value=text><div id=target3>text</div>' '<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 () { describe('in ElementHandles', function () {
it('should query existing element', async () => { it('should query existing element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div class="a"><span>a</span></div>'); 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 () => { it('should return null for non-existing element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div class="a"></div>'); await page.setContent('<div class="a"></div>');
@ -295,7 +289,7 @@ describe('Query handler tests', function () {
describe('XPath selectors', function () { describe('XPath selectors', function () {
describe('in Page', function () { describe('in Page', function () {
it('should query existing element', async () => { it('should query existing element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<section>test</section>'); await page.setContent('<section>test</section>');
@ -303,7 +297,7 @@ describe('Query handler tests', function () {
expect(await page.$$('xpath/html/body/section')).toHaveLength(1); expect(await page.$$('xpath/html/body/section')).toHaveLength(1);
}); });
it('should return empty array for non-existing element', async () => { it('should return empty array for non-existing element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
expect( expect(
await page.$('xpath/html/body/non-existing-element') await page.$('xpath/html/body/non-existing-element')
@ -313,7 +307,7 @@ describe('Query handler tests', function () {
).toHaveLength(0); ).toHaveLength(0);
}); });
it('should return first element', async () => { it('should return first element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div>a</div><div></div>'); await page.setContent('<div>a</div><div></div>');
@ -325,7 +319,7 @@ describe('Query handler tests', function () {
).toBeTruthy(); ).toBeTruthy();
}); });
it('should return multiple elements', async () => { it('should return multiple elements', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div></div><div></div>'); await page.setContent('<div></div><div></div>');
@ -335,7 +329,7 @@ describe('Query handler tests', function () {
}); });
describe('in ElementHandles', function () { describe('in ElementHandles', function () {
it('should query existing element', async () => { it('should query existing element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div class="a">a<span></span></div>'); 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 () => { it('should return null for non-existing element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div class="a">a</div>'); await page.setContent('<div class="a">a</div>');
@ -358,13 +352,12 @@ describe('Query handler tests', function () {
describe('P selectors', () => { describe('P selectors', () => {
beforeEach(async () => { beforeEach(async () => {
const {page, server} = getTestState();
await page.goto(`${server.PREFIX}/p-selectors.html`);
Puppeteer.clearCustomQueryHandlers(); Puppeteer.clearCustomQueryHandlers();
}); });
it('should work with CSS selectors', async () => { 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'); const element = await page.$('div > button');
assert(element, 'Could not find element'); assert(element, 'Could not find element');
expect( expect(
@ -385,7 +378,8 @@ describe('Query handler tests', function () {
}); });
it('should work with deep combinators', async () => { 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'); const element = await page.$('div >>>> div');
assert(element, 'Could not find element'); assert(element, 'Could not find element');
@ -425,7 +419,8 @@ describe('Query handler tests', function () {
}); });
it('should work with text selectors', async () => { 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)'); const element = await page.$('div ::-p-text(world)');
assert(element, 'Could not find element'); assert(element, 'Could not find element');
expect( expect(
@ -436,7 +431,8 @@ describe('Query handler tests', function () {
}); });
it('should work ARIA selectors', async () => { 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)'); const element = await page.$('div ::-p-aria(world)');
assert(element, 'Could not find element'); assert(element, 'Could not find element');
expect( expect(
@ -447,7 +443,8 @@ describe('Query handler tests', function () {
}); });
it('should work for ARIA selectors in multiple isolated worlds', async () => { 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)'); let element = await page.waitForSelector('::-p-aria(world)');
assert(element, 'Could not find element'); assert(element, 'Could not find element');
expect( expect(
@ -467,7 +464,8 @@ describe('Query handler tests', function () {
}); });
it('should work ARIA selectors with role', async () => { 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"])'); const element = await page.$('::-p-aria(world[role="button"])');
assert(element, 'Could not find element'); assert(element, 'Could not find element');
expect( expect(
@ -478,7 +476,8 @@ describe('Query handler tests', function () {
}); });
it('should work ARIA selectors with name and role', async () => { 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"])'); const element = await page.$('::-p-aria([name="world"][role="button"])');
assert(element, 'Could not find element'); assert(element, 'Could not find element');
expect( expect(
@ -489,7 +488,8 @@ describe('Query handler tests', function () {
}); });
it('should work XPath selectors', async () => { 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)'); const element = await page.$('div ::-p-xpath(//button)');
assert(element, 'Could not find element'); assert(element, 'Could not find element');
expect( 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'); const element = await page.$('::-p-div');
assert(element, 'Could not find element'); assert(element, 'Could not find element');
expect( expect(
@ -517,7 +518,8 @@ describe('Query handler tests', function () {
}); });
it('should work with custom selectors with args', async () => { 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', { Puppeteer.registerCustomQueryHandler('div', {
queryOne(_, selector) { queryOne(_, selector) {
if (selector === 'true') { if (selector === 'true') {
@ -567,7 +569,8 @@ describe('Query handler tests', function () {
}); });
it('should work with :hover', async () => { 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)'); let button = await page.$('div ::-p-text(world)');
assert(button, 'Could not find element'); assert(button, 'Could not find element');
await button.hover(); await button.hover();
@ -582,7 +585,8 @@ describe('Query handler tests', function () {
}); });
it('should work with selector lists', async () => { 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)'); const elements = await page.$$('div, ::-p-text(world)');
expect(elements).toHaveLength(3); expect(elements).toHaveLength(3);
}); });
@ -606,7 +610,8 @@ describe('Query handler tests', function () {
}; };
it('should match querySelector* ordering', async () => { 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'])) { for (const list of permute(['div', 'button', 'span'])) {
const elements = await page.$$( const elements = await page.$$(
list list
@ -627,7 +632,8 @@ describe('Query handler tests', function () {
}); });
it('should not have duplicate elements from selector lists', async () => { 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'); const elements = await page.$$('::-p-text(world), button');
expect(elements).toHaveLength(1); expect(elements).toHaveLength(1);
}); });

View File

@ -17,18 +17,12 @@ import expect from 'expect';
import {Puppeteer} from 'puppeteer'; import {Puppeteer} from 'puppeteer';
import type {CustomQueryHandler} from 'puppeteer-core/internal/common/CustomQueryHandler.js'; import type {CustomQueryHandler} from 'puppeteer-core/internal/common/CustomQueryHandler.js';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
describe('querySelector', function () { describe('querySelector', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Page.$eval', function () { describe('Page.$eval', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<section id="testAttribute">43543</section>'); await page.setContent('<section id="testAttribute">43543</section>');
const idAttribute = await page.$eval('section', e => { const idAttribute = await page.$eval('section', e => {
@ -37,7 +31,7 @@ describe('querySelector', function () {
expect(idAttribute).toBe('testAttribute'); expect(idAttribute).toBe('testAttribute');
}); });
it('should accept arguments', async () => { it('should accept arguments', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<section>hello</section>'); await page.setContent('<section>hello</section>');
const text = await page.$eval( const text = await page.$eval(
@ -50,7 +44,7 @@ describe('querySelector', function () {
expect(text).toBe('hello world!'); expect(text).toBe('hello world!');
}); });
it('should accept ElementHandles as arguments', async () => { it('should accept ElementHandles as arguments', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<section>hello</section><div> world</div>'); await page.setContent('<section>hello</section><div> world</div>');
const divHandle = (await page.$('div'))!; const divHandle = (await page.$('div'))!;
@ -64,7 +58,7 @@ describe('querySelector', function () {
expect(text).toBe('hello world'); expect(text).toBe('hello world');
}); });
it('should throw error if no element is found', async () => { it('should throw error if no element is found', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page await page
@ -85,7 +79,7 @@ describe('querySelector', function () {
// as opposed to NodeListOf<Element>. // as opposed to NodeListOf<Element>.
describe('Page.$$eval', function () { describe('Page.$$eval', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div>hello</div><div>beautiful</div><div>world!</div>' '<div>hello</div><div>beautiful</div><div>world!</div>'
@ -96,7 +90,7 @@ describe('querySelector', function () {
expect(divsCount).toBe(3); expect(divsCount).toBe(3);
}); });
it('should accept extra arguments', async () => { it('should accept extra arguments', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div>hello</div><div>beautiful</div><div>world!</div>' '<div>hello</div><div>beautiful</div><div>world!</div>'
); );
@ -111,7 +105,7 @@ describe('querySelector', function () {
expect(divsCountPlus5).toBe(8); expect(divsCountPlus5).toBe(8);
}); });
it('should accept ElementHandles as arguments', async () => { it('should accept ElementHandles as arguments', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<section>2</section><section>2</section><section>1</section><div>3</div>' '<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 () { it('should handle many elements', async function () {
this.timeout(25_000); this.timeout(25_000);
const {page} = getTestState(); const {page} = await getTestState();
await page.evaluate( await page.evaluate(
` `
for (var i = 0; i <= 1000; i++) { for (var i = 0; i <= 1000; i++) {
@ -153,14 +147,14 @@ describe('querySelector', function () {
describe('Page.$', function () { describe('Page.$', function () {
it('should query existing element', async () => { it('should query existing element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<section>test</section>'); await page.setContent('<section>test</section>');
const element = (await page.$('section'))!; const element = (await page.$('section'))!;
expect(element).toBeTruthy(); expect(element).toBeTruthy();
}); });
it('should return null for non-existing element', async () => { it('should return null for non-existing element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const element = (await page.$('non-existing-element'))!; const element = (await page.$('non-existing-element'))!;
expect(element).toBe(null); expect(element).toBe(null);
@ -169,7 +163,7 @@ describe('querySelector', function () {
describe('Page.$$', function () { describe('Page.$$', function () {
it('should query existing elements', async () => { it('should query existing elements', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div>A</div><br/><div>B</div>'); await page.setContent('<div>A</div><br/><div>B</div>');
const elements = await page.$$('div'); const elements = await page.$$('div');
@ -182,7 +176,7 @@ describe('querySelector', function () {
expect(await Promise.all(promises)).toEqual(['A', 'B']); expect(await Promise.all(promises)).toEqual(['A', 'B']);
}); });
it('should return empty array if nothing is found', async () => { 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); await page.goto(server.EMPTY_PAGE);
const elements = await page.$$('div'); const elements = await page.$$('div');
@ -192,7 +186,7 @@ describe('querySelector', function () {
describe('Page.$x', function () { describe('Page.$x', function () {
it('should query existing element', async () => { it('should query existing element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<section>test</section>'); await page.setContent('<section>test</section>');
const elements = await page.$x('/html/body/section'); const elements = await page.$x('/html/body/section');
@ -200,13 +194,13 @@ describe('querySelector', function () {
expect(elements).toHaveLength(1); expect(elements).toHaveLength(1);
}); });
it('should return empty array for non-existing element', async () => { 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'); const element = await page.$x('/html/body/non-existing-element');
expect(element).toEqual([]); expect(element).toEqual([]);
}); });
it('should return multiple elements', async () => { it('should return multiple elements', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div></div><div></div>'); await page.setContent('<div></div><div></div>');
const elements = await page.$x('/html/body/div'); const elements = await page.$x('/html/body/div');
@ -216,7 +210,7 @@ describe('querySelector', function () {
describe('ElementHandle.$', function () { describe('ElementHandle.$', function () {
it('should query existing element', async () => { it('should query existing element', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/playground.html'); await page.goto(server.PREFIX + '/playground.html');
await page.setContent( await page.setContent(
@ -232,7 +226,7 @@ describe('querySelector', function () {
}); });
it('should return null for non-existing element', async () => { it('should return null for non-existing element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<html><body><div class="second"><div class="inner">B</div></div></body></html>' '<html><body><div class="second"><div class="inner">B</div></div></body></html>'
@ -244,7 +238,7 @@ describe('querySelector', function () {
}); });
describe('ElementHandle.$eval', function () { describe('ElementHandle.$eval', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<html><body><div class="tweet"><div class="like">100</div><div class="retweets">10</div></div></body></html>' '<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 () => { it('should retrieve content from subtree', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const htmlContent = const htmlContent =
'<div class="a">not-a-child-div</div><div id="myId"><div class="a">a-child-div</div></div>'; '<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 () => { it('should throw in case of missing selector', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const htmlContent = const htmlContent =
'<div class="a">not-a-child-div</div><div id="myId"></div>'; '<div class="a">not-a-child-div</div><div id="myId"></div>';
@ -290,7 +284,7 @@ describe('querySelector', function () {
}); });
describe('ElementHandle.$$eval', function () { describe('ElementHandle.$$eval', function () {
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<html><body><div class="tweet"><div class="like">100</div><div class="like">10</div></div></body></html>' '<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 () => { it('should retrieve content from subtree', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const htmlContent = 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>'; '<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 () => { it('should not throw in case of missing selector', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const htmlContent = const htmlContent =
'<div class="a">not-a-child-div</div><div id="myId"></div>'; '<div class="a">not-a-child-div</div><div id="myId"></div>';
@ -335,7 +329,7 @@ describe('querySelector', function () {
describe('ElementHandle.$$', function () { describe('ElementHandle.$$', function () {
it('should query existing elements', async () => { it('should query existing elements', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<html><body><div>A</div><br/><div>B</div></body></html>' '<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 () => { it('should return empty array for non-existing elements', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<html><body><span>A</span><br/><span>B</span></body></html>' '<html><body><span>A</span><br/><span>B</span></body></html>'
@ -365,7 +359,7 @@ describe('querySelector', function () {
describe('ElementHandle.$x', function () { describe('ElementHandle.$x', function () {
it('should query existing element', async () => { it('should query existing element', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.PREFIX + '/playground.html'); await page.goto(server.PREFIX + '/playground.html');
await page.setContent( await page.setContent(
@ -381,7 +375,7 @@ describe('querySelector', function () {
}); });
it('should return null for non-existing element', async () => { it('should return null for non-existing element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<html><body><div class="second"><div class="inner">B</div></div></body></html>' '<html><body><div class="second"><div class="inner">B</div></div></body></html>'
@ -410,7 +404,7 @@ describe('querySelector', function () {
).toBeTruthy(); ).toBeTruthy();
}); });
it('$$ should query existing elements', async () => { it('$$ should query existing elements', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<html><body><div>A</div><br/><div>B</div></body></html>' '<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 () => { it('$$ should return empty array for non-existing elements', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<html><body><span>A</span><br/><span>B</span></body></html>' '<html><body><span>A</span><br/><span>B</span></body></html>'
@ -437,7 +431,7 @@ describe('querySelector', function () {
expect(elements).toHaveLength(0); expect(elements).toHaveLength(0);
}); });
it('$$eval should work', async () => { it('$$eval should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div>hello</div><div>beautiful</div><div>world!</div>' '<div>hello</div><div>beautiful</div><div>world!</div>'
@ -448,7 +442,7 @@ describe('querySelector', function () {
expect(divsCount).toBe(3); expect(divsCount).toBe(3);
}); });
it('$$eval should accept extra arguments', async () => { it('$$eval should accept extra arguments', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div>hello</div><div>beautiful</div><div>world!</div>' '<div>hello</div><div>beautiful</div><div>world!</div>'
); );
@ -463,7 +457,7 @@ describe('querySelector', function () {
expect(divsCountPlus5).toBe(8); expect(divsCountPlus5).toBe(8);
}); });
it('$$eval should accept ElementHandles as arguments', async () => { it('$$eval should accept ElementHandles as arguments', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<section>2</section><section>2</section><section>1</section><div>3</div>' '<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 () { it('$$eval should handle many elements', async function () {
this.timeout(25_000); this.timeout(25_000);
const {page} = getTestState(); const {page} = await getTestState();
await page.evaluate( await page.evaluate(
` `
for (var i = 0; i <= 1000; i++) { for (var i = 0; i <= 1000; i++) {

View File

@ -25,22 +25,16 @@ import {
} from 'puppeteer-core/internal/api/HTTPRequest.js'; } from 'puppeteer-core/internal/api/HTTPRequest.js';
import {ConsoleMessage} from 'puppeteer-core/internal/common/ConsoleMessage.js'; import {ConsoleMessage} from 'puppeteer-core/internal/common/ConsoleMessage.js';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {isFavicon, waitEvent} from './utils.js'; import {isFavicon, waitEvent} from './utils.js';
describe('request interception', function () { describe('request interception', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Page.setRequestInterception', function () { describe('Page.setRequestInterception', function () {
const expectedActions: ActionResult[] = ['abort', 'continue', 'respond']; const expectedActions: ActionResult[] = ['abort', 'continue', 'respond'];
while (expectedActions.length > 0) { while (expectedActions.length > 0) {
const expectedAction = expectedActions.pop(); const expectedAction = expectedActions.pop();
it(`should cooperatively ${expectedAction} by priority`, async () => { it(`should cooperatively ${expectedAction} by priority`, async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const actionResults: ActionResult[] = []; const actionResults: ActionResult[] = [];
await page.setRequestInterception(true); await page.setRequestInterception(true);
@ -105,7 +99,7 @@ describe('request interception', function () {
} }
it('should intercept', async () => { it('should intercept', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -129,7 +123,7 @@ describe('request interception', function () {
}); });
// @see https://github.com/puppeteer/puppeteer/pull/3105 // @see https://github.com/puppeteer/puppeteer/pull/3105
it('should work when POST is redirected with 302', async () => { it('should work when POST is redirected with 302', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.setRedirect('/rredirect', '/empty.html'); server.setRedirect('/rredirect', '/empty.html');
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -151,7 +145,7 @@ describe('request interception', function () {
}); });
// @see https://github.com/puppeteer/puppeteer/issues/3973 // @see https://github.com/puppeteer/puppeteer/issues/3973
it('should work when header manipulation headers with redirect', async () => { it('should work when header manipulation headers with redirect', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.setRedirect('/rrredirect', '/empty.html'); server.setRedirect('/rrredirect', '/empty.html');
await page.setRequestInterception(true); await page.setRequestInterception(true);
@ -168,7 +162,7 @@ describe('request interception', function () {
}); });
// @see https://github.com/puppeteer/puppeteer/issues/4743 // @see https://github.com/puppeteer/puppeteer/issues/4743
it('should be able to remove headers', async () => { it('should be able to remove headers', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -187,7 +181,7 @@ describe('request interception', function () {
expect(serverRequest.headers.origin).toBe(undefined); expect(serverRequest.headers.origin).toBe(undefined);
}); });
it('should contain referer header', async () => { it('should contain referer header', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
@ -202,7 +196,7 @@ describe('request interception', function () {
expect(requests[1]!.headers()['referer']).toContain('/one-style.html'); expect(requests[1]!.headers()['referer']).toContain('/one-style.html');
}); });
it('should properly return navigation response when URL has cookies', async () => { it('should properly return navigation response when URL has cookies', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
// Setup cookie. // Setup cookie.
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -217,7 +211,7 @@ describe('request interception', function () {
expect(response!.status()).toBe(200); expect(response!.status()).toBe(200);
}); });
it('should stop intercepting', async () => { it('should stop intercepting', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.once('request', request => { page.once('request', request => {
@ -228,7 +222,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
}); });
it('should show custom HTTP headers', async () => { it('should show custom HTTP headers', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setExtraHTTPHeaders({ await page.setExtraHTTPHeaders({
foo: 'bar', foo: 'bar',
@ -243,7 +237,7 @@ describe('request interception', function () {
}); });
// @see https://github.com/puppeteer/puppeteer/issues/4337 // @see https://github.com/puppeteer/puppeteer/issues/4337
it('should work with redirect inside sync XHR', async () => { it('should work with redirect inside sync XHR', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
server.setRedirect('/logo.png', '/pptr.png'); server.setRedirect('/logo.png', '/pptr.png');
@ -260,7 +254,7 @@ describe('request interception', function () {
expect(status).toBe(200); expect(status).toBe(200);
}); });
it('should work with custom referer headers', async () => { 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.setExtraHTTPHeaders({referer: server.EMPTY_PAGE});
await page.setRequestInterception(true); await page.setRequestInterception(true);
@ -272,7 +266,7 @@ describe('request interception', function () {
expect(response!.ok()).toBe(true); expect(response!.ok()).toBe(true);
}); });
it('should be abortable', async () => { it('should be abortable', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -292,7 +286,7 @@ describe('request interception', function () {
expect(failedRequests).toBe(1); expect(failedRequests).toBe(1);
}); });
it('should be able to access the error reason', async () => { it('should be able to access the error reason', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -307,7 +301,7 @@ describe('request interception', function () {
expect(abortReason).toBe('Failed'); expect(abortReason).toBe('Failed');
}); });
it('should be abortable with custom error codes', async () => { it('should be abortable with custom error codes', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -324,7 +318,7 @@ describe('request interception', function () {
); );
}); });
it('should send referer', async () => { it('should send referer', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setExtraHTTPHeaders({ await page.setExtraHTTPHeaders({
referer: 'http://google.com/', referer: 'http://google.com/',
@ -340,7 +334,7 @@ describe('request interception', function () {
expect(request.headers['referer']).toBe('http://google.com/'); expect(request.headers['referer']).toBe('http://google.com/');
}); });
it('should fail navigation when aborting main resource', async () => { it('should fail navigation when aborting main resource', async () => {
const {page, server, isChrome} = getTestState(); const {page, server, isChrome} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -358,7 +352,7 @@ describe('request interception', function () {
} }
}); });
it('should work with redirects', async () => { it('should work with redirects', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
@ -398,7 +392,7 @@ describe('request interception', function () {
} }
}); });
it('should work with redirects for subresources', async () => { it('should work with redirects for subresources', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
@ -428,7 +422,7 @@ describe('request interception', function () {
expect(redirectChain[2]!.url()).toContain('/three-style.css'); expect(redirectChain[2]!.url()).toContain('/three-style.css');
}); });
it('should be able to abort redirects', async () => { it('should be able to abort redirects', async () => {
const {page, server, isChrome} = getTestState(); const {page, server, isChrome} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
server.setRedirect('/non-existing.json', '/non-existing-2.json'); server.setRedirect('/non-existing.json', '/non-existing-2.json');
@ -455,7 +449,7 @@ describe('request interception', function () {
} }
}); });
it('should work with equal requests', async () => { it('should work with equal requests', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
let responseCount = 1; let responseCount = 1;
@ -502,7 +496,7 @@ describe('request interception', function () {
expect(results).toEqual(['11', 'FAILED', '22']); expect(results).toEqual(['11', 'FAILED', '22']);
}); });
it('should navigate to dataURL and fire dataURL requests', async () => { it('should navigate to dataURL and fire dataURL requests', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
@ -517,7 +511,7 @@ describe('request interception', function () {
expect(requests[0]!.url()).toBe(dataURL); expect(requests[0]!.url()).toBe(dataURL);
}); });
it('should be able to fetch dataURL and fire dataURL requests', async () => { 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.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true); await page.setRequestInterception(true);
@ -537,7 +531,7 @@ describe('request interception', function () {
expect(requests[0]!.url()).toBe(dataURL); expect(requests[0]!.url()).toBe(dataURL);
}); });
it('should navigate to URL with hash and fire requests without hash', async () => { 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); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
@ -552,7 +546,7 @@ describe('request interception', function () {
expect(requests[0]!.url()).toBe(server.EMPTY_PAGE); expect(requests[0]!.url()).toBe(server.EMPTY_PAGE);
}); });
it('should work with encoded server', async () => { 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 // The requestWillBeSent will report encoded URL, whereas interception will
// report URL as-is. @see crbug.com/759388 // report URL as-is. @see crbug.com/759388
@ -566,7 +560,7 @@ describe('request interception', function () {
expect(response!.status()).toBe(404); expect(response!.status()).toBe(404);
}); });
it('should work with badly encoded server', async () => { it('should work with badly encoded server', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
server.setRoute('/malformed?rnd=%911', (_req, res) => { server.setRoute('/malformed?rnd=%911', (_req, res) => {
@ -579,7 +573,7 @@ describe('request interception', function () {
expect(response!.status()).toBe(200); expect(response!.status()).toBe(200);
}); });
it('should work with encoded server - 2', async () => { 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 // The requestWillBeSent will report URL as-is, whereas interception will
// report encoded URL for stylesheet. @see crbug.com/759388 // report encoded URL for stylesheet. @see crbug.com/759388
@ -597,7 +591,7 @@ describe('request interception', function () {
expect(requests[1]!.response()!.status()).toBe(404); expect(requests[1]!.response()!.status()).toBe(404);
}); });
it('should not throw "Invalid Interception Id" if the request was cancelled', async () => { 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.setContent('<iframe></iframe>');
await page.setRequestInterception(true); await page.setRequestInterception(true);
@ -625,7 +619,7 @@ describe('request interception', function () {
expect(error).toBeUndefined(); expect(error).toBeUndefined();
}); });
it('should throw if interception is not enabled', async () => { it('should throw if interception is not enabled', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
let error!: Error; let error!: Error;
page.on('request', async request => { page.on('request', async request => {
@ -639,7 +633,7 @@ describe('request interception', function () {
expect(error.message).toContain('Request Interception is not enabled'); expect(error.message).toContain('Request Interception is not enabled');
}); });
it('should work with file URLs', async () => { it('should work with file URLs', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
const urls = new Set(); const urls = new Set();
@ -655,7 +649,7 @@ describe('request interception', function () {
expect(urls.has('one-style.css')).toBe(true); expect(urls.has('one-style.css')).toBe(true);
}); });
it('should not cache if cache disabled', async () => { 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. // Load and re-load to make sure it's cached.
await page.goto(server.PREFIX + '/cached/one-style.html'); await page.goto(server.PREFIX + '/cached/one-style.html');
@ -675,7 +669,7 @@ describe('request interception', function () {
expect(cached).toHaveLength(0); expect(cached).toHaveLength(0);
}); });
it('should cache if cache enabled', async () => { 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. // Load and re-load to make sure it's cached.
await page.goto(server.PREFIX + '/cached/one-style.html'); await page.goto(server.PREFIX + '/cached/one-style.html');
@ -695,7 +689,7 @@ describe('request interception', function () {
expect(cached).toHaveLength(1); expect(cached).toHaveLength(1);
}); });
it('should load fonts if cache enabled', async () => { it('should load fonts if cache enabled', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
await page.setCacheEnabled(true); await page.setCacheEnabled(true);
@ -712,7 +706,7 @@ describe('request interception', function () {
describe('Request.continue', function () { describe('Request.continue', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -721,7 +715,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
}); });
it('should amend HTTP headers', async () => { it('should amend HTTP headers', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -739,7 +733,7 @@ describe('request interception', function () {
expect(request.headers['foo']).toBe('bar'); expect(request.headers['foo']).toBe('bar');
}); });
it('should redirect in a way non-observable to page', async () => { it('should redirect in a way non-observable to page', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -757,7 +751,7 @@ describe('request interception', function () {
expect(consoleMessage.text()).toBe('yellow'); expect(consoleMessage.text()).toBe('yellow');
}); });
it('should amend method', async () => { it('should amend method', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -774,7 +768,7 @@ describe('request interception', function () {
expect(request.method).toBe('POST'); expect(request.method).toBe('POST');
}); });
it('should amend post data', async () => { it('should amend post data', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -791,7 +785,7 @@ describe('request interception', function () {
expect(await serverRequest.postBody).toBe('doggo'); expect(await serverRequest.postBody).toBe('doggo');
}); });
it('should amend both post data and method on navigation', async () => { it('should amend both post data and method on navigation', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -808,7 +802,7 @@ describe('request interception', function () {
describe('Request.respond', function () { describe('Request.respond', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -833,7 +827,7 @@ describe('request interception', function () {
).toBe('Yo, page!'); ).toBe('Yo, page!');
}); });
it('should be able to access the response', async () => { it('should be able to access the response', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -854,7 +848,7 @@ describe('request interception', function () {
expect(response).toEqual({status: 200, body: 'Yo, page!'}); expect(response).toEqual({status: 200, body: 'Yo, page!'});
}); });
it('should work with status code 422', async () => { it('should work with status code 422', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -876,7 +870,7 @@ describe('request interception', function () {
).toBe('Yo, page!'); ).toBe('Yo, page!');
}); });
it('should redirect', async () => { it('should redirect', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -902,7 +896,7 @@ describe('request interception', function () {
expect(response!.url()).toBe(server.EMPTY_PAGE); expect(response!.url()).toBe(server.EMPTY_PAGE);
}); });
it('should allow mocking binary responses', async () => { it('should allow mocking binary responses', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -929,7 +923,7 @@ describe('request interception', function () {
expect(await img.screenshot()).toBeGolden('mock-binary-response.png'); expect(await img.screenshot()).toBeGolden('mock-binary-response.png');
}); });
it('should stringify intercepted request response headers', async () => { it('should stringify intercepted request response headers', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -955,7 +949,7 @@ describe('request interception', function () {
).toBe('Yo, page!'); ).toBe('Yo, page!');
}); });
it('should indicate already-handled if an intercept has been handled', async () => { 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); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {

View File

@ -21,19 +21,13 @@ import expect from 'expect';
import {HTTPRequest} from 'puppeteer-core/internal/api/HTTPRequest.js'; import {HTTPRequest} from 'puppeteer-core/internal/api/HTTPRequest.js';
import {ConsoleMessage} from 'puppeteer-core/internal/common/ConsoleMessage.js'; import {ConsoleMessage} from 'puppeteer-core/internal/common/ConsoleMessage.js';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {isFavicon, waitEvent} from './utils.js'; import {isFavicon, waitEvent} from './utils.js';
describe('request interception', function () { describe('request interception', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Page.setRequestInterception', function () { describe('Page.setRequestInterception', function () {
it('should intercept', async () => { it('should intercept', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -58,7 +52,7 @@ describe('request interception', function () {
}); });
// @see https://github.com/puppeteer/puppeteer/pull/3105 // @see https://github.com/puppeteer/puppeteer/pull/3105
it('should work when POST is redirected with 302', async () => { it('should work when POST is redirected with 302', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.setRedirect('/rredirect', '/empty.html'); server.setRedirect('/rredirect', '/empty.html');
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -80,7 +74,7 @@ describe('request interception', function () {
}); });
// @see https://github.com/puppeteer/puppeteer/issues/3973 // @see https://github.com/puppeteer/puppeteer/issues/3973
it('should work when header manipulation headers with redirect', async () => { it('should work when header manipulation headers with redirect', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
server.setRedirect('/rrredirect', '/empty.html'); server.setRedirect('/rrredirect', '/empty.html');
await page.setRequestInterception(true); await page.setRequestInterception(true);
@ -94,7 +88,7 @@ describe('request interception', function () {
}); });
// @see https://github.com/puppeteer/puppeteer/issues/4743 // @see https://github.com/puppeteer/puppeteer/issues/4743
it('should be able to remove headers', async () => { it('should be able to remove headers', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -113,7 +107,7 @@ describe('request interception', function () {
expect(serverRequest.headers.origin).toBe(undefined); expect(serverRequest.headers.origin).toBe(undefined);
}); });
it('should contain referer header', async () => { it('should contain referer header', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
@ -128,7 +122,7 @@ describe('request interception', function () {
expect(requests[1]!.headers()['referer']).toContain('/one-style.html'); expect(requests[1]!.headers()['referer']).toContain('/one-style.html');
}); });
it('should work with requests without networkId', async () => { 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.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true); await page.setRequestInterception(true);
@ -144,7 +138,7 @@ describe('request interception', function () {
expect(urls).toStrictEqual([server.EMPTY_PAGE]); expect(urls).toStrictEqual([server.EMPTY_PAGE]);
}); });
it('should properly return navigation response when URL has cookies', async () => { it('should properly return navigation response when URL has cookies', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
// Setup cookie. // Setup cookie.
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -159,7 +153,7 @@ describe('request interception', function () {
expect(response.status()).toBe(200); expect(response.status()).toBe(200);
}); });
it('should stop intercepting', async () => { it('should stop intercepting', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.once('request', request => { page.once('request', request => {
@ -170,7 +164,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
}); });
it('should show custom HTTP headers', async () => { it('should show custom HTTP headers', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setExtraHTTPHeaders({ await page.setExtraHTTPHeaders({
foo: 'bar', foo: 'bar',
@ -185,7 +179,7 @@ describe('request interception', function () {
}); });
// @see https://github.com/puppeteer/puppeteer/issues/4337 // @see https://github.com/puppeteer/puppeteer/issues/4337
it('should work with redirect inside sync XHR', async () => { it('should work with redirect inside sync XHR', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
server.setRedirect('/logo.png', '/pptr.png'); server.setRedirect('/logo.png', '/pptr.png');
@ -202,7 +196,7 @@ describe('request interception', function () {
expect(status).toBe(200); expect(status).toBe(200);
}); });
it('should work with custom referer headers', async () => { 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.setExtraHTTPHeaders({referer: server.EMPTY_PAGE});
await page.setRequestInterception(true); await page.setRequestInterception(true);
@ -214,7 +208,7 @@ describe('request interception', function () {
expect(response.ok()).toBe(true); expect(response.ok()).toBe(true);
}); });
it('should be abortable', async () => { it('should be abortable', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -234,7 +228,7 @@ describe('request interception', function () {
expect(failedRequests).toBe(1); expect(failedRequests).toBe(1);
}); });
it('should be abortable with custom error codes', async () => { it('should be abortable with custom error codes', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -251,7 +245,7 @@ describe('request interception', function () {
); );
}); });
it('should send referer', async () => { it('should send referer', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setExtraHTTPHeaders({ await page.setExtraHTTPHeaders({
referer: 'http://google.com/', referer: 'http://google.com/',
@ -267,7 +261,7 @@ describe('request interception', function () {
expect(request.headers['referer']).toBe('http://google.com/'); expect(request.headers['referer']).toBe('http://google.com/');
}); });
it('should fail navigation when aborting main resource', async () => { it('should fail navigation when aborting main resource', async () => {
const {page, server, isChrome} = getTestState(); const {page, server, isChrome} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -285,7 +279,7 @@ describe('request interception', function () {
} }
}); });
it('should work with redirects', async () => { it('should work with redirects', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
@ -325,7 +319,7 @@ describe('request interception', function () {
} }
}); });
it('should work with redirects for subresources', async () => { it('should work with redirects for subresources', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
@ -355,7 +349,7 @@ describe('request interception', function () {
expect(redirectChain[2]!.url()).toContain('/three-style.css'); expect(redirectChain[2]!.url()).toContain('/three-style.css');
}); });
it('should be able to abort redirects', async () => { it('should be able to abort redirects', async () => {
const {page, server, isChrome} = getTestState(); const {page, server, isChrome} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
server.setRedirect('/non-existing.json', '/non-existing-2.json'); server.setRedirect('/non-existing.json', '/non-existing-2.json');
@ -382,7 +376,7 @@ describe('request interception', function () {
} }
}); });
it('should work with equal requests', async () => { it('should work with equal requests', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
let responseCount = 1; let responseCount = 1;
@ -429,7 +423,7 @@ describe('request interception', function () {
expect(results).toEqual(['11', 'FAILED', '22']); expect(results).toEqual(['11', 'FAILED', '22']);
}); });
it('should navigate to dataURL and fire dataURL requests', async () => { it('should navigate to dataURL and fire dataURL requests', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
@ -444,7 +438,7 @@ describe('request interception', function () {
expect(requests[0]!.url()).toBe(dataURL); expect(requests[0]!.url()).toBe(dataURL);
}); });
it('should be able to fetch dataURL and fire dataURL requests', async () => { 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.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true); await page.setRequestInterception(true);
@ -464,7 +458,7 @@ describe('request interception', function () {
expect(requests[0]!.url()).toBe(dataURL); expect(requests[0]!.url()).toBe(dataURL);
}); });
it('should navigate to URL with hash and fire requests without hash', async () => { 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); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
@ -479,7 +473,7 @@ describe('request interception', function () {
expect(requests[0]!.url()).toBe(server.EMPTY_PAGE); expect(requests[0]!.url()).toBe(server.EMPTY_PAGE);
}); });
it('should work with encoded server', async () => { 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 // The requestWillBeSent will report encoded URL, whereas interception will
// report URL as-is. @see crbug.com/759388 // report URL as-is. @see crbug.com/759388
@ -493,7 +487,7 @@ describe('request interception', function () {
expect(response.status()).toBe(404); expect(response.status()).toBe(404);
}); });
it('should work with badly encoded server', async () => { it('should work with badly encoded server', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
server.setRoute('/malformed?rnd=%911', (_req, res) => { server.setRoute('/malformed?rnd=%911', (_req, res) => {
@ -508,7 +502,7 @@ describe('request interception', function () {
expect(response.status()).toBe(200); expect(response.status()).toBe(200);
}); });
it('should work with encoded server - 2', async () => { 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 // The requestWillBeSent will report URL as-is, whereas interception will
// report encoded URL for stylesheet. @see crbug.com/759388 // report encoded URL for stylesheet. @see crbug.com/759388
@ -526,7 +520,7 @@ describe('request interception', function () {
expect(requests[1]!.response()!.status()).toBe(404); expect(requests[1]!.response()!.status()).toBe(404);
}); });
it('should not throw "Invalid Interception Id" if the request was cancelled', async () => { 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.setContent('<iframe></iframe>');
await page.setRequestInterception(true); await page.setRequestInterception(true);
@ -554,7 +548,7 @@ describe('request interception', function () {
expect(error).toBeUndefined(); expect(error).toBeUndefined();
}); });
it('should throw if interception is not enabled', async () => { it('should throw if interception is not enabled', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
let error!: Error; let error!: Error;
page.on('request', async request => { page.on('request', async request => {
@ -568,7 +562,7 @@ describe('request interception', function () {
expect(error.message).toContain('Request Interception is not enabled'); expect(error.message).toContain('Request Interception is not enabled');
}); });
it('should work with file URLs', async () => { it('should work with file URLs', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
const urls = new Set(); const urls = new Set();
@ -584,7 +578,7 @@ describe('request interception', function () {
expect(urls.has('one-style.css')).toBe(true); expect(urls.has('one-style.css')).toBe(true);
}); });
it('should not cache if cache disabled', async () => { 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. // Load and re-load to make sure it's cached.
await page.goto(server.PREFIX + '/cached/one-style.html'); await page.goto(server.PREFIX + '/cached/one-style.html');
@ -604,7 +598,7 @@ describe('request interception', function () {
expect(cached).toHaveLength(0); expect(cached).toHaveLength(0);
}); });
it('should cache if cache enabled', async () => { 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. // Load and re-load to make sure it's cached.
await page.goto(server.PREFIX + '/cached/one-style.html'); await page.goto(server.PREFIX + '/cached/one-style.html');
@ -624,7 +618,7 @@ describe('request interception', function () {
expect(cached).toHaveLength(1); expect(cached).toHaveLength(1);
}); });
it('should load fonts if cache enabled', async () => { it('should load fonts if cache enabled', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
await page.setCacheEnabled(true); await page.setCacheEnabled(true);
@ -642,7 +636,7 @@ describe('request interception', function () {
describe('Request.continue', function () { describe('Request.continue', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -651,7 +645,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
}); });
it('should amend HTTP headers', async () => { it('should amend HTTP headers', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -669,7 +663,7 @@ describe('request interception', function () {
expect(request.headers['foo']).toBe('bar'); expect(request.headers['foo']).toBe('bar');
}); });
it('should redirect in a way non-observable to page', async () => { it('should redirect in a way non-observable to page', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -686,7 +680,7 @@ describe('request interception', function () {
expect(consoleMessage.text()).toBe('yellow'); expect(consoleMessage.text()).toBe('yellow');
}); });
it('should amend method', async () => { it('should amend method', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -703,7 +697,7 @@ describe('request interception', function () {
expect(request.method).toBe('POST'); expect(request.method).toBe('POST');
}); });
it('should amend post data', async () => { it('should amend post data', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -720,7 +714,7 @@ describe('request interception', function () {
expect(await serverRequest.postBody).toBe('doggo'); expect(await serverRequest.postBody).toBe('doggo');
}); });
it('should amend both post data and method on navigation', async () => { it('should amend both post data and method on navigation', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -734,7 +728,7 @@ describe('request interception', function () {
expect(await serverRequest.postBody).toBe('doggo'); expect(await serverRequest.postBody).toBe('doggo');
}); });
it('should fail if the header value is invalid', async () => { it('should fail if the header value is invalid', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
let error!: Error; let error!: Error;
await page.setRequestInterception(true); await page.setRequestInterception(true);
@ -757,7 +751,7 @@ describe('request interception', function () {
describe('Request.respond', function () { describe('Request.respond', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -779,7 +773,7 @@ describe('request interception', function () {
).toBe('Yo, page!'); ).toBe('Yo, page!');
}); });
it('should work with status code 422', async () => { it('should work with status code 422', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -798,7 +792,7 @@ describe('request interception', function () {
).toBe('Yo, page!'); ).toBe('Yo, page!');
}); });
it('should redirect', async () => { it('should redirect', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -821,7 +815,7 @@ describe('request interception', function () {
expect(response.url()).toBe(server.EMPTY_PAGE); expect(response.url()).toBe(server.EMPTY_PAGE);
}); });
it('should allow mocking multiple headers with same key', async () => { it('should allow mocking multiple headers with same key', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -852,7 +846,7 @@ describe('request interception', function () {
expect(secondCookie?.value).toBe('2'); expect(secondCookie?.value).toBe('2');
}); });
it('should allow mocking binary responses', async () => { it('should allow mocking binary responses', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -876,7 +870,7 @@ describe('request interception', function () {
expect(await img.screenshot()).toBeGolden('mock-binary-response.png'); expect(await img.screenshot()).toBeGolden('mock-binary-response.png');
}); });
it('should stringify intercepted request response headers', async () => { it('should stringify intercepted request response headers', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', request => { page.on('request', request => {
@ -899,7 +893,7 @@ describe('request interception', function () {
).toBe('Yo, page!'); ).toBe('Yo, page!');
}); });
it('should fail if the header value is invalid', async () => { it('should fail if the header value is invalid', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
let error!: Error; let error!: Error;
await page.setRequestInterception(true); await page.setRequestInterception(true);

View File

@ -16,20 +16,12 @@
import expect from 'expect'; import expect from 'expect';
import { import {getTestState, launch} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
launch,
} from './mocha-utils.js';
describe('Screenshots', function () { describe('Screenshots', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Page.screenshot', function () { describe('Page.screenshot', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html'); await page.goto(server.PREFIX + '/grid.html');
@ -37,7 +29,7 @@ describe('Screenshots', function () {
expect(screenshot).toBeGolden('screenshot-sanity.png'); expect(screenshot).toBeGolden('screenshot-sanity.png');
}); });
it('should clip rect', async () => { it('should clip rect', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html'); await page.goto(server.PREFIX + '/grid.html');
@ -52,7 +44,7 @@ describe('Screenshots', function () {
expect(screenshot).toBeGolden('screenshot-clip-rect.png'); expect(screenshot).toBeGolden('screenshot-clip-rect.png');
}); });
it('should use scale for clip', async () => { 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.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html'); await page.goto(server.PREFIX + '/grid.html');
@ -68,7 +60,7 @@ describe('Screenshots', function () {
expect(screenshot).toBeGolden('screenshot-clip-rect-scale2.png'); expect(screenshot).toBeGolden('screenshot-clip-rect-scale2.png');
}); });
it('should get screenshot bigger than the viewport', async () => { 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.setViewport({width: 50, height: 50});
await page.goto(server.PREFIX + '/grid.html'); await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot({ const screenshot = await page.screenshot({
@ -82,7 +74,7 @@ describe('Screenshots', function () {
expect(screenshot).toBeGolden('screenshot-offscreen-clip.png'); expect(screenshot).toBeGolden('screenshot-offscreen-clip.png');
}); });
it('should run in parallel', async () => { it('should run in parallel', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html'); await page.goto(server.PREFIX + '/grid.html');
@ -103,7 +95,7 @@ describe('Screenshots', function () {
expect(screenshots[1]).toBeGolden('grid-cell-1.png'); expect(screenshots[1]).toBeGolden('grid-cell-1.png');
}); });
it('should take fullPage screenshots', async () => { it('should take fullPage screenshots', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html'); await page.goto(server.PREFIX + '/grid.html');
@ -113,7 +105,7 @@ describe('Screenshots', function () {
expect(screenshot).toBeGolden('screenshot-grid-fullpage.png'); expect(screenshot).toBeGolden('screenshot-grid-fullpage.png');
}); });
it('should run in parallel in multiple pages', async () => { it('should run in parallel in multiple pages', async () => {
const {server, context} = getTestState(); const {server, context} = await getTestState();
const N = 2; const N = 2;
const pages = await Promise.all( const pages = await Promise.all(
@ -144,7 +136,7 @@ describe('Screenshots', function () {
); );
}); });
it('should allow transparency', async () => { it('should allow transparency', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setViewport({width: 100, height: 100}); await page.setViewport({width: 100, height: 100});
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -152,7 +144,7 @@ describe('Screenshots', function () {
expect(screenshot).toBeGolden('transparent.png'); expect(screenshot).toBeGolden('transparent.png');
}); });
it('should render white background on jpeg file', async () => { 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.setViewport({width: 100, height: 100});
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -163,7 +155,7 @@ describe('Screenshots', function () {
expect(screenshot).toBeGolden('white.jpg'); expect(screenshot).toBeGolden('white.jpg');
}); });
it('should work with webp', async () => { it('should work with webp', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setViewport({width: 100, height: 100}); await page.setViewport({width: 100, height: 100});
await page.goto(server.PREFIX + '/grid.html'); await page.goto(server.PREFIX + '/grid.html');
@ -174,7 +166,7 @@ describe('Screenshots', function () {
expect(screenshot).toBeInstanceOf(Buffer); expect(screenshot).toBeInstanceOf(Buffer);
}); });
it('should work with odd clip size on Retina displays', async () => { it('should work with odd clip size on Retina displays', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const screenshot = await page.screenshot({ const screenshot = await page.screenshot({
clip: { clip: {
@ -187,7 +179,7 @@ describe('Screenshots', function () {
expect(screenshot).toBeGolden('screenshot-clip-odd-size.png'); expect(screenshot).toBeGolden('screenshot-clip-odd-size.png');
}); });
it('should return base64', async () => { it('should return base64', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html'); await page.goto(server.PREFIX + '/grid.html');
@ -199,7 +191,7 @@ describe('Screenshots', function () {
); );
}); });
it('should work in "fromSurface: false" mode', async () => { 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.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html'); await page.goto(server.PREFIX + '/grid.html');
@ -212,7 +204,7 @@ describe('Screenshots', function () {
describe('ElementHandle.screenshot', function () { describe('ElementHandle.screenshot', function () {
it('should work', async () => { it('should work', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html'); await page.goto(server.PREFIX + '/grid.html');
@ -224,10 +216,10 @@ describe('Screenshots', function () {
expect(screenshot).toBeGolden('screenshot-element-bounding-box.png'); expect(screenshot).toBeGolden('screenshot-element-bounding-box.png');
}); });
it('should work with a null viewport', async () => { it('should work with a null viewport', async () => {
const {defaultBrowserOptions, server} = getTestState(); const {server} = await getTestState({
skipLaunch: true,
});
const {browser, close} = await launch({ const {browser, close} = await launch({
...defaultBrowserOptions,
defaultViewport: null, defaultViewport: null,
}); });
@ -245,7 +237,7 @@ describe('Screenshots', function () {
} }
}); });
it('should take into account padding and border', async () => { 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.setViewport({width: 500, height: 500});
await page.setContent(` await page.setContent(`
@ -264,7 +256,7 @@ describe('Screenshots', function () {
expect(screenshot).toBeGolden('screenshot-element-padding-border.png'); expect(screenshot).toBeGolden('screenshot-element-padding-border.png');
}); });
it('should capture full element when larger than viewport', async () => { it('should capture full element when larger than viewport', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
@ -299,7 +291,7 @@ describe('Screenshots', function () {
).toEqual({w: 500, h: 500}); ).toEqual({w: 500, h: 500});
}); });
it('should scroll element into view', async () => { it('should scroll element into view', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.setContent(` await page.setContent(`
@ -326,7 +318,7 @@ describe('Screenshots', function () {
); );
}); });
it('should work with a rotated element', async () => { it('should work with a rotated element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setViewport({width: 500, height: 500}); await page.setViewport({width: 500, height: 500});
await page.setContent(`<div style="position:absolute; await page.setContent(`<div style="position:absolute;
@ -341,7 +333,7 @@ describe('Screenshots', function () {
expect(screenshot).toBeGolden('screenshot-element-rotate.png'); expect(screenshot).toBeGolden('screenshot-element-rotate.png');
}); });
it('should fail to screenshot a detached element', async () => { it('should fail to screenshot a detached element', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<h1>remove this</h1>'); await page.setContent('<h1>remove this</h1>');
const elementHandle = (await page.$('h1'))!; const elementHandle = (await page.$('h1'))!;
@ -356,7 +348,7 @@ describe('Screenshots', function () {
); );
}); });
it('should not hang with zero width/height element', async () => { 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>'); await page.setContent('<div style="width: 50px; height: 0"></div>');
const div = (await page.$('div'))!; const div = (await page.$('div'))!;
@ -366,7 +358,7 @@ describe('Screenshots', function () {
expect(error.message).toBe('Node has 0 height.'); expect(error.message).toBe('Node has 0 height.');
}); });
it('should work for an element with fractional dimensions', async () => { it('should work for an element with fractional dimensions', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div style="width:48.51px;height:19.8px;border:1px solid black;"></div>' '<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'); expect(screenshot).toBeGolden('screenshot-element-fractional.png');
}); });
it('should work for an element with an offset', async () => { it('should work for an element with an offset', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent( await page.setContent(
'<div style="position:absolute; top: 10.3px; left: 20.4px;width:50.3px;height:20.2px;border:1px solid black;"></div>' '<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 expect from 'expect';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {waitEvent} from './utils.js'; import {waitEvent} from './utils.js';
const FILENAME = __filename.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&'); const FILENAME = __filename.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
describe('Stack trace', function () { describe('Stack trace', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('should work', async () => { it('should work', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const error = (await page const error = (await page
.evaluate(() => { .evaluate(() => {
@ -49,13 +42,13 @@ describe('Stack trace', function () {
expect(error.stack.split('\n at ').slice(0, 2)).toMatchObject({ expect(error.stack.split('\n at ').slice(0, 2)).toMatchObject({
...[ ...[
'Error: Test', '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 () => { it('should work with handles', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const error = (await page const error = (await page
.evaluateHandle(() => { .evaluateHandle(() => {
@ -72,13 +65,13 @@ describe('Stack trace', function () {
expect(error.stack.split('\n at ').slice(0, 2)).toMatchObject({ expect(error.stack.split('\n at ').slice(0, 2)).toMatchObject({
...[ ...[
'Error: Test', '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 () => { it('should work with contiguous evaluation', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const thrower = await page.evaluateHandle(() => { const thrower = await page.evaluateHandle(() => {
return () => { return () => {
@ -100,14 +93,14 @@ describe('Stack trace', function () {
expect(error.stack.split('\n at ').slice(0, 3)).toMatchObject({ expect(error.stack.split('\n at ').slice(0, 3)).toMatchObject({
...[ ...[
'Error: Test', 'Error: Test',
'evaluateHandle (evaluateHandle at Context.<anonymous> (<filename>:71:36), <anonymous>:2:22)', 'evaluateHandle (evaluateHandle at Context.<anonymous> (<filename>:69:36), <anonymous>:2:22)',
'evaluate (evaluate at Context.<anonymous> (<filename>:77:14), <anonymous>:1:12)', 'evaluate (evaluate at Context.<anonymous> (<filename>:75:14), <anonymous>:1:12)',
], ],
}); });
}); });
it('should work with nested function calls', async () => { it('should work with nested function calls', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const error = (await page const error = (await page
.evaluate(() => { .evaluate(() => {
@ -136,17 +129,17 @@ describe('Stack trace', function () {
expect(error.stack.split('\n at ').slice(0, 6)).toMatchObject({ expect(error.stack.split('\n at ').slice(0, 6)).toMatchObject({
...[ ...[
'Error: Test', 'Error: Test',
'a (evaluate at Context.<anonymous> (<filename>:98:14), <anonymous>:2:22)', 'a (evaluate at Context.<anonymous> (<filename>:96:14), <anonymous>:2:22)',
'b (evaluate at Context.<anonymous> (<filename>:98:14), <anonymous>:5:16)', 'b (evaluate at Context.<anonymous> (<filename>:96:14), <anonymous>:5:16)',
'c (evaluate at Context.<anonymous> (<filename>:98:14), <anonymous>:8:16)', 'c (evaluate at Context.<anonymous> (<filename>:96:14), <anonymous>:8:16)',
'd (evaluate at Context.<anonymous> (<filename>:98:14), <anonymous>:11:16)', 'd (evaluate at Context.<anonymous> (<filename>:96:14), <anonymous>:11:16)',
'evaluate (evaluate at Context.<anonymous> (<filename>:98:14), <anonymous>:13:12)', 'evaluate (evaluate at Context.<anonymous> (<filename>:96:14), <anonymous>:13:12)',
], ],
}); });
}); });
it('should work for none error objects', async () => { it('should work for none error objects', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const [error] = await Promise.all([ const [error] = await Promise.all([
waitEvent<Error>(page, 'pageerror'), waitEvent<Error>(page, 'pageerror'),

View File

@ -21,19 +21,12 @@ import {TimeoutError} from 'puppeteer';
import {Page} from 'puppeteer-core/internal/api/Page.js'; import {Page} from 'puppeteer-core/internal/api/Page.js';
import {Target} from 'puppeteer-core/internal/common/Target.js'; import {Target} from 'puppeteer-core/internal/common/Target.js';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {waitEvent} from './utils.js'; import {waitEvent} from './utils.js';
describe('Target', function () { describe('Target', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('Browser.targets should return all of the targets', async () => { 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 // The pages will be the testing page and the original newtab page
const targets = browser.targets(); const targets = browser.targets();
@ -49,7 +42,7 @@ describe('Target', function () {
).toBeTruthy(); ).toBeTruthy();
}); });
it('Browser.pages should return all of the pages', async () => { 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 // The pages will be the testing page
const allPages = await context.pages(); const allPages = await context.pages();
@ -57,7 +50,7 @@ describe('Target', function () {
expect(allPages).toContain(page); expect(allPages).toContain(page);
}); });
it('should contain browser target', async () => { it('should contain browser target', async () => {
const {browser} = getTestState(); const {browser} = await getTestState();
const targets = browser.targets(); const targets = browser.targets();
const browserTarget = targets.find(target => { const browserTarget = targets.find(target => {
@ -66,7 +59,7 @@ describe('Target', function () {
expect(browserTarget).toBeTruthy(); expect(browserTarget).toBeTruthy();
}); });
it('should be able to use the default page in the browser', async () => { 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 // The pages will be the testing page and the original newtab page
const allPages = await browser.pages(); const allPages = await browser.pages();
@ -81,7 +74,7 @@ describe('Target', function () {
expect(await originalPage.$('body')).toBeTruthy(); expect(await originalPage.$('body')).toBeTruthy();
}); });
it('should be able to use async waitForTarget', async () => { 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([ const [otherPage] = await Promise.all([
context context
@ -103,7 +96,7 @@ describe('Target', function () {
expect(page).not.toEqual(otherPage); expect(page).not.toEqual(otherPage);
}); });
it('should report when a new page is created and closed', async () => { 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([ const [otherPage] = await Promise.all([
context context
@ -144,7 +137,7 @@ describe('Target', function () {
expect(allPages).not.toContain(otherPage); expect(allPages).not.toContain(otherPage);
}); });
it('should report when a service worker is created and destroyed', async () => { 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); await page.goto(server.EMPTY_PAGE);
const createdTarget = waitEvent(context, 'targetcreated'); const createdTarget = waitEvent(context, 'targetcreated');
@ -169,7 +162,7 @@ describe('Target', function () {
expect(await destroyedTarget).toBe(await createdTarget); expect(await destroyedTarget).toBe(await createdTarget);
}); });
it('should create a worker from a service worker', async () => { 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'); await page.goto(server.PREFIX + '/serviceworkers/empty/sw.html');
@ -184,7 +177,7 @@ describe('Target', function () {
).toBe('[object ServiceWorkerGlobalScope]'); ).toBe('[object ServiceWorkerGlobalScope]');
}); });
it('should create a worker from a shared worker', async () => { 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.goto(server.EMPTY_PAGE);
await page.evaluate(() => { await page.evaluate(() => {
@ -201,7 +194,7 @@ describe('Target', function () {
).toBe('[object SharedWorkerGlobalScope]'); ).toBe('[object SharedWorkerGlobalScope]');
}); });
it('should report when a target url changes', async () => { 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); await page.goto(server.EMPTY_PAGE);
let changedTarget = waitEvent(context, 'targetchanged'); let changedTarget = waitEvent(context, 'targetchanged');
@ -213,7 +206,7 @@ describe('Target', function () {
expect((await changedTarget).url()).toBe(server.EMPTY_PAGE); expect((await changedTarget).url()).toBe(server.EMPTY_PAGE);
}); });
it('should not report uninitialized pages', async () => { it('should not report uninitialized pages', async () => {
const {context} = getTestState(); const {context} = await getTestState();
let targetChanged = false; let targetChanged = false;
const listener = () => { const listener = () => {
@ -238,7 +231,7 @@ describe('Target', function () {
context.off('targetchanged', listener); context.off('targetchanged', listener);
}); });
it('should not crash while redirecting if original request was missed', async () => { 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; let serverResponse!: ServerResponse;
server.setRoute('/one-style.css', (_req, res) => { server.setRoute('/one-style.css', (_req, res) => {
@ -265,7 +258,7 @@ describe('Target', function () {
await newPage.close(); await newPage.close();
}); });
it('should have an opener', async () => { it('should have an opener', async () => {
const {page, server, context} = getTestState(); const {page, server, context} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const [createdTarget] = await Promise.all([ const [createdTarget] = await Promise.all([
@ -281,7 +274,7 @@ describe('Target', function () {
describe('Browser.waitForTarget', () => { describe('Browser.waitForTarget', () => {
it('should wait for a target', async () => { it('should wait for a target', async () => {
const {browser, server} = getTestState(); const {browser, server} = await getTestState();
let resolved = false; let resolved = false;
const targetPromise = browser.waitForTarget(target => { const targetPromise = browser.waitForTarget(target => {
@ -315,7 +308,7 @@ describe('Target', function () {
await page.close(); await page.close();
}); });
it('should timeout waiting for a non-existent target', async () => { it('should timeout waiting for a non-existent target', async () => {
const {browser, server} = getTestState(); const {browser, server} = await getTestState();
let error!: Error; let error!: Error;
await browser await browser

View File

@ -17,18 +17,11 @@
import expect from 'expect'; import expect from 'expect';
import {KnownDevices, BoundingBox} from 'puppeteer'; import {KnownDevices, BoundingBox} from 'puppeteer';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
describe('Touchscreen', function () { describe('Touchscreen', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('should tap the button', async () => { it('should tap the button', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const iPhone = KnownDevices['iPhone 6']!; const iPhone = KnownDevices['iPhone 6']!;
await page.emulate(iPhone); await page.emulate(iPhone);
await page.goto(server.PREFIX + '/input/button.html'); await page.goto(server.PREFIX + '/input/button.html');
@ -41,7 +34,7 @@ describe('Touchscreen', function () {
}); });
it('should report touches', async () => { it('should report touches', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const iPhone = KnownDevices['iPhone 6']!; const iPhone = KnownDevices['iPhone 6']!;
await page.emulate(iPhone); await page.emulate(iPhone);
await page.goto(server.PREFIX + '/input/touches.html'); await page.goto(server.PREFIX + '/input/touches.html');
@ -55,7 +48,7 @@ describe('Touchscreen', function () {
}); });
it('should report touchMove', async () => { it('should report touchMove', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const iPhone = KnownDevices['iPhone 6']!; const iPhone = KnownDevices['iPhone 6']!;
await page.emulate(iPhone); await page.emulate(iPhone);
await page.goto(server.PREFIX + '/input/touches-move.html'); await page.goto(server.PREFIX + '/input/touches-move.html');

View File

@ -19,7 +19,7 @@ import path from 'path';
import expect from 'expect'; import expect from 'expect';
import {getTestState, launch} from './mocha-utils.js'; import {launch} from './mocha-utils.js';
describe('Tracing', function () { describe('Tracing', function () {
let outputFile!: string; let outputFile!: string;
@ -29,8 +29,7 @@ describe('Tracing', function () {
* individual test, which isn't the default behaviour of getTestState() * individual test, which isn't the default behaviour of getTestState()
*/ */
beforeEach(async () => { beforeEach(async () => {
const {defaultBrowserOptions} = getTestState(); testState = await launch({});
testState = await launch(defaultBrowserOptions);
outputFile = path.join(__dirname, 'trace.json'); outputFile = path.join(__dirname, 'trace.json');
}); });

View File

@ -18,21 +18,13 @@ import expect from 'expect';
import {TimeoutError, ElementHandle} from 'puppeteer'; import {TimeoutError, ElementHandle} from 'puppeteer';
import {isErrorLike} from 'puppeteer-core/internal/util/ErrorLike.js'; import {isErrorLike} from 'puppeteer-core/internal/util/ErrorLike.js';
import { import {createTimeout, getTestState} from './mocha-utils.js';
createTimeout,
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {attachFrame, detachFrame} from './utils.js'; import {attachFrame, detachFrame} from './utils.js';
describe('waittask specs', function () { describe('waittask specs', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Frame.waitForFunction', function () { describe('Frame.waitForFunction', function () {
it('should accept a string', async () => { it('should accept a string', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const watchdog = page.waitForFunction('self.__FOO === 1'); const watchdog = page.waitForFunction('self.__FOO === 1');
await page.evaluate(() => { await page.evaluate(() => {
@ -41,7 +33,7 @@ describe('waittask specs', function () {
await watchdog; await watchdog;
}); });
it('should work when resolved right before execution context disposal', async () => { it('should work when resolved right before execution context disposal', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.evaluateOnNewDocument(() => { await page.evaluateOnNewDocument(() => {
return ((globalThis as any).__RELOADED = true); return ((globalThis as any).__RELOADED = true);
@ -55,7 +47,7 @@ describe('waittask specs', function () {
}); });
}); });
it('should poll on interval', async () => { it('should poll on interval', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const startTime = Date.now(); const startTime = Date.now();
const polling = 100; const polling = 100;
const watchdog = page.waitForFunction( const watchdog = page.waitForFunction(
@ -73,7 +65,7 @@ describe('waittask specs', function () {
expect(Date.now() - startTime).not.toBeLessThan(polling / 2); expect(Date.now() - startTime).not.toBeLessThan(polling / 2);
}); });
it('should poll on mutation', async () => { it('should poll on mutation', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let success = false; let success = false;
const watchdog = page const watchdog = page
@ -98,7 +90,7 @@ describe('waittask specs', function () {
await watchdog; await watchdog;
}); });
it('should poll on mutation async', async () => { it('should poll on mutation async', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let success = false; let success = false;
const watchdog = page const watchdog = page
@ -123,7 +115,7 @@ describe('waittask specs', function () {
await watchdog; await watchdog;
}); });
it('should poll on raf', async () => { it('should poll on raf', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const watchdog = page.waitForFunction( const watchdog = page.waitForFunction(
() => { () => {
@ -139,7 +131,7 @@ describe('waittask specs', function () {
await watchdog; await watchdog;
}); });
it('should poll on raf async', async () => { it('should poll on raf async', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const watchdog = page.waitForFunction( const watchdog = page.waitForFunction(
async () => { async () => {
@ -155,7 +147,7 @@ describe('waittask specs', function () {
await watchdog; await watchdog;
}); });
it('should work with strict CSP policy', async () => { 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); server.setCSP('/empty.html', 'script-src ' + server.PREFIX);
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -180,7 +172,7 @@ describe('waittask specs', function () {
expect(error).toBeUndefined(); expect(error).toBeUndefined();
}); });
it('should throw negative polling interval', async () => { it('should throw negative polling interval', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
try { try {
@ -200,7 +192,7 @@ describe('waittask specs', function () {
); );
}); });
it('should return the success value as a JSHandle', async () => { it('should return the success value as a JSHandle', async () => {
const {page} = getTestState(); const {page} = await getTestState();
expect( expect(
await ( await (
@ -211,7 +203,7 @@ describe('waittask specs', function () {
).toBe(5); ).toBe(5);
}); });
it('should return the window as a success value', async () => { it('should return the window as a success value', async () => {
const {page} = getTestState(); const {page} = await getTestState();
expect( expect(
await page.waitForFunction(() => { await page.waitForFunction(() => {
@ -220,7 +212,7 @@ describe('waittask specs', function () {
).toBeTruthy(); ).toBeTruthy();
}); });
it('should accept ElementHandle arguments', async () => { it('should accept ElementHandle arguments', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent('<div></div>'); await page.setContent('<div></div>');
const div = (await page.$('div'))!; const div = (await page.$('div'))!;
@ -243,7 +235,7 @@ describe('waittask specs', function () {
await waitForFunction; await waitForFunction;
}); });
it('should respect timeout', async () => { it('should respect timeout', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page await page
@ -261,7 +253,7 @@ describe('waittask specs', function () {
expect(error?.message).toContain('Waiting failed: 10ms exceeded'); expect(error?.message).toContain('Waiting failed: 10ms exceeded');
}); });
it('should respect default timeout', async () => { it('should respect default timeout', async () => {
const {page} = getTestState(); const {page} = await getTestState();
page.setDefaultTimeout(1); page.setDefaultTimeout(1);
let error!: Error; let error!: Error;
@ -276,7 +268,7 @@ describe('waittask specs', function () {
expect(error?.message).toContain('Waiting failed: 1ms exceeded'); expect(error?.message).toContain('Waiting failed: 1ms exceeded');
}); });
it('should disable timeout when its set to 0', async () => { it('should disable timeout when its set to 0', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const watchdog = page.waitForFunction( const watchdog = page.waitForFunction(
() => { () => {
@ -295,7 +287,7 @@ describe('waittask specs', function () {
await watchdog; await watchdog;
}); });
it('should survive cross-process navigation', async () => { it('should survive cross-process navigation', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
let fooFound = false; let fooFound = false;
const waitForFunction = page const waitForFunction = page
@ -318,7 +310,7 @@ describe('waittask specs', function () {
expect(fooFound).toBe(true); expect(fooFound).toBe(true);
}); });
it('should survive navigations', async () => { it('should survive navigations', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
const watchdog = page.waitForFunction(() => { const watchdog = page.waitForFunction(() => {
return (globalThis as any).__done; return (globalThis as any).__done;
@ -331,7 +323,7 @@ describe('waittask specs', function () {
await watchdog; await watchdog;
}); });
it('should be cancellable', async () => { it('should be cancellable', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const abortController = new AbortController(); const abortController = new AbortController();
@ -350,7 +342,7 @@ describe('waittask specs', function () {
describe('Page.waitForTimeout', () => { describe('Page.waitForTimeout', () => {
it('waits for the given timeout before resolving', async () => { it('waits for the given timeout before resolving', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const startTime = Date.now(); const startTime = Date.now();
await page.waitForTimeout(1000); await page.waitForTimeout(1000);
@ -366,7 +358,7 @@ describe('waittask specs', function () {
describe('Frame.waitForTimeout', () => { describe('Frame.waitForTimeout', () => {
it('waits for the given timeout before resolving', async () => { it('waits for the given timeout before resolving', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const frame = page.mainFrame(); const frame = page.mainFrame();
const startTime = Date.now(); const startTime = Date.now();
@ -387,7 +379,7 @@ describe('waittask specs', function () {
}; };
it('should immediately resolve promise if node exists', async () => { 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.goto(server.EMPTY_PAGE);
const frame = page.mainFrame(); const frame = page.mainFrame();
@ -397,7 +389,7 @@ describe('waittask specs', function () {
}); });
it('should be cancellable', async () => { it('should be cancellable', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const abortController = new AbortController(); const abortController = new AbortController();
@ -409,7 +401,7 @@ describe('waittask specs', function () {
}); });
it('should work with removed MutationObserver', async () => { it('should work with removed MutationObserver', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.evaluate(() => { await page.evaluate(() => {
// @ts-expect-error We want to remove it for the test. // @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 () => { it('should resolve promise when node is added', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const frame = page.mainFrame(); const frame = page.mainFrame();
@ -440,7 +432,7 @@ describe('waittask specs', function () {
}); });
it('should work when node is added through innerHTML', async () => { 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); await page.goto(server.EMPTY_PAGE);
const watchdog = page.waitForSelector('h3 div'); const watchdog = page.waitForSelector('h3 div');
@ -453,7 +445,7 @@ describe('waittask specs', function () {
}); });
it('Page.waitForSelector is shortcut for main frame', async () => { 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 page.goto(server.EMPTY_PAGE);
await attachFrame(page, 'frame1', 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 () => { 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, 'frame1', server.EMPTY_PAGE);
await attachFrame(page, 'frame2', 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 () => { it('should throw when frame is detached', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await attachFrame(page, 'frame1', server.EMPTY_PAGE); await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = page.frames()[1]!; const frame = page.frames()[1]!;
@ -496,7 +488,7 @@ describe('waittask specs', function () {
); );
}); });
it('should survive cross-process navigation', async () => { it('should survive cross-process navigation', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
let boxFound = false; let boxFound = false;
const waitForSelector = page.waitForSelector('.box').then(() => { const waitForSelector = page.waitForSelector('.box').then(() => {
@ -511,7 +503,7 @@ describe('waittask specs', function () {
expect(boxFound).toBe(true); expect(boxFound).toBe(true);
}); });
it('should wait for element to be visible (display)', async () => { it('should wait for element to be visible (display)', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const promise = page.waitForSelector('div', {visible: true}); const promise = page.waitForSelector('div', {visible: true});
await page.setContent('<div style="display: none">text</div>'); await page.setContent('<div style="display: none">text</div>');
@ -527,7 +519,7 @@ describe('waittask specs', function () {
await expect(promise).resolves.toBeTruthy(); await expect(promise).resolves.toBeTruthy();
}); });
it('should wait for element to be visible (visibility)', async () => { it('should wait for element to be visible (visibility)', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const promise = page.waitForSelector('div', {visible: true}); const promise = page.waitForSelector('div', {visible: true});
await page.setContent('<div style="visibility: hidden">text</div>'); await page.setContent('<div style="visibility: hidden">text</div>');
@ -549,7 +541,7 @@ describe('waittask specs', function () {
await expect(promise).resolves.toBeTruthy(); await expect(promise).resolves.toBeTruthy();
}); });
it('should wait for element to be visible (bounding box)', async () => { 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}); const promise = page.waitForSelector('div', {visible: true});
await page.setContent('<div style="width: 0">text</div>'); await page.setContent('<div style="width: 0">text</div>');
@ -572,7 +564,7 @@ describe('waittask specs', function () {
await expect(promise).resolves.toBeTruthy(); await expect(promise).resolves.toBeTruthy();
}); });
it('should wait for element to be visible recursively', async () => { it('should wait for element to be visible recursively', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const promise = page.waitForSelector('div#inner', { const promise = page.waitForSelector('div#inner', {
visible: true, visible: true,
@ -598,7 +590,7 @@ describe('waittask specs', function () {
await expect(promise).resolves.toBeTruthy(); await expect(promise).resolves.toBeTruthy();
}); });
it('should wait for element to be hidden (visibility)', async () => { it('should wait for element to be hidden (visibility)', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const promise = page.waitForSelector('div', {hidden: true}); const promise = page.waitForSelector('div', {hidden: true});
await page.setContent(`<div style='display: block;'>text</div>`); await page.setContent(`<div style='display: block;'>text</div>`);
@ -614,7 +606,7 @@ describe('waittask specs', function () {
await expect(promise).resolves.toBeTruthy(); await expect(promise).resolves.toBeTruthy();
}); });
it('should wait for element to be hidden (display)', async () => { it('should wait for element to be hidden (display)', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const promise = page.waitForSelector('div', {hidden: true}); const promise = page.waitForSelector('div', {hidden: true});
await page.setContent(`<div style='display: block;'>text</div>`); await page.setContent(`<div style='display: block;'>text</div>`);
@ -630,7 +622,7 @@ describe('waittask specs', function () {
await expect(promise).resolves.toBeTruthy(); await expect(promise).resolves.toBeTruthy();
}); });
it('should wait for element to be hidden (bounding box)', async () => { 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}); const promise = page.waitForSelector('div', {hidden: true});
await page.setContent('<div>text</div>'); await page.setContent('<div>text</div>');
@ -646,7 +638,7 @@ describe('waittask specs', function () {
await expect(promise).resolves.toBeTruthy(); await expect(promise).resolves.toBeTruthy();
}); });
it('should wait for element to be hidden (removal)', async () => { it('should wait for element to be hidden (removal)', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const promise = page.waitForSelector('div', {hidden: true}); const promise = page.waitForSelector('div', {hidden: true});
await page.setContent(`<div>text</div>`); await page.setContent(`<div>text</div>`);
@ -662,7 +654,7 @@ describe('waittask specs', function () {
await expect(promise).resolves.toBeFalsy(); await expect(promise).resolves.toBeFalsy();
}); });
it('should return null if waiting to hide non-existing element', async () => { 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', { const handle = await page.waitForSelector('non-existing', {
hidden: true, hidden: true,
@ -670,7 +662,7 @@ describe('waittask specs', function () {
expect(handle).toBe(null); expect(handle).toBe(null);
}); });
it('should respect timeout', async () => { it('should respect timeout', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page.waitForSelector('div', {timeout: 10}).catch(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 () => { 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>`); await page.setContent(`<div>text</div>`);
let error!: Error; let error!: Error;
@ -698,7 +690,7 @@ describe('waittask specs', function () {
}); });
it('should respond to node attribute mutation', async () => { it('should respond to node attribute mutation', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let divFound = false; let divFound = false;
const waitForSelector = page.waitForSelector('.zombo').then(() => { const waitForSelector = page.waitForSelector('.zombo').then(() => {
@ -712,7 +704,7 @@ describe('waittask specs', function () {
expect(await waitForSelector).toBe(true); expect(await waitForSelector).toBe(true);
}); });
it('should return the element handle', async () => { it('should return the element handle', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const waitForSelector = page.waitForSelector('.zombo'); const waitForSelector = page.waitForSelector('.zombo');
await page.setContent(`<div class='zombo'>anything</div>`); await page.setContent(`<div class='zombo'>anything</div>`);
@ -723,7 +715,7 @@ describe('waittask specs', function () {
).toBe('anything'); ).toBe('anything');
}); });
it('should have correct stack trace for timeout', async () => { it('should have correct stack trace for timeout', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page.waitForSelector('.zombo', {timeout: 10}).catch(error_ => { await page.waitForSelector('.zombo', {timeout: 10}).catch(error_ => {
@ -743,7 +735,7 @@ describe('waittask specs', function () {
}; };
it('should support some fancy xpath', async () => { 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>`); await page.setContent(`<p>red herring</p><p>hello world </p>`);
const waitForXPath = page.waitForXPath( const waitForXPath = page.waitForXPath(
@ -756,7 +748,7 @@ describe('waittask specs', function () {
).toBe('hello world '); ).toBe('hello world ');
}); });
it('should respect timeout', async () => { it('should respect timeout', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let error!: Error; let error!: Error;
await page.waitForXPath('//div', {timeout: 10}).catch(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'); expect(error?.message).toContain('Waiting failed: 10ms exceeded');
}); });
it('should run in specified frame', async () => { 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, 'frame1', server.EMPTY_PAGE);
await attachFrame(page, 'frame2', server.EMPTY_PAGE); await attachFrame(page, 'frame2', server.EMPTY_PAGE);
@ -779,7 +771,7 @@ describe('waittask specs', function () {
expect(eHandle?.frame).toBe(frame2); expect(eHandle?.frame).toBe(frame2);
}); });
it('should throw when frame is detached', async () => { it('should throw when frame is detached', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await attachFrame(page, 'frame1', server.EMPTY_PAGE); await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = page.frames()[1]!; const frame = page.frames()[1]!;
@ -797,7 +789,7 @@ describe('waittask specs', function () {
); );
}); });
it('hidden should wait for display: none', async () => { it('hidden should wait for display: none', async () => {
const {page} = getTestState(); const {page} = await getTestState();
let divHidden = false; let divHidden = false;
await page.setContent(`<div style='display: block;'>text</div>`); await page.setContent(`<div style='display: block;'>text</div>`);
@ -817,14 +809,14 @@ describe('waittask specs', function () {
expect(divHidden).toBe(true); expect(divHidden).toBe(true);
}); });
it('hidden should return null if the element is not found', async () => { 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}); const waitForXPath = await page.waitForXPath('//div', {hidden: true});
expect(waitForXPath).toBe(null); expect(waitForXPath).toBe(null);
}); });
it('hidden should return an empty element handle if the element is found', async () => { 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>`); await page.setContent(`<div style='display: none;'>text</div>`);
@ -833,7 +825,7 @@ describe('waittask specs', function () {
expect(waitForXPath).toBeInstanceOf(ElementHandle); expect(waitForXPath).toBeInstanceOf(ElementHandle);
}); });
it('should return the element handle', async () => { it('should return the element handle', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const waitForXPath = page.waitForXPath('//*[@class="zombo"]'); const waitForXPath = page.waitForXPath('//*[@class="zombo"]');
await page.setContent(`<div class='zombo'>anything</div>`); await page.setContent(`<div class='zombo'>anything</div>`);
@ -844,7 +836,7 @@ describe('waittask specs', function () {
).toBe('anything'); ).toBe('anything');
}); });
it('should allow you to select a text node', async () => { it('should allow you to select a text node', async () => {
const {page} = getTestState(); const {page} = await getTestState();
await page.setContent(`<div>some text</div>`); await page.setContent(`<div>some text</div>`);
const text = await page.waitForXPath('//div/text()'); const text = await page.waitForXPath('//div/text()');
@ -853,7 +845,7 @@ describe('waittask specs', function () {
); );
}); });
it('should allow you to select an element with single slash', async () => { 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>`); await page.setContent(`<div>some text</div>`);
const waitForXPath = page.waitForXPath('/html/body/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 {ConsoleMessage} from 'puppeteer-core/internal/common/ConsoleMessage.js';
import {WebWorker} from 'puppeteer-core/internal/common/WebWorker.js'; import {WebWorker} from 'puppeteer-core/internal/common/WebWorker.js';
import { import {getTestState} from './mocha-utils.js';
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {waitEvent} from './utils.js'; import {waitEvent} from './utils.js';
describe('Workers', function () { describe('Workers', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
it('Page.workers', async () => { it('Page.workers', async () => {
const {page, server} = getTestState(); const {page, server} = await getTestState();
await Promise.all([ await Promise.all([
waitEvent(page, 'workercreated'), waitEvent(page, 'workercreated'),
@ -48,7 +42,7 @@ describe('Workers', function () {
expect(page.workers()).toHaveLength(0); expect(page.workers()).toHaveLength(0);
}); });
it('should emit created and destroyed events', async () => { it('should emit created and destroyed events', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const workerCreatedPromise = waitEvent<WebWorker>(page, 'workercreated'); const workerCreatedPromise = waitEvent<WebWorker>(page, 'workercreated');
const workerObj = await page.evaluateHandle(() => { const workerObj = await page.evaluateHandle(() => {
@ -69,7 +63,7 @@ describe('Workers', function () {
expect(error.message).toContain('Most likely the worker has been closed.'); expect(error.message).toContain('Most likely the worker has been closed.');
}); });
it('should report console logs', async () => { it('should report console logs', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const [message] = await Promise.all([ const [message] = await Promise.all([
waitEvent(page, 'console'), waitEvent(page, 'console'),
@ -85,7 +79,7 @@ describe('Workers', function () {
}); });
}); });
it('should have JSHandles for console logs', async () => { it('should have JSHandles for console logs', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const logPromise = waitEvent<ConsoleMessage>(page, 'console'); const logPromise = waitEvent<ConsoleMessage>(page, 'console');
await page.evaluate(() => { await page.evaluate(() => {
@ -99,7 +93,7 @@ describe('Workers', function () {
); );
}); });
it('should have an execution context', async () => { it('should have an execution context', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const workerCreatedPromise = waitEvent<WebWorker>(page, 'workercreated'); const workerCreatedPromise = waitEvent<WebWorker>(page, 'workercreated');
await page.evaluate(() => { await page.evaluate(() => {
@ -109,7 +103,7 @@ describe('Workers', function () {
expect(await (await worker.executionContext()).evaluate('1+1')).toBe(2); expect(await (await worker.executionContext()).evaluate('1+1')).toBe(2);
}); });
it('should report errors', async () => { it('should report errors', async () => {
const {page} = getTestState(); const {page} = await getTestState();
const errorPromise = waitEvent<Error>(page, 'pageerror'); const errorPromise = waitEvent<Error>(page, 'pageerror');
await page.evaluate(() => { await page.evaluate(() => {