chore: use Google's TS style guide's format config (#8542)

This commit is contained in:
jrandolf 2022-06-22 15:25:44 +02:00 committed by GitHub
parent 3744c2f584
commit 84712cbc28
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
122 changed files with 2891 additions and 2962 deletions

1
.prettierrc.cjs Normal file
View File

@ -0,0 +1 @@
module.exports = require('gts/.prettierrc.json');

View File

@ -218,7 +218,7 @@ Puppeteer creates its own browser user profile which it **cleans up on every run
This is also handy when debugging code in `page.evaluate()`: This is also handy when debugging code in `page.evaluate()`:
```js ```js
page.on('console', (msg) => console.log('PAGE LOG:', msg.text())); page.on('console', msg => console.log('PAGE LOG:', msg.text()));
await page.evaluate(() => console.log(`url is ${location.href}`)); await page.evaluate(() => console.log(`url is ${location.href}`));
``` ```

View File

@ -515,7 +515,7 @@ const puppeteer = require('puppeteer');
], ],
}); });
const backgroundPageTarget = await browser.waitForTarget( const backgroundPageTarget = await browser.waitForTarget(
(target) => target.type() === 'background_page' target => target.type() === 'background_page'
); );
const backgroundPage = await backgroundPageTarget.page(); const backgroundPage = await backgroundPageTarget.page();
// Test the background page as you would any other page. // Test the background page as you would any other page.
@ -1003,7 +1003,7 @@ An example of finding a target for a page opened via `window.open`:
```js ```js
await page.evaluate(() => window.open('https://www.example.com/')); await page.evaluate(() => window.open('https://www.example.com/'));
const newWindowTarget = await browser.waitForTarget( const newWindowTarget = await browser.waitForTarget(
(target) => target.url() === 'https://www.example.com/' target => target.url() === 'https://www.example.com/'
); );
``` ```
@ -1155,7 +1155,7 @@ An example of finding a target for a page opened via `window.open`:
```js ```js
await page.evaluate(() => window.open('https://www.example.com/')); await page.evaluate(() => window.open('https://www.example.com/'));
const newWindowTarget = await browserContext.waitForTarget( const newWindowTarget = await browserContext.waitForTarget(
(target) => target.url() === 'https://www.example.com/' target => target.url() === 'https://www.example.com/'
); );
``` ```
@ -1215,7 +1215,7 @@ The arguments passed into `console.log` appear as arguments on the event handler
An example of handling `console` event: An example of handling `console` event:
```js ```js
page.on('console', (msg) => { page.on('console', msg => {
for (let i = 0; i < msg.args().length; ++i) for (let i = 0; i < msg.args().length; ++i)
console.log(`${i}: ${msg.args()[i]}`); console.log(`${i}: ${msg.args()[i]}`);
}); });
@ -1286,14 +1286,14 @@ Emitted when the page opens a new tab or window.
```js ```js
const [popup] = await Promise.all([ const [popup] = await Promise.all([
new Promise((resolve) => page.once('popup', resolve)), new Promise(resolve => page.once('popup', resolve)),
page.click('a[target=_blank]'), page.click('a[target=_blank]'),
]); ]);
``` ```
```js ```js
const [popup] = await Promise.all([ const [popup] = await Promise.all([
new Promise((resolve) => page.once('popup', resolve)), new Promise(resolve => page.once('popup', resolve)),
page.evaluate(() => window.open('https://example.com')), page.evaluate(() => window.open('https://example.com')),
]); ]);
``` ```
@ -1369,12 +1369,12 @@ If `pageFunction` returns a [Promise], then `page.$$eval` would wait for the pro
Examples: Examples:
```js ```js
const divCount = await page.$$eval('div', (divs) => divs.length); const divCount = await page.$$eval('div', divs => divs.length);
``` ```
```js ```js
const options = await page.$$eval('div > span.options', (options) => const options = await page.$$eval('div > span.options', options =>
options.map((option) => option.textContent) options.map(option => option.textContent)
); );
``` ```
@ -1392,9 +1392,9 @@ If `pageFunction` returns a [Promise], then `page.$eval` would wait for the prom
Examples: Examples:
```js ```js
const searchValue = await page.$eval('#search', (el) => el.value); const searchValue = await page.$eval('#search', el => el.value);
const preloadHref = await page.$eval('link[rel=preload]', (el) => el.href); const preloadHref = await page.$eval('link[rel=preload]', el => el.href);
const html = await page.$eval('.main-container', (e) => e.outerHTML); const html = await page.$eval('.main-container', e => e.outerHTML);
``` ```
Shortcut for [page.mainFrame().$eval(selector, pageFunction)](#frameevalselector-pagefunction-args). Shortcut for [page.mainFrame().$eval(selector, pageFunction)](#frameevalselector-pagefunction-args).
@ -1799,7 +1799,7 @@ If the function passed to the `page.evaluate` returns a non-[Serializable] value
Passing arguments to `pageFunction`: Passing arguments to `pageFunction`:
```js ```js
const result = await page.evaluate((x) => { const result = await page.evaluate(x => {
return Promise.resolve(8 * x); return Promise.resolve(8 * x);
}, 7); }, 7);
console.log(result); // prints "56" console.log(result); // prints "56"
@ -1817,7 +1817,7 @@ console.log(await page.evaluate(`1 + ${x}`)); // prints "11"
```js ```js
const bodyHandle = await page.$('body'); const bodyHandle = await page.$('body');
const html = await page.evaluate((body) => body.innerHTML, bodyHandle); const html = await page.evaluate(body => body.innerHTML, bodyHandle);
await bodyHandle.dispose(); await bodyHandle.dispose();
``` ```
@ -1843,10 +1843,7 @@ const aHandle = await page.evaluateHandle('document'); // Handle for the 'docume
```js ```js
const aHandle = await page.evaluateHandle(() => document.body); const aHandle = await page.evaluateHandle(() => document.body);
const resultHandle = await page.evaluateHandle( const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);
(body) => body.innerHTML,
aHandle
);
console.log(await resultHandle.jsonValue()); console.log(await resultHandle.jsonValue());
await resultHandle.dispose(); await resultHandle.dispose();
``` ```
@ -1915,8 +1912,8 @@ const crypto = require('crypto');
(async () => { (async () => {
const browser = await puppeteer.launch(); const browser = await puppeteer.launch();
const page = await browser.newPage(); const page = await browser.newPage();
page.on('console', (msg) => console.log(msg.text())); page.on('console', msg => console.log(msg.text()));
await page.exposeFunction('md5', (text) => await page.exposeFunction('md5', text =>
crypto.createHash('md5').update(text).digest('hex') crypto.createHash('md5').update(text).digest('hex')
); );
await page.evaluate(async () => { await page.evaluate(async () => {
@ -1938,8 +1935,8 @@ const fs = require('fs');
(async () => { (async () => {
const browser = await puppeteer.launch(); const browser = await puppeteer.launch();
const page = await browser.newPage(); const page = await browser.newPage();
page.on('console', (msg) => console.log(msg.text())); page.on('console', msg => console.log(msg.text()));
await page.exposeFunction('readfile', async (filePath) => { await page.exposeFunction('readfile', async filePath => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err, text) => { fs.readFile(filePath, 'utf8', (err, text) => {
if (err) reject(err); if (err) reject(err);
@ -2180,7 +2177,7 @@ const mapPrototype = await page.evaluateHandle(() => Map.prototype);
// Query all map instances into an array // Query all map instances into an array
const mapInstances = await page.queryObjects(mapPrototype); const mapInstances = await page.queryObjects(mapPrototype);
// Count amount of map objects in heap // Count amount of map objects in heap
const count = await page.evaluate((maps) => maps.length, mapInstances); const count = await page.evaluate(maps => maps.length, mapInstances);
await mapInstances.dispose(); await mapInstances.dispose();
await mapPrototype.dispose(); await mapPrototype.dispose();
``` ```
@ -2380,7 +2377,7 @@ const puppeteer = require('puppeteer');
const browser = await puppeteer.launch(); const browser = await puppeteer.launch();
const page = await browser.newPage(); const page = await browser.newPage();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (interceptedRequest) => { page.on('request', interceptedRequest => {
if (interceptedRequest.isInterceptResolutionHandled()) return; if (interceptedRequest.isInterceptResolutionHandled()) return;
if ( if (
interceptedRequest.url().endsWith('.png') || interceptedRequest.url().endsWith('.png') ||
@ -2411,7 +2408,7 @@ This example demonstrates two synchronous handlers working together:
/* /*
This first handler will succeed in calling request.continue because the request interception has never been resolved. This first handler will succeed in calling request.continue because the request interception has never been resolved.
*/ */
page.on('request', (interceptedRequest) => { page.on('request', interceptedRequest => {
if (interceptedRequest.isInterceptResolutionHandled()) return; if (interceptedRequest.isInterceptResolutionHandled()) return;
interceptedRequest.continue(); interceptedRequest.continue();
}); });
@ -2420,7 +2417,7 @@ page.on('request', (interceptedRequest) => {
This second handler will return before calling request.abort because request.continue was already This second handler will return before calling request.abort because request.continue was already
called by the first handler. called by the first handler.
*/ */
page.on('request', (interceptedRequest) => { page.on('request', interceptedRequest => {
if (interceptedRequest.isInterceptResolutionHandled()) return; if (interceptedRequest.isInterceptResolutionHandled()) return;
interceptedRequest.abort(); interceptedRequest.abort();
}); });
@ -2432,12 +2429,12 @@ This example demonstrates asynchronous handlers working together:
/* /*
This first handler will succeed in calling request.continue because the request interception has never been resolved. This first handler will succeed in calling request.continue because the request interception has never been resolved.
*/ */
page.on('request', (interceptedRequest) => { page.on('request', interceptedRequest => {
// The interception has not been handled yet. Control will pass through this guard. // The interception has not been handled yet. Control will pass through this guard.
if (interceptedRequest.isInterceptResolutionHandled()) return; if (interceptedRequest.isInterceptResolutionHandled()) return;
// It is not strictly necessary to return a promise, but doing so will allow Puppeteer to await this handler. // It is not strictly necessary to return a promise, but doing so will allow Puppeteer to await this handler.
return new Promise((resolve) => { return new Promise(resolve => {
// Continue after 500ms // Continue after 500ms
setTimeout(() => { setTimeout(() => {
// Inside, check synchronously to verify that the intercept wasn't handled already. // Inside, check synchronously to verify that the intercept wasn't handled already.
@ -2451,7 +2448,7 @@ page.on('request', (interceptedRequest) => {
}, 500); }, 500);
}); });
}); });
page.on('request', async (interceptedRequest) => { page.on('request', async interceptedRequest => {
// The interception has not been handled yet. Control will pass through this guard. // The interception has not been handled yet. Control will pass through this guard.
if (interceptedRequest.isInterceptResolutionHandled()) return; if (interceptedRequest.isInterceptResolutionHandled()) return;
@ -2471,13 +2468,13 @@ Here is the example above rewritten using `request.interceptResolutionState`
/* /*
This first handler will succeed in calling request.continue because the request interception has never been resolved. This first handler will succeed in calling request.continue because the request interception has never been resolved.
*/ */
page.on('request', (interceptedRequest) => { page.on('request', interceptedRequest => {
// The interception has not been handled yet. Control will pass through this guard. // The interception has not been handled yet. Control will pass through this guard.
const {action} = interceptedRequest.interceptResolutionState(); const {action} = interceptedRequest.interceptResolutionState();
if (action === InterceptResolutionAction.AlreadyHandled) return; if (action === InterceptResolutionAction.AlreadyHandled) return;
// It is not strictly necessary to return a promise, but doing so will allow Puppeteer to await this handler. // It is not strictly necessary to return a promise, but doing so will allow Puppeteer to await this handler.
return new Promise((resolve) => { return new Promise(resolve => {
// Continue after 500ms // Continue after 500ms
setTimeout(() => { setTimeout(() => {
// Inside, check synchronously to verify that the intercept wasn't handled already. // Inside, check synchronously to verify that the intercept wasn't handled already.
@ -2492,7 +2489,7 @@ page.on('request', (interceptedRequest) => {
}, 500); }, 500);
}); });
}); });
page.on('request', async (interceptedRequest) => { page.on('request', async interceptedRequest => {
// The interception has not been handled yet. Control will pass through this guard. // The interception has not been handled yet. Control will pass through this guard.
if ( if (
interceptedRequest.interceptResolutionState().action === interceptedRequest.interceptResolutionState().action ===
@ -2534,13 +2531,13 @@ In this example, Legacy Mode prevails and the request is aborted immediately bec
```ts ```ts
// Final outcome: immediate abort() // Final outcome: immediate abort()
page.setRequestInterception(true); page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
// Legacy Mode: interception is aborted immediately. // Legacy Mode: interception is aborted immediately.
request.abort('failed'); request.abort('failed');
}); });
page.on('request', (request) => { page.on('request', request => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
// Control will never reach this point because the request was already aborted in Legacy Mode // Control will never reach this point because the request was already aborted in Legacy Mode
@ -2554,13 +2551,13 @@ In this example, Legacy Mode prevails and the request is continued because at le
```ts ```ts
// Final outcome: immediate continue() // Final outcome: immediate continue()
page.setRequestInterception(true); page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
// Cooperative Intercept Mode: votes to abort at priority 0. // Cooperative Intercept Mode: votes to abort at priority 0.
request.abort('failed', 0); request.abort('failed', 0);
}); });
page.on('request', (request) => { page.on('request', request => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
// Control reaches this point because the request was cooperatively aborted which postpones resolution. // Control reaches this point because the request was cooperatively aborted which postpones resolution.
@ -2571,7 +2568,7 @@ page.on('request', (request) => {
// Legacy Mode: intercept continues immediately. // Legacy Mode: intercept continues immediately.
request.continue({}); request.continue({});
}); });
page.on('request', (request) => { page.on('request', request => {
// { action: InterceptResolutionAction.AlreadyHandled }, because continue in Legacy Mode was called // { action: InterceptResolutionAction.AlreadyHandled }, because continue in Legacy Mode was called
console.log(request.interceptResolutionState()); console.log(request.interceptResolutionState());
}); });
@ -2582,19 +2579,19 @@ In this example, Cooperative Intercept Mode is active because all handlers speci
```ts ```ts
// Final outcome: cooperative continue() @ 5 // Final outcome: cooperative continue() @ 5
page.setRequestInterception(true); page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
// Cooperative Intercept Mode: votes to abort at priority 10 // Cooperative Intercept Mode: votes to abort at priority 10
request.abort('failed', 0); request.abort('failed', 0);
}); });
page.on('request', (request) => { page.on('request', request => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
// Cooperative Intercept Mode: votes to continue at priority 5 // Cooperative Intercept Mode: votes to continue at priority 5
request.continue(request.continueRequestOverrides(), 5); request.continue(request.continueRequestOverrides(), 5);
}); });
page.on('request', (request) => { page.on('request', request => {
// { action: InterceptResolutionAction.Continue, priority: 5 }, because continue @ 5 > abort @ 0 // { action: InterceptResolutionAction.Continue, priority: 5 }, because continue @ 5 > abort @ 0
console.log(request.interceptResolutionState()); console.log(request.interceptResolutionState());
}); });
@ -2605,31 +2602,31 @@ In this example, Cooperative Intercept Mode is active because all handlers speci
```ts ```ts
// Final outcome: cooperative respond() @ 15 // Final outcome: cooperative respond() @ 15
page.setRequestInterception(true); page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
// Cooperative Intercept Mode: votes to abort at priority 10 // Cooperative Intercept Mode: votes to abort at priority 10
request.abort('failed', 10); request.abort('failed', 10);
}); });
page.on('request', (request) => { page.on('request', request => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
// Cooperative Intercept Mode: votes to continue at priority 15 // Cooperative Intercept Mode: votes to continue at priority 15
request.continue(request.continueRequestOverrides(), 15); request.continue(request.continueRequestOverrides(), 15);
}); });
page.on('request', (request) => { page.on('request', request => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
// Cooperative Intercept Mode: votes to respond at priority 15 // Cooperative Intercept Mode: votes to respond at priority 15
request.respond(request.responseForRequest(), 15); request.respond(request.responseForRequest(), 15);
}); });
page.on('request', (request) => { page.on('request', request => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
// Cooperative Intercept Mode: votes to respond at priority 12 // Cooperative Intercept Mode: votes to respond at priority 12
request.respond(request.responseForRequest(), 12); request.respond(request.responseForRequest(), 12);
}); });
page.on('request', (request) => { page.on('request', request => {
// { action: InterceptResolutionAction.Respond, priority: 15 }, because respond @ 15 > continue @ 15 > respond @ 12 > abort @ 10 // { action: InterceptResolutionAction.Respond, priority: 15 }, because respond @ 15 > continue @ 15 > respond @ 12 > abort @ 10
console.log(request.interceptResolutionState()); console.log(request.interceptResolutionState());
}); });
@ -2656,7 +2653,7 @@ To summarize, reason through whether your use of `request.continue` is just mean
If you are package maintainer and your package uses intercept handlers, you can update your intercept handlers to use Cooperative Intercept Mode. Suppose you have the following existing handler: If you are package maintainer and your package uses intercept handlers, you can update your intercept handlers to use Cooperative Intercept Mode. Suppose you have the following existing handler:
```ts ```ts
page.on('request', (interceptedRequest) => { page.on('request', interceptedRequest => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
if ( if (
interceptedRequest.url().endsWith('.png') || interceptedRequest.url().endsWith('.png') ||
@ -2670,7 +2667,7 @@ page.on('request', (interceptedRequest) => {
To use Cooperative Intercept Mode, upgrade `continue()` and `abort()`: To use Cooperative Intercept Mode, upgrade `continue()` and `abort()`:
```ts ```ts
page.on('request', (interceptedRequest) => { page.on('request', interceptedRequest => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
if ( if (
interceptedRequest.url().endsWith('.png') || interceptedRequest.url().endsWith('.png') ||
@ -2706,7 +2703,7 @@ export const setInterceptResolutionConfig = (priority = 0) =>
* Note that this handler uses `DEFAULT_INTERCEPT_RESOLUTION_PRIORITY` to "pass" on this request. It is important to use * Note that this handler uses `DEFAULT_INTERCEPT_RESOLUTION_PRIORITY` to "pass" on this request. It is important to use
* the default priority when your handler has no opinion on the request and the intent is to continue() by default. * the default priority when your handler has no opinion on the request and the intent is to continue() by default.
*/ */
page.on('request', (interceptedRequest) => { page.on('request', interceptedRequest => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
if ( if (
interceptedRequest.url().endsWith('.png') || interceptedRequest.url().endsWith('.png') ||
@ -2744,7 +2741,7 @@ export const setInterceptResolutionConfig = (
config: InterceptResolutionConfig config: InterceptResolutionConfig
) => (_config = {...DEFAULT_CONFIG, ...config}); ) => (_config = {...DEFAULT_CONFIG, ...config});
page.on('request', (interceptedRequest) => { page.on('request', interceptedRequest => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
if ( if (
interceptedRequest.url().endsWith('.png') || interceptedRequest.url().endsWith('.png') ||
@ -2931,7 +2928,7 @@ To pass arguments from node.js to the predicate of `page.waitFor` function:
```js ```js
const selector = '.foo'; const selector = '.foo';
await page.waitFor( await page.waitFor(
(selector) => !!document.querySelector(selector), selector => !!document.querySelector(selector),
{}, {},
selector selector
); );
@ -2970,7 +2967,7 @@ await fileChooser.accept(['/tmp/myfile.pdf']);
- returns: <[Promise]<[Frame]>> Promise which resolves to the matched frame. - returns: <[Promise]<[Frame]>> Promise which resolves to the matched frame.
```js ```js
const frame = await page.waitForFrame(async (frame) => { const frame = await page.waitForFrame(async frame => {
return frame.name() === 'Test'; return frame.name() === 'Test';
}); });
``` ```
@ -3006,7 +3003,7 @@ To pass arguments from node.js to the predicate of `page.waitForFunction` functi
```js ```js
const selector = '.foo'; const selector = '.foo';
await page.waitForFunction( await page.waitForFunction(
(selector) => !!document.querySelector(selector), selector => !!document.querySelector(selector),
{}, {},
selector selector
); );
@ -3017,7 +3014,7 @@ The predicate of `page.waitForFunction` can be asynchronous too:
```js ```js
const username = 'github-username'; const username = 'github-username';
await page.waitForFunction( await page.waitForFunction(
async (username) => { async username => {
const githubResponse = await fetch( const githubResponse = await fetch(
`https://api.github.com/users/${username}` `https://api.github.com/users/${username}`
); );
@ -3083,7 +3080,7 @@ page.waitForNetworkIdle(); // The promise resolves after fetch above finishes
```js ```js
const firstRequest = await page.waitForRequest('http://example.com/resource'); const firstRequest = await page.waitForRequest('http://example.com/resource');
const finalRequest = await page.waitForRequest( const finalRequest = await page.waitForRequest(
(request) => request =>
request.url() === 'http://example.com' && request.method() === 'GET' request.url() === 'http://example.com' && request.method() === 'GET'
); );
return firstRequest.url(); return firstRequest.url();
@ -3101,10 +3098,10 @@ const firstResponse = await page.waitForResponse(
'https://example.com/resource' 'https://example.com/resource'
); );
const finalResponse = await page.waitForResponse( const finalResponse = await page.waitForResponse(
(response) => response =>
response.url() === 'https://example.com' && response.status() === 200 response.url() === 'https://example.com' && response.status() === 200
); );
const finalResponse = await page.waitForResponse(async (response) => { const finalResponse = await page.waitForResponse(async response => {
return (await response.text()).includes('<html>'); return (await response.text()).includes('<html>');
}); });
return finalResponse.ok(); return finalResponse.ok();
@ -3228,10 +3225,10 @@ The WebWorker class represents a [WebWorker](https://developer.mozilla.org/en-US
The events `workercreated` and `workerdestroyed` are emitted on the page object to signal the worker lifecycle. The events `workercreated` and `workerdestroyed` are emitted on the page object to signal the worker lifecycle.
```js ```js
page.on('workercreated', (worker) => page.on('workercreated', worker =>
console.log('Worker created: ' + worker.url()) console.log('Worker created: ' + worker.url())
); );
page.on('workerdestroyed', (worker) => page.on('workerdestroyed', worker =>
console.log('Worker destroyed: ' + worker.url()) console.log('Worker destroyed: ' + worker.url())
); );
@ -3708,7 +3705,7 @@ const puppeteer = require('puppeteer');
(async () => { (async () => {
const browser = await puppeteer.launch(); const browser = await puppeteer.launch();
const page = await browser.newPage(); const page = await browser.newPage();
page.on('dialog', async (dialog) => { page.on('dialog', async dialog => {
console.log(dialog.message()); console.log(dialog.message());
await dialog.dismiss(); await dialog.dismiss();
await browser.close(); await browser.close();
@ -3804,8 +3801,8 @@ const puppeteer = require('puppeteer');
An example of getting text from an iframe element: An example of getting text from an iframe element:
```js ```js
const frame = page.frames().find((frame) => frame.name() === 'myframe'); const frame = page.frames().find(frame => frame.name() === 'myframe');
const text = await frame.$eval('.selector', (element) => element.textContent); const text = await frame.$eval('.selector', element => element.textContent);
console.log(text); console.log(text);
``` ```
@ -3837,7 +3834,7 @@ If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the pr
Examples: Examples:
```js ```js
const divsCounts = await frame.$$eval('div', (divs) => divs.length); const divsCounts = await frame.$$eval('div', divs => divs.length);
``` ```
#### frame.$eval(selector, pageFunction[, ...args]) #### frame.$eval(selector, pageFunction[, ...args])
@ -3854,9 +3851,9 @@ If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the pro
Examples: Examples:
```js ```js
const searchValue = await frame.$eval('#search', (el) => el.value); const searchValue = await frame.$eval('#search', el => el.value);
const preloadHref = await frame.$eval('link[rel=preload]', (el) => el.href); const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);
const html = await frame.$eval('.main-container', (e) => e.outerHTML); const html = await frame.$eval('.main-container', e => e.outerHTML);
``` ```
#### frame.$x(expression) #### frame.$x(expression)
@ -3946,7 +3943,7 @@ console.log(await frame.evaluate('1 + 2')); // prints "3"
```js ```js
const bodyHandle = await frame.$('body'); const bodyHandle = await frame.$('body');
const html = await frame.evaluate((body) => body.innerHTML, bodyHandle); const html = await frame.evaluate(body => body.innerHTML, bodyHandle);
await bodyHandle.dispose(); await bodyHandle.dispose();
``` ```
@ -3978,7 +3975,7 @@ const aHandle = await frame.evaluateHandle('document'); // Handle for the 'docum
```js ```js
const aHandle = await frame.evaluateHandle(() => document.body); const aHandle = await frame.evaluateHandle(() => document.body);
const resultHandle = await frame.evaluateHandle( const resultHandle = await frame.evaluateHandle(
(body) => body.innerHTML, body => body.innerHTML,
aHandle aHandle
); );
console.log(await resultHandle.jsonValue()); console.log(await resultHandle.jsonValue());
@ -4157,7 +4154,7 @@ To pass arguments from node.js to the predicate of `page.waitFor` function:
```js ```js
const selector = '.foo'; const selector = '.foo';
await page.waitFor( await page.waitFor(
(selector) => !!document.querySelector(selector), selector => !!document.querySelector(selector),
{}, {},
selector selector
); );
@ -4194,7 +4191,7 @@ To pass arguments from node.js to the predicate of `page.waitForFunction` functi
```js ```js
const selector = '.foo'; const selector = '.foo';
await page.waitForFunction( await page.waitForFunction(
(selector) => !!document.querySelector(selector), selector => !!document.querySelector(selector),
{}, {},
selector selector
); );
@ -4395,7 +4392,7 @@ const aHandle = await context.evaluateHandle('1 + 2'); // Handle for the '3' obj
```js ```js
const aHandle = await context.evaluateHandle(() => document.body); const aHandle = await context.evaluateHandle(() => document.body);
const resultHandle = await context.evaluateHandle( const resultHandle = await context.evaluateHandle(
(body) => body.innerHTML, body => body.innerHTML,
aHandle aHandle
); );
console.log(await resultHandle.jsonValue()); // prints body's innerHTML console.log(await resultHandle.jsonValue()); // prints body's innerHTML
@ -4424,7 +4421,7 @@ const mapPrototype = await page.evaluateHandle(() => Map.prototype);
// Query all map instances into an array // Query all map instances into an array
const mapInstances = await page.queryObjects(mapPrototype); const mapInstances = await page.queryObjects(mapPrototype);
// Count amount of map objects in heap // Count amount of map objects in heap
const count = await page.evaluate((maps) => maps.length, mapInstances); const count = await page.evaluate(maps => maps.length, mapInstances);
await mapInstances.dispose(); await mapInstances.dispose();
await mapPrototype.dispose(); await mapPrototype.dispose();
``` ```
@ -4468,7 +4465,7 @@ Examples:
```js ```js
const tweetHandle = await page.$('.tweet .retweets'); const tweetHandle = await page.$('.tweet .retweets');
expect(await tweetHandle.evaluate((node) => node.innerText)).toBe('10'); expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10');
``` ```
#### jsHandle.evaluateHandle(pageFunction[, ...args]) #### jsHandle.evaluateHandle(pageFunction[, ...args])
@ -4584,7 +4581,7 @@ Examples:
```js ```js
const feedHandle = await page.$('.feed'); const feedHandle = await page.$('.feed');
expect( expect(
await feedHandle.$$eval('.tweet', (nodes) => nodes.map((n) => n.innerText)) await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText))
).toEqual(['Hello!', 'Hi!']); ).toEqual(['Hello!', 'Hi!']);
``` ```
@ -4603,10 +4600,8 @@ Examples:
```js ```js
const tweetHandle = await page.$('.tweet'); const tweetHandle = await page.$('.tweet');
expect(await tweetHandle.$eval('.like', (node) => node.innerText)).toBe('100'); expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');
expect(await tweetHandle.$eval('.retweets', (node) => node.innerText)).toBe( expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');
'10'
);
``` ```
#### elementHandle.$x(expression) #### elementHandle.$x(expression)
@ -4740,7 +4735,7 @@ Examples:
```js ```js
const tweetHandle = await page.$('.tweet .retweets'); const tweetHandle = await page.$('.tweet .retweets');
expect(await tweetHandle.evaluate((node) => node.innerText)).toBe('10'); expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10');
``` ```
#### elementHandle.evaluateHandle(pageFunction[, ...args]) #### elementHandle.evaluateHandle(pageFunction[, ...args])
@ -5005,7 +5000,7 @@ your handler has no opinion about it.
```js ```js
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
// Override headers // Override headers
@ -5044,7 +5039,7 @@ The method returns `null` unless this request was failed, as reported by
Example of logging all failed requests: Example of logging all failed requests:
```js ```js
page.on('requestfailed', (request) => { page.on('requestfailed', request => {
console.log(request.url() + ' ' + request.failure().errorText); console.log(request.url() + ' ' + request.failure().errorText);
}); });
``` ```
@ -5091,7 +5086,7 @@ This example will `continue()` a request at a slightly higher priority than the
already handled and is not already being continued. already handled and is not already being continued.
```js ```js
page.on('request', (interceptedRequest) => { page.on('request', interceptedRequest => {
const {action, priority} = interceptedRequest.interceptResolutionState(); const {action, priority} = interceptedRequest.interceptResolutionState();
if (action === InterceptResolutionAction.AlreadyHandled) return; if (action === InterceptResolutionAction.AlreadyHandled) return;
if (action === InterceptResolutionAction.Continue) return; if (action === InterceptResolutionAction.Continue) return;
@ -5180,7 +5175,7 @@ An example of fulfilling all requests with 404 responses:
```js ```js
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
if (request.isInterceptResolutionHandled()) return; if (request.isInterceptResolutionHandled()) return;
request.respond({ request.respond({

View File

@ -22,7 +22,7 @@ const puppeteer = require('puppeteer');
const browser = await puppeteer.launch(); const browser = await puppeteer.launch();
const page = await browser.newPage(); const page = await browser.newPage();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
if (request.resourceType() === 'image') { if (request.resourceType() === 'image') {
request.abort(); request.abort();
} else { } else {

View File

@ -35,9 +35,9 @@ const firefoxOptions = {
// Extract articles from the page. // Extract articles from the page.
const resultsSelector = '.titlelink'; const resultsSelector = '.titlelink';
const links = await page.evaluate((resultsSelector) => { const links = await page.evaluate(resultsSelector => {
const anchors = Array.from(document.querySelectorAll(resultsSelector)); const anchors = Array.from(document.querySelectorAll(resultsSelector));
return anchors.map((anchor) => { return anchors.map(anchor => {
const title = anchor.textContent.trim(); const title = anchor.textContent.trim();
return `${title} - ${anchor.href}`; return `${title} - ${anchor.href}`;
}); });

View File

@ -23,7 +23,7 @@ const puppeteer = require('puppeteer');
const page = await browser.newPage(); const page = await browser.newPage();
// Define a window.onCustomEvent function on the page. // Define a window.onCustomEvent function on the page.
await page.exposeFunction('onCustomEvent', (e) => { await page.exposeFunction('onCustomEvent', e => {
console.log(`${e.type} fired`, e.detail || ''); console.log(`${e.type} fired`, e.detail || '');
}); });
@ -33,8 +33,8 @@ const puppeteer = require('puppeteer');
* @returns {!Promise} * @returns {!Promise}
*/ */
function listenFor(type) { function listenFor(type) {
return page.evaluateOnNewDocument((type) => { return page.evaluateOnNewDocument(type => {
document.addEventListener(type, (e) => { document.addEventListener(type, e => {
window.onCustomEvent({type, detail: e.detail}); window.onCustomEvent({type, detail: e.detail});
}); });
}, type); }, type);

View File

@ -23,7 +23,7 @@ async function attachFrame(frameId, url) {
frame.src = url; frame.src = url;
frame.id = frameId; frame.id = frameId;
document.body.appendChild(frame); document.body.appendChild(frame);
await new Promise((x) => { await new Promise(x => {
return (frame.onload = x); return (frame.onload = x);
}); });
return frame; return frame;

View File

@ -42,9 +42,9 @@ const puppeteer = require('puppeteer');
await page.waitForSelector(resultsSelector); await page.waitForSelector(resultsSelector);
// Extract the results from the page. // Extract the results from the page.
const links = await page.evaluate((resultsSelector) => { const links = await page.evaluate(resultsSelector => {
const anchors = Array.from(document.querySelectorAll(resultsSelector)); const anchors = Array.from(document.querySelectorAll(resultsSelector));
return anchors.map((anchor) => { return anchors.map(anchor => {
const title = anchor.textContent.split('|')[0].trim(); const title = anchor.textContent.split('|')[0].trim();
return `${title} - ${anchor.href}`; return `${title} - ${anchor.href}`;
}); });

View File

@ -114,8 +114,9 @@
"eslint-plugin-tsdoc": "0.2.16", "eslint-plugin-tsdoc": "0.2.16",
"esprima": "4.0.1", "esprima": "4.0.1",
"expect": "25.2.7", "expect": "25.2.7",
"gts": "3.1.0",
"husky": "8.0.1", "husky": "8.0.1",
"jpeg-js": "0.4.3", "jpeg-js": "0.4.4",
"mime": "3.0.0", "mime": "3.0.0",
"minimist": "1.2.6", "minimist": "1.2.6",
"mocha": "10.0.0", "mocha": "10.0.0",

View File

@ -1,5 +0,0 @@
module.exports = {
semi: true,
trailingComma: 'es5',
singleQuote: true,
};

View File

@ -32,7 +32,7 @@ if (invalidDeps.size > 0) {
console.error('Found non-pinned dependencies in package.json:'); console.error('Found non-pinned dependencies in package.json:');
console.log( console.log(
[...invalidDeps.keys()] [...invalidDeps.keys()]
.map((k) => { .map(k => {
return ` ${k}`; return ` ${k}`;
}) })
.join('\n') .join('\n')

View File

@ -146,18 +146,14 @@ function testProject(folder: string) {
// there was no node_modules folder, which is fine. // there was no node_modules folder, which is fine.
} }
console.log('===> Installing Puppeteer from tar file', tarLocation); console.log('===> Installing Puppeteer from tar file', tarLocation);
const { status, stderr, stdout } = spawnSync( const {status, stderr, stdout} = spawnSync('npm', ['install', tarLocation], {
'npm',
['install', tarLocation],
{
env: { env: {
...process.env, ...process.env,
PUPPETEER_SKIP_DOWNLOAD: '1', PUPPETEER_SKIP_DOWNLOAD: '1',
}, },
cwd: projectLocation, cwd: projectLocation,
encoding: 'utf-8', encoding: 'utf-8',
} });
);
if (status) { if (status) {
console.error( console.error(
@ -171,7 +167,7 @@ function testProject(folder: string) {
const result = compileAndCatchErrors(projectLocation); const result = compileAndCatchErrors(projectLocation);
const expectedErrors = EXPECTED_ERRORS.get(folder) || []; const expectedErrors = EXPECTED_ERRORS.get(folder) || [];
if ( if (
result.tsErrorMesssage.find((line) => { result.tsErrorMesssage.find(line => {
return line.includes('good.ts') || line.includes('good.js'); return line.includes('good.ts') || line.includes('good.js');
}) })
) { ) {
@ -182,12 +178,12 @@ function testProject(folder: string) {
); );
process.exit(1); process.exit(1);
} }
const errorsInTsMessage = result.tsErrorMesssage.filter((line) => { const errorsInTsMessage = result.tsErrorMesssage.filter(line => {
return line.includes('bad.ts') || line.includes('bad.js'); return line.includes('bad.ts') || line.includes('bad.js');
}); });
const expectedErrorsThatHaveOccurred = new Set<string>(); const expectedErrorsThatHaveOccurred = new Set<string>();
const unexpectedErrors = errorsInTsMessage.filter((message) => { const unexpectedErrors = errorsInTsMessage.filter(message => {
const isExpected = expectedErrors.some((expectedError) => { const isExpected = expectedErrors.some(expectedError => {
const isExpected = message.startsWith(expectedError); const isExpected = message.startsWith(expectedError);
if (isExpected) { if (isExpected) {
expectedErrorsThatHaveOccurred.add(expectedError); expectedErrorsThatHaveOccurred.add(expectedError);
@ -205,7 +201,7 @@ function testProject(folder: string) {
); );
process.exit(1); process.exit(1);
} }
expectedErrors.forEach((expected) => { expectedErrors.forEach(expected => {
if (!expectedErrorsThatHaveOccurred.has(expected)) { if (!expectedErrorsThatHaveOccurred.has(expected)) {
console.error( console.error(
`${projectLocation} expected error that was not thrown: ${expected}` `${projectLocation} expected error that was not thrown: ${expected}`
@ -216,6 +212,6 @@ function testProject(folder: string) {
console.log('===> ✅ Type-checked correctly.'); console.log('===> ✅ Type-checked correctly.');
} }
PROJECT_FOLDERS.forEach((folder) => { PROJECT_FOLDERS.forEach(folder => {
testProject(folder); testProject(folder);
}); });

View File

@ -193,7 +193,7 @@ export class Accessibility {
const defaultRoot = AXNode.createTree(nodes); const defaultRoot = AXNode.createTree(nodes);
let needle: AXNode | null = defaultRoot; let needle: AXNode | null = defaultRoot;
if (backendNodeId) { if (backendNodeId) {
needle = defaultRoot.find((node) => { needle = defaultRoot.find(node => {
return node.payload.backendDOMNodeId === backendNodeId; return node.payload.backendDOMNodeId === backendNodeId;
}); });
if (!needle) { if (!needle) {

View File

@ -132,7 +132,7 @@ const queryAll = async (
const {name, role} = parseAriaSelector(selector); const {name, role} = parseAriaSelector(selector);
const res = await queryAXTree(exeCtx._client, element, name, role); const res = await queryAXTree(exeCtx._client, element, name, role);
return Promise.all( return Promise.all(
res.map((axNode) => { res.map(axNode => {
return exeCtx._adoptBackendNodeId(axNode.backendDOMNodeId); return exeCtx._adoptBackendNodeId(axNode.backendDOMNodeId);
}) })
); );

View File

@ -548,7 +548,7 @@ export class Browser extends EventEmitter {
* an array with all the targets in all browser contexts. * an array with all the targets in all browser contexts.
*/ */
targets(): Target[] { targets(): Target[] {
return Array.from(this.#targets.values()).filter((target) => { return Array.from(this.#targets.values()).filter(target => {
return target._isInitialized; return target._isInitialized;
}); });
} }
@ -557,7 +557,7 @@ export class Browser extends EventEmitter {
* The target associated with the browser. * The target associated with the browser.
*/ */
target(): Target { target(): Target {
const browserTarget = this.targets().find((target) => { const browserTarget = this.targets().find(target => {
return target.type() === 'browser'; return target.type() === 'browser';
}); });
if (!browserTarget) { if (!browserTarget) {
@ -587,7 +587,7 @@ export class Browser extends EventEmitter {
const {timeout = 30000} = options; const {timeout = 30000} = options;
let resolve: (value: Target | PromiseLike<Target>) => void; let resolve: (value: Target | PromiseLike<Target>) => void;
let isResolved = false; let isResolved = false;
const targetPromise = new Promise<Target>((x) => { const targetPromise = new Promise<Target>(x => {
return (resolve = x); return (resolve = x);
}); });
this.on(BrowserEmittedEvents.TargetCreated, check); this.on(BrowserEmittedEvents.TargetCreated, check);
@ -622,7 +622,7 @@ export class Browser extends EventEmitter {
*/ */
async pages(): Promise<Page[]> { async pages(): Promise<Page[]> {
const contextPages = await Promise.all( const contextPages = await Promise.all(
this.browserContexts().map((context) => { this.browserContexts().map(context => {
return context.pages(); return context.pages();
}) })
); );
@ -762,7 +762,7 @@ export class BrowserContext extends EventEmitter {
* An array of all active targets inside the browser context. * An array of all active targets inside the browser context.
*/ */
targets(): Target[] { targets(): Target[] {
return this.#browser.targets().filter((target) => { return this.#browser.targets().filter(target => {
return target.browserContext() === this; return target.browserContext() === this;
}); });
} }
@ -788,7 +788,7 @@ export class BrowserContext extends EventEmitter {
predicate: (x: Target) => boolean | Promise<boolean>, predicate: (x: Target) => boolean | Promise<boolean>,
options: {timeout?: number} = {} options: {timeout?: number} = {}
): Promise<Target> { ): Promise<Target> {
return this.#browser.waitForTarget((target) => { return this.#browser.waitForTarget(target => {
return target.browserContext() === this && predicate(target); return target.browserContext() === this && predicate(target);
}, options); }, options);
} }
@ -803,7 +803,7 @@ export class BrowserContext extends EventEmitter {
async pages(): Promise<Page[]> { async pages(): Promise<Page[]> {
const pages = await Promise.all( const pages = await Promise.all(
this.targets() this.targets()
.filter((target) => { .filter(target => {
return ( return (
target.type() === 'page' || target.type() === 'page' ||
(target.type() === 'other' && (target.type() === 'other' &&
@ -812,7 +812,7 @@ export class BrowserContext extends EventEmitter {
)) ))
); );
}) })
.map((target) => { .map(target => {
return target.page(); return target.page();
}) })
); );
@ -847,7 +847,7 @@ export class BrowserContext extends EventEmitter {
origin: string, origin: string,
permissions: Permission[] permissions: Permission[]
): Promise<void> { ): Promise<void> {
const protocolPermissions = permissions.map((permission) => { const protocolPermissions = permissions.map(permission => {
const protocolPermission = const protocolPermission =
WEB_PERMISSION_TO_PROTOCOL_PERMISSION.get(permission); WEB_PERMISSION_TO_PROTOCOL_PERMISSION.get(permission);
if (!protocolPermission) { if (!protocolPermission) {

View File

@ -33,7 +33,7 @@ export class BrowserWebSocketTransport implements ConnectionTransport {
constructor(ws: WebSocket) { constructor(ws: WebSocket) {
this.#ws = ws; this.#ws = ws;
this.#ws.addEventListener('message', (event) => { this.#ws.addEventListener('message', event => {
if (this.onmessage) { if (this.onmessage) {
this.onmessage.call(null, event.data); this.onmessage.call(null, event.data);
} }

View File

@ -120,9 +120,7 @@ export class Connection extends EventEmitter {
*/ */
_rawSend(message: Record<string, unknown>): number { _rawSend(message: Record<string, unknown>): number {
const id = ++this.#lastId; const id = ++this.#lastId;
const stringifiedMessage = JSON.stringify( const stringifiedMessage = JSON.stringify(Object.assign({}, message, {id}));
Object.assign({}, message, { id })
);
debugProtocolSend(stringifiedMessage); debugProtocolSend(stringifiedMessage);
this.#transport.send(stringifiedMessage); this.#transport.send(stringifiedMessage);
return id; return id;
@ -130,7 +128,7 @@ export class Connection extends EventEmitter {
async #onMessage(message: string): Promise<void> { async #onMessage(message: string): Promise<void> {
if (this.#delay) { if (this.#delay) {
await new Promise((f) => { await new Promise(f => {
return setTimeout(f, this.#delay); return setTimeout(f, this.#delay);
}); });
} }

View File

@ -15,11 +15,7 @@
*/ */
import {assert} from './assert.js'; import {assert} from './assert.js';
import { import {addEventListener, debugError, PuppeteerEventListener} from './util.js';
addEventListener,
debugError,
PuppeteerEventListener,
} from './util.js';
import {Protocol} from 'devtools-protocol'; import {Protocol} from 'devtools-protocol';
import {CDPSession} from './Connection.js'; import {CDPSession} from './Connection.js';
@ -480,7 +476,7 @@ function convertToDisjointRanges(
} }
} }
// Filter out empty ranges. // Filter out empty ranges.
return results.filter((range) => { return results.filter(range => {
return range.end - range.start > 1; return range.end - range.start > 1;
}); });
} }

View File

@ -37,10 +37,7 @@ import {
} from './util.js'; } from './util.js';
import {MouseButton} from './Input.js'; import {MouseButton} from './Input.js';
import {ElementHandle, JSHandle} from './JSHandle.js'; import {ElementHandle, JSHandle} from './JSHandle.js';
import { import {LifecycleWatcher, PuppeteerLifeCycleEvent} from './LifecycleWatcher.js';
LifecycleWatcher,
PuppeteerLifeCycleEvent,
} from './LifecycleWatcher.js';
import {_getQueryHandlerAndSelector} from './QueryHandler.js'; import {_getQueryHandlerAndSelector} from './QueryHandler.js';
import {TimeoutSettings} from './TimeoutSettings.js'; import {TimeoutSettings} from './TimeoutSettings.js';
@ -149,7 +146,7 @@ export class DOMWorld {
} }
} else { } else {
this.#documentPromise = null; this.#documentPromise = null;
this.#contextPromise = new Promise((fulfill) => { this.#contextPromise = new Promise(fulfill => {
this.#contextResolveCallback = fulfill; this.#contextResolveCallback = fulfill;
}); });
} }
@ -221,7 +218,7 @@ export class DOMWorld {
if (this.#documentPromise) { if (this.#documentPromise) {
return this.#documentPromise; return this.#documentPromise;
} }
this.#documentPromise = this.executionContext().then(async (context) => { this.#documentPromise = this.executionContext().then(async context => {
const document = await context.evaluateHandle('document'); const document = await context.evaluateHandle('document');
const element = document.asElement(); const element = document.asElement();
if (element === null) { if (element === null) {
@ -301,7 +298,7 @@ export class DOMWorld {
} = options; } = options;
// We rely upon the fact that document.open() will reset frame lifecycle with "init" // We rely upon the fact that document.open() will reset frame lifecycle with "init"
// lifecycle event. @see https://crrev.com/608658 // lifecycle event. @see https://crrev.com/608658
await this.evaluate<(x: string) => void>((html) => { await this.evaluate<(x: string) => void>(html => {
document.open(); document.open();
document.write(html); document.write(html);
document.close(); document.close();
@ -445,7 +442,7 @@ export class DOMWorld {
script.id = id; script.id = id;
} }
let error = null; let error = null;
script.onerror = (e) => { script.onerror = e => {
return (error = e); return (error = e);
}; };
document.head.appendChild(script); document.head.appendChild(script);
@ -992,7 +989,7 @@ export class WaitTask {
if ( if (
!error && !error &&
(await this.#domWorld (await this.#domWorld
.evaluate((s) => { .evaluate(s => {
return !s; return !s;
}, success) }, success)
.catch(() => { .catch(() => {
@ -1085,7 +1082,7 @@ async function waitForPredicatePageFunction(
} }
let fulfill = (_?: unknown) => {}; let fulfill = (_?: unknown) => {};
const result = new Promise((x) => { const result = new Promise(x => {
return (fulfill = x); return (fulfill = x);
}); });
const observer = new MutationObserver(async () => { const observer = new MutationObserver(async () => {
@ -1114,7 +1111,7 @@ async function waitForPredicatePageFunction(
async function pollRaf(): Promise<unknown> { async function pollRaf(): Promise<unknown> {
let fulfill = (_?: unknown): void => {}; let fulfill = (_?: unknown): void => {};
const result = new Promise((x) => { const result = new Promise(x => {
return (fulfill = x); return (fulfill = x);
}); });
await onRaf(); await onRaf();
@ -1138,7 +1135,7 @@ async function waitForPredicatePageFunction(
async function pollInterval(pollInterval: number): Promise<unknown> { async function pollInterval(pollInterval: number): Promise<unknown> {
let fulfill = (_?: unknown): void => {}; let fulfill = (_?: unknown): void => {};
const result = new Promise((x) => { const result = new Promise(x => {
return (fulfill = x); return (fulfill = x);
}); });
await onTimeout(); await onTimeout();

View File

@ -110,7 +110,7 @@ export class EventEmitter implements CommonEventEmitter {
* @returns `this` to enable you to chain method calls. * @returns `this` to enable you to chain method calls.
*/ */
once(event: EventType, handler: Handler): EventEmitter { once(event: EventType, handler: Handler): EventEmitter {
const onceHandler: Handler = (eventData) => { const onceHandler: Handler = eventData => {
handler(eventData); handler(eventData);
this.off(event, onceHandler); this.off(event, onceHandler);
}; };

View File

@ -20,11 +20,7 @@ import { CDPSession } from './Connection.js';
import {DOMWorld} from './DOMWorld.js'; import {DOMWorld} from './DOMWorld.js';
import {EvaluateHandleFn, SerializableOrJSHandle} from './EvalTypes.js'; import {EvaluateHandleFn, SerializableOrJSHandle} from './EvalTypes.js';
import {Frame} from './FrameManager.js'; import {Frame} from './FrameManager.js';
import { import {getExceptionMessage, isString, valueFromRemoteObject} from './util.js';
getExceptionMessage,
isString,
valueFromRemoteObject,
} from './util.js';
import {ElementHandle, JSHandle, _createJSHandle} from './JSHandle.js'; import {ElementHandle, JSHandle, _createJSHandle} from './JSHandle.js';
/** /**

View File

@ -31,10 +31,7 @@ import { EVALUATION_SCRIPT_URL, ExecutionContext } from './ExecutionContext.js';
import {HTTPResponse} from './HTTPResponse.js'; import {HTTPResponse} from './HTTPResponse.js';
import {MouseButton} from './Input.js'; import {MouseButton} from './Input.js';
import {ElementHandle, JSHandle} from './JSHandle.js'; import {ElementHandle, JSHandle} from './JSHandle.js';
import { import {LifecycleWatcher, PuppeteerLifeCycleEvent} from './LifecycleWatcher.js';
LifecycleWatcher,
PuppeteerLifeCycleEvent,
} from './LifecycleWatcher.js';
import {NetworkManager} from './NetworkManager.js'; import {NetworkManager} from './NetworkManager.js';
import {Page} from './Page.js'; import {Page} from './Page.js';
import {TimeoutSettings} from './TimeoutSettings.js'; import {TimeoutSettings} from './TimeoutSettings.js';
@ -104,13 +101,13 @@ export class FrameManager extends EventEmitter {
} }
private setupEventListeners(session: CDPSession) { private setupEventListeners(session: CDPSession) {
session.on('Page.frameAttached', (event) => { session.on('Page.frameAttached', event => {
this.#onFrameAttached(session, event.frameId, event.parentFrameId); this.#onFrameAttached(session, event.frameId, event.parentFrameId);
}); });
session.on('Page.frameNavigated', (event) => { session.on('Page.frameNavigated', event => {
this.#onFrameNavigated(event.frame); this.#onFrameNavigated(event.frame);
}); });
session.on('Page.navigatedWithinDocument', (event) => { session.on('Page.navigatedWithinDocument', event => {
this.#onFrameNavigatedWithinDocument(event.frameId, event.url); this.#onFrameNavigatedWithinDocument(event.frameId, event.url);
}); });
session.on( session.on(
@ -122,28 +119,28 @@ export class FrameManager extends EventEmitter {
); );
} }
); );
session.on('Page.frameStartedLoading', (event) => { session.on('Page.frameStartedLoading', event => {
this.#onFrameStartedLoading(event.frameId); this.#onFrameStartedLoading(event.frameId);
}); });
session.on('Page.frameStoppedLoading', (event) => { session.on('Page.frameStoppedLoading', event => {
this.#onFrameStoppedLoading(event.frameId); this.#onFrameStoppedLoading(event.frameId);
}); });
session.on('Runtime.executionContextCreated', (event) => { session.on('Runtime.executionContextCreated', event => {
this.#onExecutionContextCreated(event.context, session); this.#onExecutionContextCreated(event.context, session);
}); });
session.on('Runtime.executionContextDestroyed', (event) => { session.on('Runtime.executionContextDestroyed', event => {
this.#onExecutionContextDestroyed(event.executionContextId, session); this.#onExecutionContextDestroyed(event.executionContextId, session);
}); });
session.on('Runtime.executionContextsCleared', () => { session.on('Runtime.executionContextsCleared', () => {
this.#onExecutionContextsCleared(session); this.#onExecutionContextsCleared(session);
}); });
session.on('Page.lifecycleEvent', (event) => { session.on('Page.lifecycleEvent', event => {
this.#onLifecycleEvent(event); this.#onLifecycleEvent(event);
}); });
session.on('Target.attachedToTarget', async (event) => { session.on('Target.attachedToTarget', async event => {
this.#onAttachedToTarget(event); this.#onAttachedToTarget(event);
}); });
session.on('Target.detachedFromTarget', async (event) => { session.on('Target.detachedFromTarget', async event => {
this.#onDetachedFromTarget(event); this.#onDetachedFromTarget(event);
}); });
} }
@ -443,10 +440,10 @@ export class FrameManager extends EventEmitter {
// Frames might be removed before we send this. // Frames might be removed before we send this.
await Promise.all( await Promise.all(
this.frames() this.frames()
.filter((frame) => { .filter(frame => {
return frame._client() === session; return frame._client() === session;
}) })
.map((frame) => { .map(frame => {
return session return session
.send('Page.createIsolatedWorld', { .send('Page.createIsolatedWorld', {
frameId: frame._id, frameId: frame._id,
@ -1283,7 +1280,7 @@ export class Frame {
return this.waitForSelector(string, options); return this.waitForSelector(string, options);
} }
if (isNumber(selectorOrFunctionOrTimeout)) { if (isNumber(selectorOrFunctionOrTimeout)) {
return new Promise((fulfill) => { return new Promise(fulfill => {
return setTimeout(fulfill, selectorOrFunctionOrTimeout); return setTimeout(fulfill, selectorOrFunctionOrTimeout);
}); });
} }
@ -1320,7 +1317,7 @@ export class Frame {
* @param milliseconds - the number of milliseconds to wait. * @param milliseconds - the number of milliseconds to wait.
*/ */
waitForTimeout(milliseconds: number): Promise<void> { waitForTimeout(milliseconds: number): Promise<void> {
return new Promise((resolve) => { return new Promise(resolve => {
setTimeout(resolve, milliseconds); setTimeout(resolve, milliseconds);
}); });
} }

View File

@ -492,7 +492,7 @@ export class HTTPRequest {
postData: postDataBinaryBase64, postData: postDataBinaryBase64,
headers: headers ? headersArray(headers) : undefined, headers: headers ? headersArray(headers) : undefined,
}) })
.catch((error) => { .catch(error => {
this.#interceptionHandled = false; this.#interceptionHandled = false;
return handleError(error); return handleError(error);
}); });
@ -575,7 +575,7 @@ export class HTTPRequest {
const value = response.headers[header]; const value = response.headers[header];
responseHeaders[header.toLowerCase()] = Array.isArray(value) responseHeaders[header.toLowerCase()] = Array.isArray(value)
? value.map((item) => { ? value.map(item => {
return String(item); return String(item);
}) })
: String(value); : String(value);
@ -604,7 +604,7 @@ export class HTTPRequest {
responseHeaders: headersArray(responseHeaders), responseHeaders: headersArray(responseHeaders),
body: responseBody ? responseBody.toString('base64') : undefined, body: responseBody ? responseBody.toString('base64') : undefined,
}) })
.catch((error) => { .catch(error => {
this.#interceptionHandled = false; this.#interceptionHandled = false;
return handleError(error); return handleError(error);
}); });
@ -740,7 +740,7 @@ function headersArray(
const values = Array.isArray(value) ? value : [value]; const values = Array.isArray(value) ? value : [value];
result.push( result.push(
...values.map((value) => { ...values.map(value => {
return {name, value: value + ''}; return {name, value: value + ''};
}) })
); );

View File

@ -71,7 +71,7 @@ export class HTTPResponse {
this.#client = client; this.#client = client;
this.#request = request; this.#request = request;
this.#bodyLoadedPromise = new Promise((fulfill) => { this.#bodyLoadedPromise = new Promise(fulfill => {
this.#bodyLoadedPromiseFulfill = fulfill; this.#bodyLoadedPromiseFulfill = fulfill;
}); });
@ -195,7 +195,7 @@ export class HTTPResponse {
*/ */
buffer(): Promise<Buffer> { buffer(): Promise<Buffer> {
if (!this.#contentPromise) { if (!this.#contentPromise) {
this.#contentPromise = this.#bodyLoadedPromise.then(async (error) => { this.#contentPromise = this.#bodyLoadedPromise.then(async error => {
if (error) { if (error) {
throw error; throw error;
} }

View File

@ -16,11 +16,7 @@
import {assert} from './assert.js'; import {assert} from './assert.js';
import {CDPSession} from './Connection.js'; import {CDPSession} from './Connection.js';
import { import {_keyDefinitions, KeyDefinition, KeyInput} from './USKeyboardLayout.js';
_keyDefinitions,
KeyDefinition,
KeyInput,
} from './USKeyboardLayout.js';
import {Protocol} from 'devtools-protocol'; import {Protocol} from 'devtools-protocol';
import {Point} from './JSHandle.js'; import {Point} from './JSHandle.js';
@ -277,7 +273,7 @@ export class Keyboard {
await this.press(char, {delay}); await this.press(char, {delay});
} else { } else {
if (delay) { if (delay) {
await new Promise((f) => { await new Promise(f => {
return setTimeout(f, delay); return setTimeout(f, delay);
}); });
} }
@ -313,7 +309,7 @@ export class Keyboard {
const {delay = null} = options; const {delay = null} = options;
await this.down(key, options); await this.down(key, options);
if (delay) { if (delay) {
await new Promise((f) => { await new Promise(f => {
return setTimeout(f, options.delay); return setTimeout(f, options.delay);
}); });
} }
@ -457,7 +453,7 @@ export class Mouse {
if (delay !== null) { if (delay !== null) {
await this.move(x, y); await this.move(x, y);
await this.down(options); await this.down(options);
await new Promise((f) => { await new Promise(f => {
return setTimeout(f, delay); return setTimeout(f, delay);
}); });
await this.up(options); await this.up(options);
@ -540,8 +536,8 @@ export class Mouse {
* @param target - point to drag to * @param target - point to drag to
*/ */
async drag(start: Point, target: Point): Promise<Protocol.Input.DragData> { async drag(start: Point, target: Point): Promise<Protocol.Input.DragData> {
const promise = new Promise<Protocol.Input.DragData>((resolve) => { const promise = new Promise<Protocol.Input.DragData>(resolve => {
this.#client.once('Input.dragIntercepted', (event) => { this.#client.once('Input.dragIntercepted', event => {
return resolve(event.data); return resolve(event.data);
}); });
}); });
@ -614,7 +610,7 @@ export class Mouse {
await this.dragEnter(target, data); await this.dragEnter(target, data);
await this.dragOver(target, data); await this.dragOver(target, data);
if (delay) { if (delay) {
await new Promise((resolve) => { await new Promise(resolve => {
return setTimeout(resolve, delay); return setTimeout(resolve, delay);
}); });
} }

View File

@ -91,7 +91,7 @@ const applyOffsetsToQuad = (
offsetX: number, offsetX: number,
offsetY: number offsetY: number
) => { ) => {
return quad.map((part) => { return quad.map(part => {
return {x: part.x + offsetX, y: part.y + offsetY}; return {x: part.x + offsetX, y: part.y + offsetY};
}); });
}; };
@ -561,8 +561,8 @@ export class ElementHandle<
}); });
return false; return false;
} }
const visibleRatio = await new Promise((resolve) => { const visibleRatio = await new Promise(resolve => {
const observer = new IntersectionObserver((entries) => { const observer = new IntersectionObserver(entries => {
resolve(entries[0]!.intersectionRatio); resolve(entries[0]!.intersectionRatio);
observer.disconnect(); observer.disconnect();
}); });
@ -600,9 +600,7 @@ export class ElementHandle<
currentFrame = parent; currentFrame = parent;
continue; continue;
} }
const { backendNodeId } = await parent const {backendNodeId} = await parent._client().send('DOM.getFrameOwner', {
._client()
.send('DOM.getFrameOwner', {
frameId: currentFrame._id, frameId: currentFrame._id,
}); });
const result = await parent._client().send('DOM.getBoxModel', { const result = await parent._client().send('DOM.getBoxModel', {
@ -641,16 +639,16 @@ export class ElementHandle<
layoutMetrics.cssLayoutViewport || layoutMetrics.layoutViewport; layoutMetrics.cssLayoutViewport || layoutMetrics.layoutViewport;
const {offsetX, offsetY} = await this.#getOOPIFOffsets(this.#frame); const {offsetX, offsetY} = await this.#getOOPIFOffsets(this.#frame);
const quads = result.quads const quads = result.quads
.map((quad) => { .map(quad => {
return this.#fromProtocolQuad(quad); return this.#fromProtocolQuad(quad);
}) })
.map((quad) => { .map(quad => {
return applyOffsetsToQuad(quad, offsetX, offsetY); return applyOffsetsToQuad(quad, offsetX, offsetY);
}) })
.map((quad) => { .map(quad => {
return this.#intersectQuadWithViewport(quad, clientWidth, clientHeight); return this.#intersectQuadWithViewport(quad, clientWidth, clientHeight);
}) })
.filter((quad) => { .filter(quad => {
return computeQuadArea(quad) > 1; return computeQuadArea(quad) > 1;
}); });
if (!quads.length) { if (!quads.length) {
@ -696,7 +694,7 @@ export class ElementHandle<
const params: Protocol.DOM.GetBoxModelRequest = { const params: Protocol.DOM.GetBoxModelRequest = {
objectId: this._remoteObject.objectId, objectId: this._remoteObject.objectId,
}; };
return this._client.send('DOM.getBoxModel', params).catch((error) => { return this._client.send('DOM.getBoxModel', params).catch(error => {
return debugError(error); return debugError(error);
}); });
} }
@ -715,7 +713,7 @@ export class ElementHandle<
width: number, width: number,
height: number height: number
): Point[] { ): Point[] {
return quad.map((point) => { return quad.map(point => {
return { return {
x: Math.min(Math.max(point.x, 0), width), x: Math.min(Math.max(point.x, 0), width),
y: Math.min(Math.max(point.y, 0), height), y: Math.min(Math.max(point.y, 0), height),
@ -874,7 +872,7 @@ export class ElementHandle<
*/ */
async uploadFile(...filePaths: string[]): Promise<void> { async uploadFile(...filePaths: string[]): Promise<void> {
const isMultiple = await this.evaluate<(element: Element) => boolean>( const isMultiple = await this.evaluate<(element: Element) => boolean>(
(element) => { element => {
if (!(element instanceof HTMLInputElement)) { if (!(element instanceof HTMLInputElement)) {
throw new Error('uploadFile can only be called on an input element.'); throw new Error('uploadFile can only be called on an input element.');
} }
@ -898,7 +896,7 @@ export class ElementHandle<
} }
throw error; throw error;
} }
const files = filePaths.map((filePath) => { const files = filePaths.map(filePath => {
if (path.win32.isAbsolute(filePath) || path.posix.isAbsolute(filePath)) { if (path.win32.isAbsolute(filePath) || path.posix.isAbsolute(filePath)) {
return filePath; return filePath;
} else { } else {
@ -914,7 +912,7 @@ export class ElementHandle<
so the solution is to eval the element value to a new FileList directly. so the solution is to eval the element value to a new FileList directly.
*/ */
if (files.length === 0) { if (files.length === 0) {
await (this as ElementHandle<HTMLInputElement>).evaluate((element) => { await (this as ElementHandle<HTMLInputElement>).evaluate(element => {
element.files = new DataTransfer().files; element.files = new DataTransfer().files;
// Dispatch events for this case because it should behave akin to a user action. // Dispatch events for this case because it should behave akin to a user action.
@ -945,7 +943,7 @@ export class ElementHandle<
* Calls {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus | focus} on the element. * Calls {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus | focus} on the element.
*/ */
async focus(): Promise<void> { async focus(): Promise<void> {
await (this as ElementHandle<HTMLElement>).evaluate((element) => { await (this as ElementHandle<HTMLElement>).evaluate(element => {
return element.focus(); return element.focus();
}); });
} }
@ -1302,8 +1300,8 @@ export class ElementHandle<
}): Promise<boolean> { }): Promise<boolean> {
const {threshold = 0} = options || {}; const {threshold = 0} = options || {};
return await this.evaluate(async (element: Element, threshold: number) => { return await this.evaluate(async (element: Element, threshold: number) => {
const visibleRatio = await new Promise<number>((resolve) => { const visibleRatio = await new Promise<number>(resolve => {
const observer = new IntersectionObserver((entries) => { const observer = new IntersectionObserver(entries => {
resolve(entries[0]!.intersectionRatio); resolve(entries[0]!.intersectionRatio);
observer.disconnect(); observer.disconnect();
}); });

View File

@ -72,24 +72,24 @@ export class LifecycleWatcher {
#eventListeners: PuppeteerEventListener[]; #eventListeners: PuppeteerEventListener[];
#sameDocumentNavigationCompleteCallback: (x?: Error) => void = noop; #sameDocumentNavigationCompleteCallback: (x?: Error) => void = noop;
#sameDocumentNavigationPromise = new Promise<Error | undefined>((fulfill) => { #sameDocumentNavigationPromise = new Promise<Error | undefined>(fulfill => {
this.#sameDocumentNavigationCompleteCallback = fulfill; this.#sameDocumentNavigationCompleteCallback = fulfill;
}); });
#lifecycleCallback: () => void = noop; #lifecycleCallback: () => void = noop;
#lifecyclePromise: Promise<void> = new Promise((fulfill) => { #lifecyclePromise: Promise<void> = new Promise(fulfill => {
this.#lifecycleCallback = fulfill; this.#lifecycleCallback = fulfill;
}); });
#newDocumentNavigationCompleteCallback: (x?: Error) => void = noop; #newDocumentNavigationCompleteCallback: (x?: Error) => void = noop;
#newDocumentNavigationPromise: Promise<Error | undefined> = new Promise( #newDocumentNavigationPromise: Promise<Error | undefined> = new Promise(
(fulfill) => { fulfill => {
this.#newDocumentNavigationCompleteCallback = fulfill; this.#newDocumentNavigationCompleteCallback = fulfill;
} }
); );
#terminationCallback: (x?: Error) => void = noop; #terminationCallback: (x?: Error) => void = noop;
#terminationPromise: Promise<Error | undefined> = new Promise((fulfill) => { #terminationPromise: Promise<Error | undefined> = new Promise(fulfill => {
this.#terminationCallback = fulfill; this.#terminationCallback = fulfill;
}); });
@ -111,7 +111,7 @@ export class LifecycleWatcher {
} else if (typeof waitUntil === 'string') { } else if (typeof waitUntil === 'string') {
waitUntil = [waitUntil]; waitUntil = [waitUntil];
} }
this.#expectedLifecycle = waitUntil.map((value) => { this.#expectedLifecycle = waitUntil.map(value => {
const protocolEvent = puppeteerToProtocolLifecycle.get(value); const protocolEvent = puppeteerToProtocolLifecycle.get(value);
assert(protocolEvent, 'Unknown value for options.waitUntil: ' + value); assert(protocolEvent, 'Unknown value for options.waitUntil: ' + value);
return protocolEvent as ProtocolLifeCycleEvent; return protocolEvent as ProtocolLifeCycleEvent;
@ -214,7 +214,7 @@ export class LifecycleWatcher {
} }
const errorMessage = const errorMessage =
'Navigation timeout of ' + this.#timeout + ' ms exceeded'; 'Navigation timeout of ' + this.#timeout + ' ms exceeded';
await new Promise((fulfill) => { await new Promise(fulfill => {
return (this.#maximumTimer = setTimeout(fulfill, this.#timeout)); return (this.#maximumTimer = setTimeout(fulfill, this.#timeout));
}); });
return new TimeoutError(errorMessage); return new TimeoutError(errorMessage);

View File

@ -19,11 +19,7 @@ import type { Readable } from 'stream';
import {Accessibility} from './Accessibility.js'; import {Accessibility} from './Accessibility.js';
import {assert, assertNever} from './assert.js'; import {assert, assertNever} from './assert.js';
import {Browser, BrowserContext} from './Browser.js'; import {Browser, BrowserContext} from './Browser.js';
import { import {CDPSession, CDPSessionEmittedEvents, Connection} from './Connection.js';
CDPSession,
CDPSessionEmittedEvents,
Connection,
} from './Connection.js';
import {ConsoleMessage, ConsoleMessageType} from './ConsoleMessage.js'; import {ConsoleMessage, ConsoleMessageType} from './ConsoleMessage.js';
import {Coverage} from './Coverage.js'; import {Coverage} from './Coverage.js';
import {Dialog} from './Dialog.js'; import {Dialog} from './Dialog.js';
@ -71,11 +67,7 @@ import {
NetworkConditions, NetworkConditions,
NetworkManagerEmittedEvents, NetworkManagerEmittedEvents,
} from './NetworkManager.js'; } from './NetworkManager.js';
import { import {LowerCasePaperFormat, PDFOptions, _paperFormats} from './PDFOptions.js';
LowerCasePaperFormat,
PDFOptions,
_paperFormats,
} from './PDFOptions.js';
import {Viewport} from './PuppeteerViewport.js'; import {Viewport} from './PuppeteerViewport.js';
import {Target} from './Target.js'; import {Target} from './Target.js';
import {TaskQueue} from './TaskQueue.js'; import {TaskQueue} from './TaskQueue.js';
@ -545,7 +537,7 @@ export class Page extends EventEmitter {
} }
} }
); );
client.on('Target.detachedFromTarget', (event) => { client.on('Target.detachedFromTarget', event => {
const worker = this.#workers.get(event.sessionId); const worker = this.#workers.get(event.sessionId);
if (!worker) { if (!worker) {
return; return;
@ -554,33 +546,33 @@ export class Page extends EventEmitter {
this.emit(PageEmittedEvents.WorkerDestroyed, worker); this.emit(PageEmittedEvents.WorkerDestroyed, worker);
}); });
this.#frameManager.on(FrameManagerEmittedEvents.FrameAttached, (event) => { this.#frameManager.on(FrameManagerEmittedEvents.FrameAttached, event => {
return this.emit(PageEmittedEvents.FrameAttached, event); return this.emit(PageEmittedEvents.FrameAttached, event);
}); });
this.#frameManager.on(FrameManagerEmittedEvents.FrameDetached, (event) => { this.#frameManager.on(FrameManagerEmittedEvents.FrameDetached, event => {
return this.emit(PageEmittedEvents.FrameDetached, event); return this.emit(PageEmittedEvents.FrameDetached, event);
}); });
this.#frameManager.on(FrameManagerEmittedEvents.FrameNavigated, (event) => { this.#frameManager.on(FrameManagerEmittedEvents.FrameNavigated, event => {
return this.emit(PageEmittedEvents.FrameNavigated, event); return this.emit(PageEmittedEvents.FrameNavigated, event);
}); });
const networkManager = this.#frameManager.networkManager(); const networkManager = this.#frameManager.networkManager();
networkManager.on(NetworkManagerEmittedEvents.Request, (event) => { networkManager.on(NetworkManagerEmittedEvents.Request, event => {
return this.emit(PageEmittedEvents.Request, event); return this.emit(PageEmittedEvents.Request, event);
}); });
networkManager.on( networkManager.on(
NetworkManagerEmittedEvents.RequestServedFromCache, NetworkManagerEmittedEvents.RequestServedFromCache,
(event) => { event => {
return this.emit(PageEmittedEvents.RequestServedFromCache, event); return this.emit(PageEmittedEvents.RequestServedFromCache, event);
} }
); );
networkManager.on(NetworkManagerEmittedEvents.Response, (event) => { networkManager.on(NetworkManagerEmittedEvents.Response, event => {
return this.emit(PageEmittedEvents.Response, event); return this.emit(PageEmittedEvents.Response, event);
}); });
networkManager.on(NetworkManagerEmittedEvents.RequestFailed, (event) => { networkManager.on(NetworkManagerEmittedEvents.RequestFailed, event => {
return this.emit(PageEmittedEvents.RequestFailed, event); return this.emit(PageEmittedEvents.RequestFailed, event);
}); });
networkManager.on(NetworkManagerEmittedEvents.RequestFinished, (event) => { networkManager.on(NetworkManagerEmittedEvents.RequestFinished, event => {
return this.emit(PageEmittedEvents.RequestFinished, event); return this.emit(PageEmittedEvents.RequestFinished, event);
}); });
this.#fileChooserInterceptors = new Set(); this.#fileChooserInterceptors = new Set();
@ -591,28 +583,28 @@ export class Page extends EventEmitter {
client.on('Page.loadEventFired', () => { client.on('Page.loadEventFired', () => {
return this.emit(PageEmittedEvents.Load); return this.emit(PageEmittedEvents.Load);
}); });
client.on('Runtime.consoleAPICalled', (event) => { client.on('Runtime.consoleAPICalled', event => {
return this.#onConsoleAPI(event); return this.#onConsoleAPI(event);
}); });
client.on('Runtime.bindingCalled', (event) => { client.on('Runtime.bindingCalled', event => {
return this.#onBindingCalled(event); return this.#onBindingCalled(event);
}); });
client.on('Page.javascriptDialogOpening', (event) => { client.on('Page.javascriptDialogOpening', event => {
return this.#onDialog(event); return this.#onDialog(event);
}); });
client.on('Runtime.exceptionThrown', (exception) => { client.on('Runtime.exceptionThrown', exception => {
return this.#handleException(exception.exceptionDetails); return this.#handleException(exception.exceptionDetails);
}); });
client.on('Inspector.targetCrashed', () => { client.on('Inspector.targetCrashed', () => {
return this.#onTargetCrashed(); return this.#onTargetCrashed();
}); });
client.on('Performance.metrics', (event) => { client.on('Performance.metrics', event => {
return this.#emitMetrics(event); return this.#emitMetrics(event);
}); });
client.on('Log.entryAdded', (event) => { client.on('Log.entryAdded', event => {
return this.#onLogEntryAdded(event); return this.#onLogEntryAdded(event);
}); });
client.on('Page.fileChooserOpened', (event) => { client.on('Page.fileChooserOpened', event => {
return this.#onFileChooser(event); return this.#onFileChooser(event);
}); });
this.#target._isClosedPromise.then(() => { this.#target._isClosedPromise.then(() => {
@ -745,7 +737,7 @@ export class Page extends EventEmitter {
const {timeout = this.#timeoutSettings.timeout()} = options; const {timeout = this.#timeoutSettings.timeout()} = options;
let callback!: (value: FileChooser | PromiseLike<FileChooser>) => void; let callback!: (value: FileChooser | PromiseLike<FileChooser>) => void;
const promise = new Promise<FileChooser>((x) => { const promise = new Promise<FileChooser>(x => {
return (callback = x); return (callback = x);
}); });
this.#fileChooserInterceptors.add(callback); this.#fileChooserInterceptors.add(callback);
@ -753,7 +745,7 @@ export class Page extends EventEmitter {
promise, promise,
'waiting for file chooser', 'waiting for file chooser',
timeout timeout
).catch((error) => { ).catch(error => {
this.#fileChooserInterceptors.delete(callback); this.#fileChooserInterceptors.delete(callback);
throw error; throw error;
}); });
@ -828,7 +820,7 @@ export class Page extends EventEmitter {
#onLogEntryAdded(event: Protocol.Log.EntryAddedEvent): void { #onLogEntryAdded(event: Protocol.Log.EntryAddedEvent): void {
const {level, text, args, source, url, lineNumber} = event.entry; const {level, text, args, source, url, lineNumber} = event.entry;
if (args) { if (args) {
args.map((arg) => { args.map(arg => {
return releaseObject(this.#client, arg); return releaseObject(this.#client, arg);
}); });
} }
@ -1337,7 +1329,7 @@ export class Page extends EventEmitter {
async setCookie(...cookies: Protocol.Network.CookieParam[]): Promise<void> { async setCookie(...cookies: Protocol.Network.CookieParam[]): Promise<void> {
const pageURL = this.url(); const pageURL = this.url();
const startsWithHTTP = pageURL.startsWith('http'); const startsWithHTTP = pageURL.startsWith('http');
const items = cookies.map((cookie) => { const items = cookies.map(cookie => {
const item = Object.assign({}, cookie); const item = Object.assign({}, cookie);
if (!item.url && startsWithHTTP) { if (!item.url && startsWithHTTP) {
item.url = pageURL; item.url = pageURL;
@ -1477,7 +1469,7 @@ export class Page extends EventEmitter {
source: expression, source: expression,
}); });
await Promise.all( await Promise.all(
this.frames().map((frame) => { this.frames().map(frame => {
return frame.evaluate(expression).catch(debugError); return frame.evaluate(expression).catch(debugError);
}) })
); );
@ -1609,7 +1601,7 @@ export class Page extends EventEmitter {
event.executionContextId, event.executionContextId,
this.#client this.#client
); );
const values = event.args.map((arg) => { const values = event.args.map(arg => {
return _createJSHandle(context, arg); return _createJSHandle(context, arg);
}); });
this.#addConsoleMessage(event.type, values, event.stackTrace); this.#addConsoleMessage(event.type, values, event.stackTrace);
@ -1662,7 +1654,7 @@ export class Page extends EventEmitter {
stackTrace?: Protocol.Runtime.StackTrace stackTrace?: Protocol.Runtime.StackTrace
): void { ): void {
if (!this.listenerCount(PageEmittedEvents.Console)) { if (!this.listenerCount(PageEmittedEvents.Console)) {
args.forEach((arg) => { args.forEach(arg => {
return arg.dispose(); return arg.dispose();
}); });
return; return;
@ -1910,7 +1902,7 @@ export class Page extends EventEmitter {
#sessionClosePromise(): Promise<Error> { #sessionClosePromise(): Promise<Error> {
if (!this.#disconnectPromise) { if (!this.#disconnectPromise) {
this.#disconnectPromise = new Promise((fulfill) => { this.#disconnectPromise = new Promise(fulfill => {
return this.#client.once(CDPSessionEmittedEvents.Disconnected, () => { return this.#client.once(CDPSessionEmittedEvents.Disconnected, () => {
return fulfill(new Error('Target closed')); return fulfill(new Error('Target closed'));
}); });
@ -1952,7 +1944,7 @@ export class Page extends EventEmitter {
return waitForEvent( return waitForEvent(
this.#frameManager.networkManager(), this.#frameManager.networkManager(),
NetworkManagerEmittedEvents.Request, NetworkManagerEmittedEvents.Request,
(request) => { request => {
if (isString(urlOrPredicate)) { if (isString(urlOrPredicate)) {
return urlOrPredicate === request.url(); return urlOrPredicate === request.url();
} }
@ -2001,7 +1993,7 @@ export class Page extends EventEmitter {
return waitForEvent( return waitForEvent(
this.#frameManager.networkManager(), this.#frameManager.networkManager(),
NetworkManagerEmittedEvents.Response, NetworkManagerEmittedEvents.Response,
async (response) => { async response => {
if (isString(urlOrPredicate)) { if (isString(urlOrPredicate)) {
return urlOrPredicate === response.url(); return urlOrPredicate === response.url();
} }
@ -2022,13 +2014,12 @@ export class Page extends EventEmitter {
async waitForNetworkIdle( async waitForNetworkIdle(
options: {idleTime?: number; timeout?: number} = {} options: {idleTime?: number; timeout?: number} = {}
): Promise<void> { ): Promise<void> {
const { idleTime = 500, timeout = this.#timeoutSettings.timeout() } = const {idleTime = 500, timeout = this.#timeoutSettings.timeout()} = options;
options;
const networkManager = this.#frameManager.networkManager(); const networkManager = this.#frameManager.networkManager();
let idleResolveCallback: () => void; let idleResolveCallback: () => void;
const idlePromise = new Promise<void>((resolve) => { const idlePromise = new Promise<void>(resolve => {
idleResolveCallback = resolve; idleResolveCallback = resolve;
}); });
@ -2081,11 +2072,11 @@ export class Page extends EventEmitter {
...eventPromises, ...eventPromises,
this.#sessionClosePromise(), this.#sessionClosePromise(),
]).then( ]).then(
(r) => { r => {
cleanup(); cleanup();
return r; return r;
}, },
(error) => { error => {
cleanup(); cleanup();
throw error; throw error;
} }
@ -2145,7 +2136,7 @@ export class Page extends EventEmitter {
timeout, timeout,
this.#sessionClosePromise() this.#sessionClosePromise()
), ),
...this.frames().map(async (frame) => { ...this.frames().map(async frame => {
if (await predicate(frame)) { if (await predicate(frame)) {
return frame; return frame;
} }

View File

@ -25,10 +25,7 @@ import {
CustomQueryHandler, CustomQueryHandler,
} from './QueryHandler.js'; } from './QueryHandler.js';
import {Product} from './Product.js'; import {Product} from './Product.js';
import { import {_connectToBrowser, BrowserConnectOptions} from './BrowserConnector.js';
_connectToBrowser,
BrowserConnectOptions,
} from './BrowserConnector.js';
import { import {
PredefinedNetworkConditions, PredefinedNetworkConditions,
networkConditions, networkConditions,

View File

@ -211,7 +211,7 @@ export function _unregisterCustomQueryHandler(name: string): void {
* @internal * @internal
*/ */
export function _customQueryHandlerNames(): string[] { export function _customQueryHandlerNames(): string[] {
return [...queryHandlers.keys()].filter((name) => { return [...queryHandlers.keys()].filter(name => {
return !builtInHandlers.has(name); return !builtInHandlers.has(name);
}); });
} }

View File

@ -84,9 +84,9 @@ export class Target {
this.#defaultViewport = defaultViewport ?? undefined; this.#defaultViewport = defaultViewport ?? undefined;
this.#screenshotTaskQueue = screenshotTaskQueue; this.#screenshotTaskQueue = screenshotTaskQueue;
this._isPageTargetCallback = isPageTargetCallback; this._isPageTargetCallback = isPageTargetCallback;
this._initializedPromise = new Promise<boolean>((fulfill) => { this._initializedPromise = new Promise<boolean>(fulfill => {
return (this._initializedCallback = fulfill); return (this._initializedCallback = fulfill);
}).then(async (success) => { }).then(async success => {
if (!success) { if (!success) {
return false; return false;
} }
@ -102,7 +102,7 @@ export class Target {
openerPage.emit(PageEmittedEvents.Popup, popupPage); openerPage.emit(PageEmittedEvents.Popup, popupPage);
return true; return true;
}); });
this._isClosedPromise = new Promise<void>((fulfill) => { this._isClosedPromise = new Promise<void>(fulfill => {
return (this._closedCallback = fulfill); return (this._closedCallback = fulfill);
}); });
this._isInitialized = this._isInitialized =
@ -132,7 +132,7 @@ export class Target {
*/ */
async page(): Promise<Page | null> { async page(): Promise<Page | null> {
if (this._isPageTargetCallback(this.#targetInfo) && !this.#pagePromise) { if (this._isPageTargetCallback(this.#targetInfo) && !this.#pagePromise) {
this.#pagePromise = this.#sessionFactory().then((client) => { this.#pagePromise = this.#sessionFactory().then(client => {
return Page._create( return Page._create(
client, client,
this, this,
@ -157,7 +157,7 @@ export class Target {
} }
if (!this.#workerPromise) { if (!this.#workerPromise) {
// TODO(einbinder): Make workers send their console logs. // TODO(einbinder): Make workers send their console logs.
this.#workerPromise = this.#sessionFactory().then((client) => { this.#workerPromise = this.#sessionFactory().then(client => {
return new WebWorker( return new WebWorker(
client, client,
this.#targetInfo.url, this.#targetInfo.url,

View File

@ -83,24 +83,20 @@ export class Tracing {
'disabled-by-default-devtools.timeline.stack', 'disabled-by-default-devtools.timeline.stack',
'disabled-by-default-v8.cpu_profiler', 'disabled-by-default-v8.cpu_profiler',
]; ];
const { const {path, screenshots = false, categories = defaultCategories} = options;
path,
screenshots = false,
categories = defaultCategories,
} = options;
if (screenshots) { if (screenshots) {
categories.push('disabled-by-default-devtools.screenshot'); categories.push('disabled-by-default-devtools.screenshot');
} }
const excludedCategories = categories const excludedCategories = categories
.filter((cat) => { .filter(cat => {
return cat.startsWith('-'); return cat.startsWith('-');
}) })
.map((cat) => { .map(cat => {
return cat.slice(1); return cat.slice(1);
}); });
const includedCategories = categories.filter((cat) => { const includedCategories = categories.filter(cat => {
return !cat.startsWith('-'); return !cat.startsWith('-');
}); });
@ -126,7 +122,7 @@ export class Tracing {
resolve = x; resolve = x;
reject = y; reject = y;
}); });
this.#client.once('Tracing.tracingComplete', async (event) => { this.#client.once('Tracing.tracingComplete', async event => {
try { try {
const readable = await getReadableFromProtocolStream( const readable = await getReadableFromProtocolStream(
this.#client, this.#client,

View File

@ -79,14 +79,14 @@ export class WebWorker extends EventEmitter {
super(); super();
this.#client = client; this.#client = client;
this.#url = url; this.#url = url;
this.#executionContextPromise = new Promise<ExecutionContext>((x) => { this.#executionContextPromise = new Promise<ExecutionContext>(x => {
return (this.#executionContextCallback = x); return (this.#executionContextCallback = x);
}); });
let jsHandleFactory: JSHandleFactory; let jsHandleFactory: JSHandleFactory;
this.#client.once('Runtime.executionContextCreated', async (event) => { this.#client.once('Runtime.executionContextCreated', async event => {
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
jsHandleFactory = (remoteObject) => { jsHandleFactory = remoteObject => {
return new JSHandle(executionContext, client, remoteObject); return new JSHandle(executionContext, client, remoteObject);
}; };
const executionContext = new ExecutionContext(client, event.context); const executionContext = new ExecutionContext(client, event.context);
@ -95,14 +95,14 @@ export class WebWorker extends EventEmitter {
// This might fail if the target is closed before we receive all execution contexts. // This might fail if the target is closed before we receive all execution contexts.
this.#client.send('Runtime.enable').catch(debugError); this.#client.send('Runtime.enable').catch(debugError);
this.#client.on('Runtime.consoleAPICalled', (event) => { this.#client.on('Runtime.consoleAPICalled', event => {
return consoleAPICalled( return consoleAPICalled(
event.type, event.type,
event.args.map(jsHandleFactory), event.args.map(jsHandleFactory),
event.stackTrace event.stackTrace
); );
}); });
this.#client.on('Runtime.exceptionThrown', (exception) => { this.#client.on('Runtime.exceptionThrown', exception => {
return exceptionThrown(exception.exceptionDetails); return exceptionThrown(exception.exceptionDetails);
}); });
} }

View File

@ -85,7 +85,7 @@ export async function releaseObject(
} }
await client await client
.send('Runtime.releaseObject', {objectId: remoteObject.objectId}) .send('Runtime.releaseObject', {objectId: remoteObject.objectId})
.catch((error) => { .catch(error => {
// Exceptions might happen in case of a page been navigated or closed. // Exceptions might happen in case of a page been navigated or closed.
// Swallow these since they are harmless and we don't leak anything in this case. // Swallow these since they are harmless and we don't leak anything in this case.
debugError(error); debugError(error);
@ -142,7 +142,7 @@ export async function waitForEvent<T>(
resolveCallback = resolve; resolveCallback = resolve;
rejectCallback = reject; rejectCallback = reject;
}); });
const listener = addEventListener(emitter, eventName, async (event) => { const listener = addEventListener(emitter, eventName, async event => {
if (!(await predicate(event))) { if (!(await predicate(event))) {
return; return;
} }
@ -160,11 +160,11 @@ export async function waitForEvent<T>(
clearTimeout(eventTimeout); clearTimeout(eventTimeout);
} }
const result = await Promise.race([promise, abortPromise]).then( const result = await Promise.race([promise, abortPromise]).then(
(r) => { r => {
cleanup(); cleanup();
return r; return r;
}, },
(error) => { error => {
cleanup(); cleanup();
throw error; throw error;
} }

View File

@ -142,8 +142,8 @@ const unlinkAsync = promisify(fs.unlink.bind(fs));
const chmodAsync = promisify(fs.chmod.bind(fs)); const chmodAsync = promisify(fs.chmod.bind(fs));
function existsAsync(filePath: string): Promise<boolean> { function existsAsync(filePath: string): Promise<boolean> {
return new Promise((resolve) => { return new Promise(resolve => {
fs.access(filePath, (err) => { fs.access(filePath, err => {
return resolve(!err); return resolve(!err);
}); });
}); });
@ -288,16 +288,16 @@ export class BrowserFetcher {
this.#downloadHost, this.#downloadHost,
revision revision
); );
return new Promise((resolve) => { return new Promise(resolve => {
const request = httpRequest( const request = httpRequest(
url, url,
'HEAD', 'HEAD',
(response) => { response => {
resolve(response.statusCode === 200); resolve(response.statusCode === 200);
}, },
false false
); );
request.on('error', (error) => { request.on('error', error => {
console.error(error); console.error(error);
resolve(false); resolve(false);
}); });
@ -367,7 +367,7 @@ export class BrowserFetcher {
} }
const fileNames = await readdirAsync(this.#downloadsFolder); const fileNames = await readdirAsync(this.#downloadsFolder);
return fileNames return fileNames
.map((fileName) => { .map(fileName => {
return parseFolderPath(this.#product, fileName); return parseFolderPath(this.#product, fileName);
}) })
.filter( .filter(
@ -377,7 +377,7 @@ export class BrowserFetcher {
return (entry && entry.platform === this.#platform) ?? false; return (entry && entry.platform === this.#platform) ?? false;
} }
) )
.map((entry) => { .map(entry => {
return entry.revision; return entry.revision;
}); });
} }
@ -395,7 +395,7 @@ export class BrowserFetcher {
await existsAsync(folderPath), await existsAsync(folderPath),
`Failed to remove: revision ${revision} is not downloaded` `Failed to remove: revision ${revision} is not downloaded`
); );
await new Promise((fulfill) => { await new Promise(fulfill => {
return removeRecursive(folderPath, fulfill); return removeRecursive(folderPath, fulfill);
}); });
} }
@ -516,7 +516,7 @@ function _downloadFile(
let downloadedBytes = 0; let downloadedBytes = 0;
let totalBytes = 0; let totalBytes = 0;
const request = httpRequest(url, 'GET', (response) => { const request = httpRequest(url, 'GET', response => {
if (response.statusCode !== 200) { if (response.statusCode !== 200) {
const error = new Error( const error = new Error(
`Download failed: server returned code ${response.statusCode}. URL: ${url}` `Download failed: server returned code ${response.statusCode}. URL: ${url}`
@ -530,7 +530,7 @@ function _downloadFile(
file.on('finish', () => { file.on('finish', () => {
return fulfill(); return fulfill();
}); });
file.on('error', (error) => { file.on('error', error => {
return reject(error); return reject(error);
}); });
response.pipe(file); response.pipe(file);
@ -539,7 +539,7 @@ function _downloadFile(
response.on('data', onData); response.on('data', onData);
} }
}); });
request.on('error', (error) => { request.on('error', error => {
return reject(error); return reject(error);
}); });
return promise; return promise;
@ -596,8 +596,8 @@ function _installDMG(dmgPath: string, folderPath: string): Promise<void> {
} }
mountPath = volumes[0]!; mountPath = volumes[0]!;
readdirAsync(mountPath) readdirAsync(mountPath)
.then((fileNames) => { .then(fileNames => {
const appName = fileNames.find((item) => { const appName = fileNames.find(item => {
return typeof item === 'string' && item.endsWith('.app'); return typeof item === 'string' && item.endsWith('.app');
}); });
if (!appName) { if (!appName) {
@ -605,7 +605,7 @@ function _installDMG(dmgPath: string, folderPath: string): Promise<void> {
} }
const copyPath = path.join(mountPath!, appName); const copyPath = path.join(mountPath!, appName);
debugFetcher(`Copying ${copyPath} to ${folderPath}`); debugFetcher(`Copying ${copyPath} to ${folderPath}`);
childProcess.exec(`cp -R "${copyPath}" "${folderPath}"`, (err) => { childProcess.exec(`cp -R "${copyPath}" "${folderPath}"`, err => {
if (err) { if (err) {
reject(err); reject(err);
} else { } else {
@ -616,7 +616,7 @@ function _installDMG(dmgPath: string, folderPath: string): Promise<void> {
.catch(reject); .catch(reject);
}); });
}) })
.catch((error) => { .catch(error => {
console.error(error); console.error(error);
}) })
.finally((): void => { .finally((): void => {
@ -625,7 +625,7 @@ function _installDMG(dmgPath: string, folderPath: string): Promise<void> {
} }
const unmountCommand = `hdiutil detach "${mountPath}" -quiet`; const unmountCommand = `hdiutil detach "${mountPath}" -quiet`;
debugFetcher(`Unmounting ${mountPath}`); debugFetcher(`Unmounting ${mountPath}`);
childProcess.exec(unmountCommand, (err) => { childProcess.exec(unmountCommand, err => {
if (err) { if (err) {
console.error(`Error unmounting dmg: ${err}`); console.error(`Error unmounting dmg: ${err}`);
} }

View File

@ -181,7 +181,7 @@ export class BrowserRunner {
this.kill(); this.kill();
} else if (this.connection) { } else if (this.connection) {
// Attempt to close the browser gracefully // Attempt to close the browser gracefully
this.connection.send('Browser.close').catch((error) => { this.connection.send('Browser.close').catch(error => {
debugError(error); debugError(error);
this.kill(); this.kill();
}); });
@ -200,7 +200,7 @@ export class BrowserRunner {
const proc = this.proc; const proc = this.proc;
try { try {
if (process.platform === 'win32') { if (process.platform === 'win32') {
childProcess.exec(`taskkill /pid ${this.proc.pid} /T /F`, (error) => { childProcess.exec(`taskkill /pid ${this.proc.pid} /T /F`, error => {
if (error) { if (error) {
// taskkill can fail to kill the process e.g. due to missing permissions. // taskkill can fail to kill the process e.g. due to missing permissions.
// Let's kill the process via Node API. This delays killing of all child // Let's kill the process via Node API. This delays killing of all child
@ -292,7 +292,7 @@ function waitForWSEndpoint(
addEventListener(browserProcess, 'exit', () => { addEventListener(browserProcess, 'exit', () => {
return onClose(); return onClose();
}), }),
addEventListener(browserProcess, 'error', (error) => { addEventListener(browserProcess, 'error', error => {
return onClose(error); return onClose(error);
}), }),
]; ];

View File

@ -102,7 +102,7 @@ class ChromeLauncher implements ProductLauncher {
chromeArguments.push(...this.defaultArgs(options)); chromeArguments.push(...this.defaultArgs(options));
} else if (Array.isArray(ignoreDefaultArgs)) { } else if (Array.isArray(ignoreDefaultArgs)) {
chromeArguments.push( chromeArguments.push(
...this.defaultArgs(options).filter((arg) => { ...this.defaultArgs(options).filter(arg => {
return !ignoreDefaultArgs.includes(arg); return !ignoreDefaultArgs.includes(arg);
}) })
); );
@ -111,7 +111,7 @@ class ChromeLauncher implements ProductLauncher {
} }
if ( if (
!chromeArguments.some((argument) => { !chromeArguments.some(argument => {
return argument.startsWith('--remote-debugging-'); return argument.startsWith('--remote-debugging-');
}) })
) { ) {
@ -130,7 +130,7 @@ class ChromeLauncher implements ProductLauncher {
// Check for the user data dir argument, which will always be set even // Check for the user data dir argument, which will always be set even
// with a custom directory specified via the userDataDir option. // with a custom directory specified via the userDataDir option.
let userDataDirIndex = chromeArguments.findIndex((arg) => { let userDataDirIndex = chromeArguments.findIndex(arg => {
return arg.startsWith('--user-data-dir'); return arg.startsWith('--user-data-dir');
}); });
if (userDataDirIndex < 0) { if (userDataDirIndex < 0) {
@ -205,7 +205,7 @@ class ChromeLauncher implements ProductLauncher {
if (waitForInitialPage) { if (waitForInitialPage) {
try { try {
await browser.waitForTarget( await browser.waitForTarget(
(t) => { t => {
return t.type() === 'page'; return t.type() === 'page';
}, },
{timeout} {timeout}
@ -272,7 +272,7 @@ class ChromeLauncher implements ProductLauncher {
); );
} }
if ( if (
args.every((arg) => { args.every(arg => {
return arg.startsWith('-'); return arg.startsWith('-');
}) })
) { ) {
@ -348,7 +348,7 @@ class FirefoxLauncher implements ProductLauncher {
firefoxArguments.push(...this.defaultArgs(options)); firefoxArguments.push(...this.defaultArgs(options));
} else if (Array.isArray(ignoreDefaultArgs)) { } else if (Array.isArray(ignoreDefaultArgs)) {
firefoxArguments.push( firefoxArguments.push(
...this.defaultArgs(options).filter((arg) => { ...this.defaultArgs(options).filter(arg => {
return !ignoreDefaultArgs.includes(arg); return !ignoreDefaultArgs.includes(arg);
}) })
); );
@ -357,7 +357,7 @@ class FirefoxLauncher implements ProductLauncher {
} }
if ( if (
!firefoxArguments.some((argument) => { !firefoxArguments.some(argument => {
return argument.startsWith('--remote-debugging-'); return argument.startsWith('--remote-debugging-');
}) })
) { ) {
@ -375,7 +375,7 @@ class FirefoxLauncher implements ProductLauncher {
// Check for the profile argument, which will always be set even // Check for the profile argument, which will always be set even
// with a custom directory specified via the userDataDir option. // with a custom directory specified via the userDataDir option.
const profileArgIndex = firefoxArguments.findIndex((arg) => { const profileArgIndex = firefoxArguments.findIndex(arg => {
return ['-profile', '--profile'].includes(arg); return ['-profile', '--profile'].includes(arg);
}); });
@ -450,7 +450,7 @@ class FirefoxLauncher implements ProductLauncher {
if (waitForInitialPage) { if (waitForInitialPage) {
try { try {
await browser.waitForTarget( await browser.waitForTarget(
(t) => { t => {
return t.type() === 'page'; return t.type() === 'page';
}, },
{timeout} {timeout}
@ -516,7 +516,7 @@ class FirefoxLauncher implements ProductLauncher {
firefoxArguments.push('--devtools'); firefoxArguments.push('--devtools');
} }
if ( if (
args.every((arg) => { args.every(arg => {
return arg.startsWith('-'); return arg.startsWith('-');
}) })
) { ) {

View File

@ -56,7 +56,7 @@ export class NodeWebSocketTransport implements ConnectionTransport {
constructor(ws: NodeWebSocket) { constructor(ws: NodeWebSocket) {
this.#ws = ws; this.#ws = ws;
this.#ws.addEventListener('message', (event) => { this.#ws.addEventListener('message', event => {
if (this.onmessage) { if (this.onmessage) {
this.onmessage.call(null, event.data); this.onmessage.call(null, event.data);
} }

View File

@ -38,7 +38,7 @@ export class PipeTransport implements ConnectionTransport {
) { ) {
this.#pipeWrite = pipeWrite; this.#pipeWrite = pipeWrite;
this.#eventListeners = [ this.#eventListeners = [
addEventListener(pipeRead, 'data', (buffer) => { addEventListener(pipeRead, 'data', buffer => {
return this.#dispatch(buffer); return this.#dispatch(buffer);
}), }),
addEventListener(pipeRead, 'close', () => { addEventListener(pipeRead, 'close', () => {

View File

@ -20,10 +20,7 @@ import {
ConnectOptions, ConnectOptions,
} from '../common/Puppeteer.js'; } from '../common/Puppeteer.js';
import {BrowserFetcher, BrowserFetcherOptions} from './BrowserFetcher.js'; import {BrowserFetcher, BrowserFetcherOptions} from './BrowserFetcher.js';
import { import {LaunchOptions, BrowserLaunchArgumentOptions} from './LaunchOptions.js';
LaunchOptions,
BrowserLaunchArgumentOptions,
} from './LaunchOptions.js';
import {BrowserConnectOptions} from '../common/BrowserConnector.js'; import {BrowserConnectOptions} from '../common/BrowserConnector.js';
import {Browser} from '../common/Browser.js'; import {Browser} from '../common/Browser.js';
import Launcher, {ProductLauncher} from './Launcher.js'; import Launcher, {ProductLauncher} from './Launcher.js';

View File

@ -20,9 +20,7 @@ import URL from 'url';
import puppeteer from '../puppeteer.js'; import puppeteer from '../puppeteer.js';
import {PUPPETEER_REVISIONS} from '../revisions.js'; import {PUPPETEER_REVISIONS} from '../revisions.js';
import {PuppeteerNode} from './Puppeteer.js'; import {PuppeteerNode} from './Puppeteer.js';
import createHttpsProxyAgent, { import createHttpsProxyAgent, {HttpsProxyAgentOptions} from 'https-proxy-agent';
HttpsProxyAgentOptions,
} from 'https-proxy-agent';
import {getProxyForUrl} from 'proxy-from-env'; import {getProxyForUrl} from 'proxy-from-env';
const supportedProducts = { const supportedProducts = {
@ -70,7 +68,7 @@ export async function downloadBrowser(): Promise<void> {
} else if (product === 'firefox') { } else if (product === 'firefox') {
(puppeteer as PuppeteerNode)._preferredRevision = (puppeteer as PuppeteerNode)._preferredRevision =
PUPPETEER_REVISIONS.firefox; PUPPETEER_REVISIONS.firefox;
return getFirefoxNightlyVersion().catch((error) => { return getFirefoxNightlyVersion().catch(error => {
console.error(error); console.error(error);
process.exit(1); process.exit(1);
}); });
@ -111,10 +109,10 @@ export async function downloadBrowser(): Promise<void> {
logPolitely( logPolitely(
`${supportedProducts[product]} (${revisionInfo.revision}) downloaded to ${revisionInfo.folderPath}` `${supportedProducts[product]} (${revisionInfo.revision}) downloaded to ${revisionInfo.folderPath}`
); );
localRevisions = localRevisions.filter((revision) => { localRevisions = localRevisions.filter(revision => {
return revision !== revisionInfo.revision; return revision !== revisionInfo.revision;
}); });
const cleanupOldVersions = localRevisions.map((revision) => { const cleanupOldVersions = localRevisions.map(revision => {
return browserFetcher.remove(revision); return browserFetcher.remove(revision);
}); });
Promise.all([...cleanupOldVersions]); Promise.all([...cleanupOldVersions]);
@ -189,11 +187,11 @@ export async function downloadBrowser(): Promise<void> {
`Requesting latest Firefox Nightly version from ${firefoxVersionsUrl}` `Requesting latest Firefox Nightly version from ${firefoxVersionsUrl}`
); );
https https
.get(firefoxVersionsUrl, requestOptions, (r) => { .get(firefoxVersionsUrl, requestOptions, r => {
if (r.statusCode && r.statusCode >= 400) { if (r.statusCode && r.statusCode >= 400) {
return reject(new Error(`Got status code ${r.statusCode}`)); return reject(new Error(`Got status code ${r.statusCode}`));
} }
r.on('data', (chunk) => { r.on('data', chunk => {
data += chunk; data += chunk;
}); });
r.on('end', () => { r.on('end', () => {

View File

@ -48,7 +48,7 @@ describeChromeOnly('Target.createCDPSession', function () {
const client = await page.target().createCDPSession(); const client = await page.target().createCDPSession();
await client.send('Network.enable'); await client.send('Network.enable');
const events = []; const events = [];
client.on('Network.requestWillBeSent', (event) => { client.on('Network.requestWillBeSent', event => {
return events.push(event); return events.push(event);
}); });
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -99,7 +99,7 @@ describeChromeOnly('Target.createCDPSession', function () {
const {page} = getTestState(); const {page} = 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 => {
return error; return error;
}); });
expect(error.stack).toContain('theSourceOfTheProblems'); expect(error.stack).toContain('theSourceOfTheProblems');

View File

@ -491,12 +491,10 @@ describeFailsFirefox('Accessibility', function () {
await page.setContent(`<button>My Button</button>`); await page.setContent(`<button>My Button</button>`);
const button = (await page.$('button'))!; const button = (await page.$('button'))!;
await page.$eval('button', (button) => { await page.$eval('button', button => {
return button.remove(); return button.remove();
}); });
expect(await page.accessibility.snapshot({ root: button })).toEqual( expect(await page.accessibility.snapshot({root: button})).toEqual(null);
null
);
}); });
it('should support the interestingOnly option', async () => { it('should support the interestingOnly option', async () => {
const {page} = getTestState(); const {page} = getTestState();

View File

@ -174,7 +174,7 @@ describeChromeOnly('AriaQueryHandler', () => {
); );
const divs = await page.$$('aria/menu div'); const divs = await page.$$('aria/menu div');
const ids = await Promise.all( const ids = await Promise.all(
divs.map((n) => { divs.map(n => {
return n.evaluate((div: Element) => { return n.evaluate((div: Element) => {
return div.id; return div.id;
}); });
@ -196,7 +196,7 @@ describeChromeOnly('AriaQueryHandler', () => {
} }
` `
); );
const sum = await page.$$eval('aria/[role="button"]', (buttons) => { const sum = await page.$$eval('aria/[role="button"]', buttons => {
return buttons.reduce((acc, button) => { return buttons.reduce((acc, button) => {
return acc + Number(button.textContent); return acc + Number(button.textContent);
}, 0); }, 0);
@ -348,7 +348,7 @@ describeChromeOnly('AriaQueryHandler', () => {
let waitError!: Error; let waitError!: Error;
const waitPromise = frame! const waitPromise = frame!
.waitForSelector('aria/does-not-exist') .waitForSelector('aria/does-not-exist')
.catch((error) => { .catch(error => {
return (waitError = error); return (waitError = error);
}); });
await utils.detachFrame(page, 'frame1'); await utils.detachFrame(page, 'frame1');
@ -507,7 +507,7 @@ describeChromeOnly('AriaQueryHandler', () => {
let error!: Error; let error!: Error;
await page await page
.waitForSelector('aria/[role="button"]', {timeout: 10}) .waitForSelector('aria/[role="button"]', {timeout: 10})
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeTruthy(); expect(error).toBeTruthy();
@ -524,7 +524,7 @@ describeChromeOnly('AriaQueryHandler', () => {
let error!: Error; let error!: Error;
await page await page
.waitForSelector('aria/[role="main"]', {hidden: true, timeout: 10}) .waitForSelector('aria/[role="main"]', {hidden: true, timeout: 10})
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeTruthy(); expect(error).toBeTruthy();
@ -566,9 +566,7 @@ describeChromeOnly('AriaQueryHandler', () => {
const {page} = getTestState(); const {page} = getTestState();
let error!: Error; let error!: Error;
await page await page.waitForSelector('aria/zombo', {timeout: 10}).catch(error_ => {
.waitForSelector('aria/zombo', { timeout: 10 })
.catch((error_) => {
return (error = error_); return (error = error_);
}); });
expect(error!.stack).toContain('waiting for selector `zombo` failed'); expect(error!.stack).toContain('waiting for selector `zombo` failed');
@ -626,7 +624,7 @@ describeChromeOnly('AriaQueryHandler', () => {
}); });
const getIds = async (elements: ElementHandle[]) => { const getIds = async (elements: ElementHandle[]) => {
return Promise.all( return Promise.all(
elements.map((element) => { elements.map(element => {
return element.evaluate((element: Element) => { return element.evaluate((element: Element) => {
return element.id; return element.id;
}); });

View File

@ -30,7 +30,7 @@ describe('BrowserContext', function () {
const defaultContext = browser.browserContexts()[0]!; const defaultContext = browser.browserContexts()[0]!;
expect(defaultContext!.isIncognito()).toBe(false); expect(defaultContext!.isIncognito()).toBe(false);
let error!: Error; let error!: Error;
await defaultContext!.close().catch((error_) => { await defaultContext!.close().catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(browser.defaultBrowserContext()).toBe(defaultContext); expect(browser.defaultBrowserContext()).toBe(defaultContext);
@ -68,7 +68,7 @@ describe('BrowserContext', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const [popupTarget] = await Promise.all([ const [popupTarget] = await Promise.all([
utils.waitEvent(browser, 'targetcreated'), utils.waitEvent(browser, 'targetcreated'),
page.evaluate<(url: string) => void>((url) => { page.evaluate<(url: string) => void>(url => {
return window.open(url); return window.open(url);
}, server.EMPTY_PAGE), }, server.EMPTY_PAGE),
]); ]);
@ -80,13 +80,13 @@ describe('BrowserContext', function () {
const context = await browser.createIncognitoBrowserContext(); 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());
}); });
context.on('targetchanged', (target) => { context.on('targetchanged', target => {
return events.push('CHANGED: ' + target.url()); return events.push('CHANGED: ' + target.url());
}); });
context.on('targetdestroyed', (target) => { context.on('targetdestroyed', target => {
return events.push('DESTROYED: ' + target.url()); return events.push('DESTROYED: ' + target.url());
}); });
const page = await context.newPage(); const page = await context.newPage();
@ -105,14 +105,14 @@ describe('BrowserContext', function () {
const context = await browser.createIncognitoBrowserContext(); const context = await browser.createIncognitoBrowserContext();
let resolved = false; let resolved = false;
const targetPromise = context.waitForTarget((target) => { const targetPromise = context.waitForTarget(target => {
return target.url() === server.EMPTY_PAGE; return target.url() === server.EMPTY_PAGE;
}); });
targetPromise targetPromise
.then(() => { .then(() => {
return (resolved = true); return (resolved = true);
}) })
.catch((error) => { .catch(error => {
resolved = true; resolved = true;
if (error instanceof puppeteer.errors.TimeoutError) { if (error instanceof puppeteer.errors.TimeoutError) {
console.error(error); console.error(error);
@ -142,14 +142,14 @@ describe('BrowserContext', function () {
const context = await browser.createIncognitoBrowserContext(); const context = await browser.createIncognitoBrowserContext();
const error = await context const error = await context
.waitForTarget( .waitForTarget(
(target) => { target => {
return target.url() === server.EMPTY_PAGE; return target.url() === server.EMPTY_PAGE;
}, },
{ {
timeout: 1, timeout: 1,
} }
) )
.catch((error_) => { .catch(error_ => {
return error_; return error_;
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);

View File

@ -71,7 +71,7 @@ describeChromeOnly('Chromium-Specific Launcher tests', function () {
browserURL, browserURL,
browserWSEndpoint: originalBrowser.wsEndpoint(), browserWSEndpoint: originalBrowser.wsEndpoint(),
}) })
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain( expect(error.message).toContain(
@ -91,7 +91,7 @@ describeChromeOnly('Chromium-Specific Launcher tests', function () {
const browserURL = 'http://127.0.0.1:32333'; const browserURL = 'http://127.0.0.1:32333';
let error!: Error; let error!: Error;
await puppeteer.connect({ browserURL }).catch((error_) => { await puppeteer.connect({browserURL}).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain( expect(error.message).toContain(
@ -128,7 +128,7 @@ describeChromeOnly('Chromium-Specific Launcher tests', function () {
const {defaultBrowserOptions, puppeteer} = getTestState(); const {defaultBrowserOptions, puppeteer} = getTestState();
const options = Object.assign({pipe: true}, defaultBrowserOptions); const options = Object.assign({pipe: true}, defaultBrowserOptions);
const browser = await puppeteer.launch(options); const browser = await puppeteer.launch(options);
const disconnectedEventPromise = new Promise((resolve) => { const disconnectedEventPromise = new Promise(resolve => {
return browser.once('disconnected', resolve); return browser.once('disconnected', resolve);
}); });
// Emulate user exiting browser. // Emulate user exiting browser.
@ -159,7 +159,7 @@ describeChromeOnly('Chromium-Specific Page Tests', function () {
}); });
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue(); return request.continue();
}); });
await page.goto(server.PREFIX + '/intervention'); await page.goto(server.PREFIX + '/intervention');

View File

@ -163,7 +163,7 @@ describe('Page.click', function () {
await page.goto(server.PREFIX + '/offscreenbuttons.html'); await page.goto(server.PREFIX + '/offscreenbuttons.html');
const messages: any[] = []; const messages: any[] = [];
page.on('console', (msg) => { page.on('console', msg => {
return messages.push(msg.text()); return messages.push(msg.text());
}); });
for (let i = 0; i < 11; ++i) { for (let i = 0; i < 11; ++i) {
@ -270,7 +270,7 @@ describe('Page.click', function () {
await page.goto(server.PREFIX + '/input/button.html'); await page.goto(server.PREFIX + '/input/button.html');
let error!: Error; let error!: Error;
await page.click('button.does-not-exist').catch((error_) => { await page.click('button.does-not-exist').catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toBe( expect(error.message).toBe(

View File

@ -240,7 +240,7 @@ describe('Cookie specs', () => {
const cookieStrings = await page.evaluate(() => { const cookieStrings = await page.evaluate(() => {
const cookies = document.cookie.split(';'); const cookies = document.cookie.split(';');
return cookies return cookies
.map((cookie) => { .map(cookie => {
return cookie.trim(); return cookie.trim();
}) })
.sort(); .sort();
@ -430,9 +430,9 @@ describe('Cookie specs', () => {
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'});
await page.evaluate<(src: string) => Promise<void>>((src) => { await page.evaluate<(src: string) => Promise<void>>(src => {
let fulfill!: () => void; let fulfill!: () => void;
const promise = new Promise<void>((x) => { const promise = new Promise<void>(x => {
return (fulfill = x); return (fulfill = x);
}); });
const iframe = document.createElement('iframe') as HTMLIFrameElement; const iframe = document.createElement('iframe') as HTMLIFrameElement;
@ -488,8 +488,7 @@ describe('Cookie specs', () => {
itFailsFirefox( itFailsFirefox(
'should set secure same-site cookies from a frame', 'should set secure same-site cookies from a frame',
async () => { async () => {
const { httpsServer, puppeteer, defaultBrowserOptions } = const {httpsServer, puppeteer, defaultBrowserOptions} = getTestState();
getTestState();
const browser = await puppeteer.launch({ const browser = await puppeteer.launch({
...defaultBrowserOptions, ...defaultBrowserOptions,
@ -500,9 +499,9 @@ describe('Cookie specs', () => {
try { try {
await page.goto(httpsServer.PREFIX + '/grid.html'); await page.goto(httpsServer.PREFIX + '/grid.html');
await page.evaluate<(src: string) => Promise<void>>((src) => { await page.evaluate<(src: string) => Promise<void>>(src => {
let fulfill!: () => void; let fulfill!: () => void;
const promise = new Promise<void>((x) => { const promise = new Promise<void>(x => {
return (fulfill = x); return (fulfill = x);
}); });
const iframe = document.createElement('iframe'); const iframe = document.createElement('iframe');

View File

@ -65,7 +65,7 @@ describe('Coverage specs', function () {
await page.goto(server.PREFIX + '/jscoverage/eval.html'); await page.goto(server.PREFIX + '/jscoverage/eval.html');
const coverage = await page.coverage.stopJSCoverage(); const coverage = await page.coverage.stopJSCoverage();
expect( expect(
coverage.find((entry) => { coverage.find(entry => {
return entry.url.startsWith('debugger://'); return entry.url.startsWith('debugger://');
}) })
).not.toBe(null); ).not.toBe(null);
@ -287,14 +287,14 @@ describe('Coverage specs', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.coverage.startCSSCoverage(); await page.coverage.startCSSCoverage();
await page.evaluate<(url: string) => Promise<void>>(async (url) => { await page.evaluate<(url: string) => Promise<void>>(async url => {
document.body.textContent = 'hello, world'; document.body.textContent = 'hello, world';
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.href = url; link.href = url;
document.head.appendChild(link); document.head.appendChild(link);
await new Promise((x) => { await new Promise(x => {
return (link.onload = x); return (link.onload = x);
}); });
}, server.PREFIX + '/csscoverage/stylesheet1.css'); }, server.PREFIX + '/csscoverage/stylesheet1.css');

View File

@ -30,7 +30,7 @@ describe('Page.Events.Dialog', function () {
it('should fire', async () => { it('should fire', async () => {
const {page} = getTestState(); const {page} = getTestState();
const onDialog = sinon.stub().callsFake((dialog) => { const onDialog = sinon.stub().callsFake(dialog => {
dialog.accept(); dialog.accept();
}); });
page.on('dialog', onDialog); page.on('dialog', onDialog);
@ -49,7 +49,7 @@ describe('Page.Events.Dialog', function () {
itFailsFirefox('should allow accepting prompts', async () => { itFailsFirefox('should allow accepting prompts', async () => {
const {page} = getTestState(); const {page} = getTestState();
const onDialog = sinon.stub().callsFake((dialog) => { const onDialog = sinon.stub().callsFake(dialog => {
dialog.accept('answer!'); dialog.accept('answer!');
}); });
page.on('dialog', onDialog); page.on('dialog', onDialog);
@ -69,7 +69,7 @@ describe('Page.Events.Dialog', function () {
it('should dismiss the prompt', async () => { it('should dismiss the prompt', async () => {
const {page} = getTestState(); const {page} = getTestState();
page.on('dialog', (dialog) => { page.on('dialog', dialog => {
dialog.dismiss(); dialog.dismiss();
}); });
const result = await page.evaluate(() => { const result = await page.evaluate(() => {

View File

@ -209,7 +209,7 @@ describe('ElementHandle specs', function () {
return document.querySelector('button')!.firstChild; return document.querySelector('button')!.firstChild;
}); });
let error!: Error; let error!: Error;
await buttonTextNode.click().catch((error_) => { await buttonTextNode.click().catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toBe('Node is not of type HTMLElement'); expect(error.message).toBe('Node is not of type HTMLElement');
@ -223,7 +223,7 @@ describe('ElementHandle specs', function () {
return button.remove(); return button.remove();
}, button); }, button);
let error!: Error; let error!: Error;
await button.click().catch((error_) => { await button.click().catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toBe('Node is detached from document'); expect(error.message).toBe('Node is detached from document');
@ -236,7 +236,7 @@ describe('ElementHandle specs', function () {
await page.evaluate((button: HTMLElement) => { await page.evaluate((button: HTMLElement) => {
return (button.style.display = 'none'); return (button.style.display = 'none');
}, button); }, button);
const error = await button.click().catch((error_) => { const error = await button.click().catch(error_ => {
return error_; return error_;
}); });
expect(error.message).toBe( expect(error.message).toBe(
@ -251,7 +251,7 @@ describe('ElementHandle specs', function () {
await page.evaluate((button: HTMLElement) => { await page.evaluate((button: HTMLElement) => {
return (button.parentElement!.style.display = 'none'); return (button.parentElement!.style.display = 'none');
}, button); }, button);
const error = await button.click().catch((error_) => { const error = await button.click().catch(error_ => {
return error_; return error_;
}); });
expect(error.message).toBe( expect(error.message).toBe(
@ -263,7 +263,7 @@ describe('ElementHandle specs', function () {
await page.setContent('hello<br>goodbye'); await page.setContent('hello<br>goodbye');
const br = (await page.$('br'))!; const br = (await page.$('br'))!;
const error = await br.click().catch((error_) => { const error = await br.click().catch(error_ => {
return error_; return error_;
}); });
expect(error.message).toBe( expect(error.message).toBe(
@ -284,13 +284,13 @@ describe('ElementHandle specs', function () {
expect(element).toBeDefined(); expect(element).toBeDefined();
const innerWaitFor = element.waitForSelector('.bar'); const innerWaitFor = element.waitForSelector('.bar');
await element.evaluate((el) => { await element.evaluate(el => {
el.innerHTML = '<div class="bar">bar1</div>'; el.innerHTML = '<div class="bar">bar1</div>';
}); });
element = (await innerWaitFor)!; element = (await innerWaitFor)!;
expect(element).toBeDefined(); expect(element).toBeDefined();
expect( expect(
await element.evaluate((el) => { await element.evaluate(el => {
return (el as HTMLElement).innerText; return (el as HTMLElement).innerText;
}) })
).toStrictEqual('bar1'); ).toStrictEqual('bar1');
@ -316,13 +316,13 @@ describe('ElementHandle specs', function () {
const el2 = (await page.waitForSelector('#el1'))!; const el2 = (await page.waitForSelector('#el1'))!;
expect( expect(
await (await el2.waitForXPath('//div'))!.evaluate((el) => { await (await el2.waitForXPath('//div'))!.evaluate(el => {
return el.id; return el.id;
}) })
).toStrictEqual('el2'); ).toStrictEqual('el2');
expect( expect(
await (await el2.waitForXPath('.//div'))!.evaluate((el) => { await (await el2.waitForXPath('.//div'))!.evaluate(el => {
return el.id; return el.id;
}) })
).toStrictEqual('el2'); ).toStrictEqual('el2');
@ -401,7 +401,7 @@ describe('ElementHandle specs', function () {
}); });
const element = (await page.$('getById/foo'))!; const element = (await page.$('getById/foo'))!;
expect( expect(
await page.evaluate<(element: HTMLElement) => string>((element) => { await page.evaluate<(element: HTMLElement) => string>(element => {
return element.id; return element.id;
}, element) }, element)
).toBe('foo'); ).toBe('foo');
@ -453,9 +453,9 @@ describe('ElementHandle specs', function () {
}); });
const elements = await page.$$('getByClass/foo'); const elements = await page.$$('getByClass/foo');
const classNames = await Promise.all( const classNames = await Promise.all(
elements.map(async (element) => { elements.map(async element => {
return await page.evaluate<(element: HTMLElement) => string>( return await page.evaluate<(element: HTMLElement) => string>(
(element) => { element => {
return element.className; return element.className;
}, },
element element
@ -475,7 +475,7 @@ describe('ElementHandle specs', function () {
return document.querySelectorAll(`.${selector}`); return document.querySelectorAll(`.${selector}`);
}, },
}); });
const elements = await page.$$eval('getByClass/foo', (divs) => { const elements = await page.$$eval('getByClass/foo', divs => {
return divs.length; return divs.length;
}); });
@ -517,14 +517,14 @@ describe('ElementHandle specs', function () {
const innerWaitFor = element.waitForSelector('getByClass/bar'); const innerWaitFor = element.waitForSelector('getByClass/bar');
await element.evaluate((el) => { await element.evaluate(el => {
el.innerHTML = '<div class="bar">bar1</div>'; el.innerHTML = '<div class="bar">bar1</div>';
}); });
element = (await innerWaitFor)!; element = (await innerWaitFor)!;
expect(element).toBeDefined(); expect(element).toBeDefined();
expect( expect(
await element.evaluate((el) => { await element.evaluate(el => {
return (el as HTMLElement).innerText; return (el as HTMLElement).innerText;
}) })
).toStrictEqual('bar1'); ).toStrictEqual('bar1');
@ -583,14 +583,14 @@ describe('ElementHandle specs', function () {
}, },
}); });
const txtContent = await page.$eval('getByClass/foo', (div) => { const txtContent = await page.$eval('getByClass/foo', div => {
return div.textContent; return div.textContent;
}); });
expect(txtContent).toBe('text'); expect(txtContent).toBe('text');
const txtContents = await page.$$eval('getByClass/foo', (divs) => { const txtContents = await page.$$eval('getByClass/foo', divs => {
return divs return divs
.map((d) => { .map(d => {
return d.textContent; return d.textContent;
}) })
.join(''); .join('');

View File

@ -91,7 +91,7 @@ describe('Emulation', () => {
function dispatchTouch() { function dispatchTouch() {
let fulfill!: (value: string) => void; let fulfill!: (value: string) => void;
const promise = new Promise((x) => { const promise = new Promise(x => {
fulfill = x; fulfill = x;
}); });
window.ontouchstart = () => { window.ontouchstart = () => {
@ -232,7 +232,7 @@ describe('Emulation', () => {
const {page} = getTestState(); const {page} = getTestState();
let error!: Error; let error!: Error;
await page.emulateMediaType('bad').catch((error_) => { await page.emulateMediaType('bad').catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toBe('Unsupported media type: bad'); expect(error.message).toBe('Unsupported media type: bad');
@ -363,7 +363,7 @@ describe('Emulation', () => {
let error!: Error; let error!: Error;
await page await page
.emulateMediaFeatures([{name: 'bad', value: ''}]) .emulateMediaFeatures([{name: 'bad', value: ''}])
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toBe('Unsupported media feature: bad'); expect(error.message).toBe('Unsupported media feature: bad');
@ -414,11 +414,11 @@ describe('Emulation', () => {
const {page} = getTestState(); const {page} = getTestState();
let error!: Error; let error!: Error;
await page.emulateTimezone('Foo/Bar').catch((error_) => { await page.emulateTimezone('Foo/Bar').catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toBe('Invalid timezone ID: Foo/Bar'); expect(error.message).toBe('Invalid timezone ID: Foo/Bar');
await page.emulateTimezone('Baz/Qux').catch((error_) => { await page.emulateTimezone('Baz/Qux').catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toBe('Invalid timezone ID: Baz/Qux'); expect(error.message).toBe('Invalid timezone ID: Baz/Qux');
@ -482,7 +482,7 @@ describe('Emulation', () => {
await page await page
// @ts-expect-error deliberately passign invalid deficiency // @ts-expect-error deliberately passign invalid deficiency
.emulateVisionDeficiency('invalid') .emulateVisionDeficiency('invalid')
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toBe('Unsupported vision deficiency: invalid'); expect(error.message).toBe('Unsupported vision deficiency: invalid');

View File

@ -50,7 +50,7 @@ describe('Evaluation specs', function () {
it('should transfer NaN', async () => { it('should transfer NaN', async () => {
const {page} = getTestState(); const {page} = getTestState();
const result = await page.evaluate((a) => { const result = await page.evaluate(a => {
return a; return a;
}, NaN); }, NaN);
expect(Object.is(result, NaN)).toBe(true); expect(Object.is(result, NaN)).toBe(true);
@ -58,7 +58,7 @@ describe('Evaluation specs', function () {
it('should transfer -0', async () => { it('should transfer -0', async () => {
const {page} = getTestState(); const {page} = getTestState();
const result = await page.evaluate((a) => { const result = await page.evaluate(a => {
return a; return a;
}, -0); }, -0);
expect(Object.is(result, -0)).toBe(true); expect(Object.is(result, -0)).toBe(true);
@ -66,7 +66,7 @@ describe('Evaluation specs', function () {
it('should transfer Infinity', async () => { it('should transfer Infinity', async () => {
const {page} = getTestState(); const {page} = getTestState();
const result = await page.evaluate((a) => { const result = await page.evaluate(a => {
return a; return a;
}, Infinity); }, Infinity);
expect(Object.is(result, Infinity)).toBe(true); expect(Object.is(result, Infinity)).toBe(true);
@ -74,7 +74,7 @@ describe('Evaluation specs', function () {
it('should transfer -Infinity', async () => { it('should transfer -Infinity', async () => {
const {page} = getTestState(); const {page} = getTestState();
const result = await page.evaluate((a) => { const result = await page.evaluate(a => {
return a; return a;
}, -Infinity); }, -Infinity);
expect(Object.is(result, -Infinity)).toBe(true); expect(Object.is(result, -Infinity)).toBe(true);
@ -83,7 +83,7 @@ describe('Evaluation specs', function () {
const {page} = getTestState(); const {page} = getTestState();
const result = await page.evaluate( const result = await page.evaluate(
(a) => { a => {
return a; return a;
}, },
[1, 2, 3] [1, 2, 3]
@ -94,7 +94,7 @@ describe('Evaluation specs', function () {
const {page} = getTestState(); const {page} = getTestState();
const result = await page.evaluate( const result = await page.evaluate(
(a) => { a => {
return Array.isArray(a); return Array.isArray(a);
}, },
[1, 2, 3] [1, 2, 3]
@ -146,7 +146,7 @@ describe('Evaluation specs', function () {
const {page} = getTestState(); const {page} = getTestState();
const result = await page.evaluate( const result = await page.evaluate(
(a) => { a => {
return a['中文字符']; return a['中文字符'];
}, },
{ {
@ -164,7 +164,7 @@ describe('Evaluation specs', function () {
location.reload(); location.reload();
return new Promise(() => {}); return new Promise(() => {});
}) })
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain('Protocol error'); expect(error.message).toContain('Protocol error');
@ -181,7 +181,7 @@ describe('Evaluation specs', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
let frameEvaluation = null; let frameEvaluation = null;
page.on('framenavigated', async (frame) => { page.on('framenavigated', async frame => {
frameEvaluation = frame.evaluate(() => { frameEvaluation = frame.evaluate(() => {
return 6 * 7; return 6 * 7;
}); });
@ -219,7 +219,7 @@ describe('Evaluation specs', function () {
// @ts-expect-error we know the object doesn't exist // @ts-expect-error we know the object doesn't exist
return notExistingObject.property; return notExistingObject.property;
}) })
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeTruthy(); expect(error).toBeTruthy();
@ -233,7 +233,7 @@ describe('Evaluation specs', function () {
.evaluate(() => { .evaluate(() => {
throw 'qwerty'; throw 'qwerty';
}) })
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeTruthy(); expect(error).toBeTruthy();
@ -247,7 +247,7 @@ describe('Evaluation specs', function () {
.evaluate(() => { .evaluate(() => {
throw 100500; throw 100500;
}) })
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeTruthy(); expect(error).toBeTruthy();
@ -257,7 +257,7 @@ describe('Evaluation specs', function () {
const {page} = getTestState(); const {page} = getTestState();
const object = {foo: 'bar!'}; const object = {foo: 'bar!'};
const result = await page.evaluate((a) => { const result = await page.evaluate(a => {
return a; return a;
}, object); }, object);
expect(result).not.toBe(object); expect(result).not.toBe(object);
@ -353,16 +353,14 @@ describe('Evaluation specs', function () {
const windowHandle = await page.evaluateHandle(() => { const windowHandle = await page.evaluateHandle(() => {
return window; return window;
}); });
const errorText = await windowHandle const errorText = await windowHandle.jsonValue<string>().catch(error_ => {
.jsonValue<string>()
.catch((error_) => {
return error_.message; return error_.message;
}); });
const error = await page const error = await page
.evaluate<(errorText: string) => Error>((errorText) => { .evaluate<(errorText: string) => Error>(errorText => {
throw new Error(errorText); throw new Error(errorText);
}, errorText) }, errorText)
.catch((error_) => { .catch(error_ => {
return error_; return error_;
}); });
expect(error.message).toContain(errorText); expect(error.message).toContain(errorText);
@ -390,7 +388,7 @@ describe('Evaluation specs', function () {
await page.setContent('<section>42</section>'); await page.setContent('<section>42</section>');
const element = (await page.$('section'))!; const element = (await page.$('section'))!;
const text = await page.evaluate((e) => { const text = await page.evaluate(e => {
return e.textContent; return e.textContent;
}, element); }, element);
expect(text).toBe('42'); expect(text).toBe('42');
@ -407,7 +405,7 @@ describe('Evaluation specs', function () {
.evaluate((e: HTMLElement) => { .evaluate((e: HTMLElement) => {
return e.textContent; return e.textContent;
}, element) }, element)
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain('JSHandle is disposed'); expect(error.message).toContain('JSHandle is disposed');
@ -424,7 +422,7 @@ describe('Evaluation specs', function () {
.evaluate((body: HTMLElement) => { .evaluate((body: HTMLElement) => {
return body.innerHTML; return body.innerHTML;
}, bodyHandle) }, bodyHandle)
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeTruthy(); expect(error).toBeTruthy();
@ -458,7 +456,7 @@ describe('Evaluation specs', function () {
.evaluate(() => { .evaluate(() => {
return null; return null;
}) })
.catch((error_) => { .catch(error_ => {
return error_; return error_;
}); });
expect((error as Error).message).toContain('navigation'); expect((error as Error).message).toContain('navigation');
@ -494,7 +492,7 @@ describe('Evaluation specs', function () {
throw new Error('Error in promise'); throw new Error('Error in promise');
}); });
}) })
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain('Error in promise'); expect(error.message).toContain('Error in promise');
@ -530,7 +528,7 @@ describe('Evaluation specs', function () {
).toBe(123); ).toBe(123);
// Make sure CSP works. // Make sure CSP works.
await page.addScriptTag({ content: 'window.e = 10;' }).catch((error) => { await page.addScriptTag({content: 'window.e = 10;'}).catch(error => {
return void error; return void error;
}); });
expect( expect(

View File

@ -36,10 +36,10 @@ describe('Fixtures', function () {
puppeteerPath, puppeteerPath,
JSON.stringify(options), JSON.stringify(options),
]); ]);
res.stderr.on('data', (data) => { res.stderr.on('data', data => {
return (dumpioData += data.toString('utf8')); return (dumpioData += data.toString('utf8'));
}); });
await new Promise((resolve) => { await new Promise(resolve => {
return res.on('close', resolve); return res.on('close', resolve);
}); });
expect(dumpioData).toContain('message from dumpio'); expect(dumpioData).toContain('message from dumpio');
@ -55,10 +55,10 @@ describe('Fixtures', function () {
puppeteerPath, puppeteerPath,
JSON.stringify(options), JSON.stringify(options),
]); ]);
res.stderr.on('data', (data) => { res.stderr.on('data', data => {
return (dumpioData += data.toString('utf8')); return (dumpioData += data.toString('utf8'));
}); });
await new Promise((resolve) => { await new Promise(resolve => {
return res.on('close', resolve); return res.on('close', resolve);
}); });
expect(dumpioData).toContain('DevTools listening on ws://'); expect(dumpioData).toContain('DevTools listening on ws://');
@ -77,11 +77,11 @@ describe('Fixtures', function () {
JSON.stringify(options), JSON.stringify(options),
]); ]);
let wsEndPointCallback: (value: string) => void; let wsEndPointCallback: (value: string) => void;
const wsEndPointPromise = new Promise<string>((x) => { const wsEndPointPromise = new Promise<string>(x => {
return (wsEndPointCallback = x); return (wsEndPointCallback = x);
}); });
let output = ''; let output = '';
res.stdout.on('data', (data) => { res.stdout.on('data', data => {
output += data; output += data;
if (output.indexOf('\n')) { if (output.indexOf('\n')) {
wsEndPointCallback(output.substring(0, output.indexOf('\n'))); wsEndPointCallback(output.substring(0, output.indexOf('\n')));
@ -91,10 +91,10 @@ describe('Fixtures', function () {
browserWSEndpoint: await wsEndPointPromise, browserWSEndpoint: await wsEndPointPromise,
}); });
const promises = [ const promises = [
new Promise((resolve) => { new Promise(resolve => {
return browser.once('disconnected', resolve); return browser.once('disconnected', resolve);
}), }),
new Promise((resolve) => { new Promise(resolve => {
return res.on('close', resolve); return res.on('close', resolve);
}), }),
]; ];

View File

@ -94,7 +94,7 @@ describe('Frame specs', function () {
.evaluate(() => { .evaluate(() => {
return 7 * 8; return 7 * 8;
}) })
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain( expect(error.message).toContain(
@ -110,7 +110,7 @@ describe('Frame specs', function () {
// This test checks if Frame.evaluate allows a readonly array to be an argument. // This test checks if Frame.evaluate allows a readonly array to be an argument.
// See https://github.com/puppeteer/puppeteer/issues/6953. // See https://github.com/puppeteer/puppeteer/issues/6953.
const readonlyArray: readonly string[] = ['a', 'b', 'c']; const readonlyArray: readonly string[] = ['a', 'b', 'c'];
await mainFrame.evaluate((arr) => { await mainFrame.evaluate(arr => {
return arr; return arr;
}, readonlyArray); }, readonlyArray);
}); });
@ -137,7 +137,7 @@ describe('Frame specs', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
// validate frameattached events // validate frameattached events
const attachedFrames: Frame[] = []; const attachedFrames: Frame[] = [];
page.on('frameattached', (frame) => { page.on('frameattached', frame => {
return attachedFrames.push(frame); return attachedFrames.push(frame);
}); });
await utils.attachFrame(page, 'frame1', './assets/frame.html'); await utils.attachFrame(page, 'frame1', './assets/frame.html');
@ -146,7 +146,7 @@ describe('Frame specs', function () {
// validate framenavigated events // validate framenavigated events
const navigatedFrames: Frame[] = []; const navigatedFrames: Frame[] = [];
page.on('framenavigated', (frame) => { page.on('framenavigated', frame => {
return navigatedFrames.push(frame); return navigatedFrames.push(frame);
}); });
await utils.navigateFrame(page, 'frame1', './empty.html'); await utils.navigateFrame(page, 'frame1', './empty.html');
@ -155,7 +155,7 @@ describe('Frame specs', function () {
// validate framedetached events // validate framedetached events
const detachedFrames: Frame[] = []; const detachedFrames: Frame[] = [];
page.on('framedetached', (frame) => { page.on('framedetached', frame => {
return detachedFrames.push(frame); return detachedFrames.push(frame);
}); });
await utils.detachFrame(page, 'frame1'); await utils.detachFrame(page, 'frame1');
@ -200,13 +200,13 @@ describe('Frame specs', function () {
let attachedFrames = []; let attachedFrames = [];
let detachedFrames = []; let detachedFrames = [];
let navigatedFrames = []; let navigatedFrames = [];
page.on('frameattached', (frame) => { page.on('frameattached', frame => {
return attachedFrames.push(frame); return attachedFrames.push(frame);
}); });
page.on('framedetached', (frame) => { page.on('framedetached', frame => {
return detachedFrames.push(frame); return detachedFrames.push(frame);
}); });
page.on('framenavigated', (frame) => { page.on('framenavigated', frame => {
return navigatedFrames.push(frame); return navigatedFrames.push(frame);
}); });
await page.goto(server.PREFIX + '/frames/nested-frames.html'); await page.goto(server.PREFIX + '/frames/nested-frames.html');
@ -228,13 +228,13 @@ describe('Frame specs', function () {
let attachedFrames = []; let attachedFrames = [];
let detachedFrames = []; let detachedFrames = [];
let navigatedFrames = []; let navigatedFrames = [];
page.on('frameattached', (frame) => { page.on('frameattached', frame => {
return attachedFrames.push(frame); return attachedFrames.push(frame);
}); });
page.on('framedetached', (frame) => { page.on('framedetached', frame => {
return detachedFrames.push(frame); return detachedFrames.push(frame);
}); });
page.on('framenavigated', (frame) => { page.on('framenavigated', frame => {
return navigatedFrames.push(frame); return navigatedFrames.push(frame);
}); });
await page.goto(server.PREFIX + '/frames/frameset.html'); await page.goto(server.PREFIX + '/frames/frameset.html');
@ -258,7 +258,7 @@ describe('Frame specs', function () {
const frame = document.createElement('iframe'); const frame = document.createElement('iframe');
frame.src = url; frame.src = url;
document.body.shadowRoot!.appendChild(frame); document.body.shadowRoot!.appendChild(frame);
await new Promise((x) => { await new Promise(x => {
return (frame.onload = x); return (frame.onload = x);
}); });
}, server.EMPTY_PAGE); }, server.EMPTY_PAGE);
@ -274,7 +274,7 @@ describe('Frame specs', function () {
frame.name = 'theFrameName'; frame.name = 'theFrameName';
frame.src = url; frame.src = url;
document.body.appendChild(frame); document.body.appendChild(frame);
return new Promise((x) => { return new Promise(x => {
return (frame.onload = x); return (frame.onload = x);
}); });
}, server.EMPTY_PAGE); }, server.EMPTY_PAGE);
@ -333,7 +333,7 @@ describe('Frame specs', function () {
await page.goto(server.PREFIX + '/frames/lazy-frame.html'); await page.goto(server.PREFIX + '/frames/lazy-frame.html');
expect( expect(
page.frames().map((frame) => { page.frames().map(frame => {
return frame._hasStartedLoading; return frame._hasStartedLoading;
}) })
).toEqual([true, true, false]); ).toEqual([true, true, false]);

View File

@ -166,7 +166,7 @@ describeChromeOnly('headful tests', function () {
); );
}, },
}); });
const devtoolsPageTarget = await browser.waitForTarget((target) => { const devtoolsPageTarget = await browser.waitForTarget(target => {
return target.type() === 'other'; return target.type() === 'other';
}); });
const page = (await devtoolsPageTarget.page())!; const page = (await devtoolsPageTarget.page())!;
@ -238,7 +238,7 @@ describeChromeOnly('headful tests', function () {
const frame = document.createElement('iframe'); const frame = document.createElement('iframe');
frame.setAttribute('src', 'https://google.com/'); frame.setAttribute('src', 'https://google.com/');
document.body.appendChild(frame); document.body.appendChild(frame);
return new Promise((x) => { return new Promise(x => {
return (frame.onload = x); return (frame.onload = x);
}); });
}); });
@ -307,7 +307,7 @@ describeChromeOnly('headful tests', function () {
}); });
await browser.close(); await browser.close();
const requests = networkEvents.map((event) => { const requests = networkEvents.map(event => {
return event.request.url; return event.request.url;
}); });
expect(requests).toContain(`http://oopifdomain:${server.PORT}/fetch`); expect(requests).toContain(`http://oopifdomain:${server.PORT}/fetch`);
@ -407,7 +407,7 @@ describeChromeOnly('headful tests', function () {
expect(screenshots[i]).toBeGolden(`grid-cell-${i}.png`); expect(screenshots[i]).toBeGolden(`grid-cell-${i}.png`);
} }
await Promise.all( await Promise.all(
pages.map((page) => { pages.map(page => {
return page.close(); return page.close();
}) })
); );

View File

@ -92,7 +92,7 @@ describe('ignoreHTTPSErrors', function () {
httpsServer.setRedirect('/plzredirect', '/empty.html'); httpsServer.setRedirect('/plzredirect', '/empty.html');
const responses: HTTPResponse[] = []; const responses: HTTPResponse[] = [];
page.on('response', (response) => { page.on('response', response => {
return responses.push(response); return responses.push(response);
}); });
const [serverRequest] = await Promise.all([ const [serverRequest] = await Promise.all([
@ -113,7 +113,7 @@ describe('ignoreHTTPSErrors', function () {
const {httpsServer} = getTestState(); const {httpsServer} = 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_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeUndefined(); expect(error).toBeUndefined();
@ -123,7 +123,7 @@ describe('ignoreHTTPSErrors', function () {
const {httpsServer} = getTestState(); const {httpsServer} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue(); return request.continue();
}); });
const response = (await page.goto(httpsServer.EMPTY_PAGE))!; const response = (await page.goto(httpsServer.EMPTY_PAGE))!;

View File

@ -38,10 +38,10 @@ describe('input tests', function () {
const input = (await page.$('input'))!; const input = (await page.$('input'))!;
await page.evaluate((e: HTMLElement) => { await page.evaluate((e: HTMLElement) => {
(globalThis as any)._inputEvents = []; (globalThis as any)._inputEvents = [];
e.addEventListener('change', (ev) => { e.addEventListener('change', ev => {
return (globalThis as any)._inputEvents.push(ev.type); return (globalThis as any)._inputEvents.push(ev.type);
}); });
e.addEventListener('input', (ev) => { e.addEventListener('input', ev => {
return (globalThis as any)._inputEvents.push(ev.type); return (globalThis as any)._inputEvents.push(ev.type);
}); });
}, input); }, input);
@ -64,7 +64,7 @@ describe('input tests', function () {
expect( expect(
await page.evaluate((e: HTMLInputElement) => { await page.evaluate((e: HTMLInputElement) => {
const reader = new FileReader(); const reader = new FileReader();
const promise = new Promise((fulfill) => { const promise = new Promise(fulfill => {
return (reader.onload = fulfill); return (reader.onload = fulfill);
}); });
reader.readAsText(e.files![0]!); reader.readAsText(e.files![0]!);
@ -104,7 +104,7 @@ describe('input tests', function () {
const {page, puppeteer} = getTestState(); const {page, puppeteer} = getTestState();
let error!: Error; let error!: Error;
await page.waitForFileChooser({ timeout: 1 }).catch((error_) => { await page.waitForFileChooser({timeout: 1}).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -114,7 +114,7 @@ describe('input tests', function () {
page.setDefaultTimeout(1); page.setDefaultTimeout(1);
let error!: Error; let error!: Error;
await page.waitForFileChooser().catch((error_) => { await page.waitForFileChooser().catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -124,7 +124,7 @@ describe('input tests', function () {
page.setDefaultTimeout(0); page.setDefaultTimeout(0);
let error!: Error; let error!: Error;
await page.waitForFileChooser({ timeout: 1 }).catch((error_) => { await page.waitForFileChooser({timeout: 1}).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -151,7 +151,7 @@ describe('input tests', function () {
const [fileChooser1, fileChooser2] = await Promise.all([ const [fileChooser1, fileChooser2] = await Promise.all([
page.waitForFileChooser(), page.waitForFileChooser(),
page.waitForFileChooser(), page.waitForFileChooser(),
page.$eval('input', (input) => { page.$eval('input', input => {
return (input as HTMLInputElement).click(); return (input as HTMLInputElement).click();
}), }),
]); ]);
@ -172,17 +172,17 @@ describe('input tests', function () {
]); ]);
await Promise.all([ await Promise.all([
chooser.accept([FILE_TO_UPLOAD]), chooser.accept([FILE_TO_UPLOAD]),
new Promise((x) => { new Promise(x => {
return page.once('metrics', x); return page.once('metrics', x);
}), }),
]); ]);
expect( expect(
await page.$eval('input', (input) => { await page.$eval('input', input => {
return (input as HTMLInputElement).files!.length; return (input as HTMLInputElement).files!.length;
}) })
).toBe(1); ).toBe(1);
expect( expect(
await page.$eval('input', (input) => { await page.$eval('input', input => {
return (input as HTMLInputElement).files![0]!.name; return (input as HTMLInputElement).files![0]!.name;
}) })
).toBe('file-to-upload.txt'); ).toBe('file-to-upload.txt');
@ -191,18 +191,18 @@ describe('input tests', function () {
const {page} = getTestState(); const {page} = getTestState();
await page.setContent(`<input type=file>`); await page.setContent(`<input type=file>`);
page.waitForFileChooser().then((chooser) => { page.waitForFileChooser().then(chooser => {
return chooser.accept([FILE_TO_UPLOAD]); return chooser.accept([FILE_TO_UPLOAD]);
}); });
expect( expect(
await page.$eval('input', async (picker) => { await page.$eval('input', async picker => {
const pick = picker as HTMLInputElement; const pick = picker as HTMLInputElement;
pick.click(); pick.click();
await new Promise((x) => { await new Promise(x => {
return (pick.oninput = x); return (pick.oninput = x);
}); });
const reader = new FileReader(); const reader = new FileReader();
const promise = new Promise((fulfill) => { const promise = new Promise(fulfill => {
return (reader.onload = fulfill); return (reader.onload = fulfill);
}); });
reader.readAsText(pick.files![0]!); reader.readAsText(pick.files![0]!);
@ -216,27 +216,27 @@ describe('input tests', function () {
const {page} = getTestState(); const {page} = getTestState();
await page.setContent(`<input type=file>`); await page.setContent(`<input type=file>`);
page.waitForFileChooser().then((chooser) => { page.waitForFileChooser().then(chooser => {
return chooser.accept([FILE_TO_UPLOAD]); return chooser.accept([FILE_TO_UPLOAD]);
}); });
expect( expect(
await page.$eval('input', async (picker) => { await page.$eval('input', async picker => {
const pick = picker as HTMLInputElement; const pick = picker as HTMLInputElement;
pick.click(); pick.click();
await new Promise((x) => { await new Promise(x => {
return (pick.oninput = x); return (pick.oninput = x);
}); });
return pick.files!.length; return pick.files!.length;
}) })
).toBe(1); ).toBe(1);
page.waitForFileChooser().then((chooser) => { page.waitForFileChooser().then(chooser => {
return chooser.accept([]); return chooser.accept([]);
}); });
expect( expect(
await page.$eval('input', async (picker) => { await page.$eval('input', async picker => {
const pick = picker as HTMLInputElement; const pick = picker as HTMLInputElement;
pick.click(); pick.click();
await new Promise((x) => { await new Promise(x => {
return (pick.oninput = x); return (pick.oninput = x);
}); });
return pick.files!.length; return pick.files!.length;
@ -260,7 +260,7 @@ describe('input tests', function () {
), ),
path.relative(process.cwd(), __dirname + '/../assets/pptr.png'), path.relative(process.cwd(), __dirname + '/../assets/pptr.png'),
]) ])
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).not.toBe(null); expect(error).not.toBe(null);
@ -274,7 +274,7 @@ describe('input tests', function () {
page.click('input'), page.click('input'),
]); ]);
let error!: Error; let error!: Error;
await chooser.accept(['file-does-not-exist.txt']).catch((error_) => { await chooser.accept(['file-does-not-exist.txt']).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeUndefined(); expect(error).toBeUndefined();
@ -283,18 +283,18 @@ describe('input tests', function () {
const {page} = getTestState(); const {page} = getTestState();
await page.setContent(`<input type=file>`); await page.setContent(`<input type=file>`);
page.waitForFileChooser().then((chooser) => { page.waitForFileChooser().then(chooser => {
return chooser.accept(['file-does-not-exist.txt']); return chooser.accept(['file-does-not-exist.txt']);
}); });
expect( expect(
await page.$eval('input', async (picker) => { await page.$eval('input', async picker => {
const pick = picker as HTMLInputElement; const pick = picker as HTMLInputElement;
pick.click(); pick.click();
await new Promise((x) => { await new Promise(x => {
return (pick.oninput = x); return (pick.oninput = x);
}); });
const reader = new FileReader(); const reader = new FileReader();
const promise = new Promise((fulfill) => { const promise = new Promise(fulfill => {
return (reader.onerror = fulfill); return (reader.onerror = fulfill);
}); });
reader.readAsText(pick.files![0]!); reader.readAsText(pick.files![0]!);
@ -310,13 +310,13 @@ describe('input tests', function () {
await page.setContent(`<input type=file>`); await page.setContent(`<input type=file>`);
const [fileChooser] = await Promise.all([ const [fileChooser] = await Promise.all([
page.waitForFileChooser(), page.waitForFileChooser(),
page.$eval('input', (input) => { page.$eval('input', input => {
return (input as HTMLInputElement).click(); return (input as HTMLInputElement).click();
}), }),
]); ]);
await fileChooser.accept([]); await fileChooser.accept([]);
let error!: Error; let error!: Error;
await fileChooser.accept([]).catch((error_) => { await fileChooser.accept([]).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toBe( expect(error.message).toBe(
@ -335,7 +335,7 @@ describe('input tests', function () {
await page.setContent(`<input type=file>`); await page.setContent(`<input type=file>`);
const [fileChooser1] = await Promise.all([ const [fileChooser1] = await Promise.all([
page.waitForFileChooser(), page.waitForFileChooser(),
page.$eval('input', (input) => { page.$eval('input', input => {
return (input as HTMLInputElement).click(); return (input as HTMLInputElement).click();
}), }),
]); ]);
@ -343,7 +343,7 @@ describe('input tests', function () {
// If this resolves, than we successfully canceled file chooser. // If this resolves, than we successfully canceled file chooser.
await Promise.all([ await Promise.all([
page.waitForFileChooser(), page.waitForFileChooser(),
page.$eval('input', (input) => { page.$eval('input', input => {
return (input as HTMLInputElement).click(); return (input as HTMLInputElement).click();
}), }),
]); ]);
@ -354,7 +354,7 @@ describe('input tests', function () {
await page.setContent(`<input type=file>`); await page.setContent(`<input type=file>`);
const [fileChooser] = await Promise.all([ const [fileChooser] = await Promise.all([
page.waitForFileChooser(), page.waitForFileChooser(),
page.$eval('input', (input) => { page.$eval('input', input => {
return (input as HTMLElement).click(); return (input as HTMLElement).click();
}), }),
]); ]);

View File

@ -54,7 +54,7 @@ describe('JSHandle', function () {
const aHandle = await page.evaluateHandle(() => { const aHandle = await page.evaluateHandle(() => {
return 5; return 5;
}); });
const isFive = await page.evaluate((e) => { const isFive = await page.evaluate(e => {
return Object.is(e, 5); return Object.is(e, 5);
}, aHandle); }, aHandle);
expect(isFive).toBeTruthy(); expect(isFive).toBeTruthy();
@ -67,13 +67,13 @@ describe('JSHandle', function () {
let error!: Error; let error!: Error;
await page await page
.evaluateHandle( .evaluateHandle(
(opts) => { opts => {
return opts.elem; return opts.elem;
}, },
// @ts-expect-error we are deliberately passing a bad type here (nested object) // @ts-expect-error we are deliberately passing a bad type here (nested object)
{test} {test}
) )
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain('Recursive objects are not allowed.'); expect(error.message).toContain('Recursive objects are not allowed.');
@ -85,7 +85,7 @@ describe('JSHandle', function () {
return Infinity; return Infinity;
}); });
expect( expect(
await page.evaluate((e) => { await page.evaluate(e => {
return Object.is(e, Infinity); return Object.is(e, Infinity);
}, aHandle) }, aHandle)
).toBe(true); ).toBe(true);
@ -181,7 +181,7 @@ describe('JSHandle', function () {
const windowHandle = await page.evaluateHandle('window'); const windowHandle = await page.evaluateHandle('window');
let error!: Error; let error!: Error;
await windowHandle.jsonValue().catch((error_) => { await windowHandle.jsonValue().catch(error_ => {
return (error = error_); return (error = error_);
}); });
if (isChrome) { if (isChrome) {
@ -358,7 +358,7 @@ describe('JSHandle', function () {
`; `;
}); });
await page.evaluate(async () => { await page.evaluate(async () => {
return new Promise((resolve) => { return new Promise(resolve => {
return window.requestAnimationFrame(resolve); return window.requestAnimationFrame(resolve);
}); });
}); });
@ -388,7 +388,7 @@ describe('JSHandle', function () {
`; `;
}); });
await page.evaluate(async () => { await page.evaluate(async () => {
return new Promise((resolve) => { return new Promise(resolve => {
return window.requestAnimationFrame(resolve); return window.requestAnimationFrame(resolve);
}); });
}); });
@ -426,7 +426,7 @@ describe('JSHandle', function () {
document.body.innerHTML = ` document.body.innerHTML = `
<div style="cursor: pointer; width: 120px; height: 60px; margin: 30px; padding: 15px;"></div> <div style="cursor: pointer; width: 120px; height: 60px; margin: 30px; padding: 15px;"></div>
`; `;
document.body.addEventListener('click', (e) => { document.body.addEventListener('click', e => {
(window as any).reportClick(e.clientX, e.clientY); (window as any).reportClick(e.clientX, e.clientY);
}); });
}); });

View File

@ -49,8 +49,8 @@ describe('Keyboard', function () {
const {page, isFirefox} = getTestState(); const {page, isFirefox} = getTestState();
await page.evaluate(() => { await page.evaluate(() => {
(window as any).keyPromise = new Promise((resolve) => { (window as any).keyPromise = new Promise(resolve => {
return document.addEventListener('keydown', (event) => { return document.addEventListener('keydown', event => {
return resolve(event.key); return resolve(event.key);
}); });
}); });
@ -106,7 +106,7 @@ describe('Keyboard', function () {
await page.evaluate(() => { await page.evaluate(() => {
return window.addEventListener( return window.addEventListener(
'keydown', 'keydown',
(e) => { e => {
return e.preventDefault(); return e.preventDefault();
}, },
true true
@ -149,7 +149,7 @@ describe('Keyboard', function () {
await page.evaluate(() => { await page.evaluate(() => {
return window.addEventListener( return window.addEventListener(
'keydown', 'keydown',
(e) => { e => {
return e.preventDefault(); return e.preventDefault();
}, },
true true
@ -333,7 +333,7 @@ describe('Keyboard', function () {
await page.evaluate(() => { await page.evaluate(() => {
window.addEventListener( window.addEventListener(
'keydown', 'keydown',
(event) => { event => {
event.stopPropagation(); event.stopPropagation();
event.stopImmediatePropagation(); event.stopImmediatePropagation();
if (event.key === 'l') { if (event.key === 'l') {
@ -361,7 +361,7 @@ describe('Keyboard', function () {
await page.evaluate(() => { await page.evaluate(() => {
return document.querySelector('textarea')!.addEventListener( return document.querySelector('textarea')!.addEventListener(
'keydown', 'keydown',
(e) => { e => {
return ((globalThis as any).lastEvent = e); return ((globalThis as any).lastEvent = e);
}, },
true true
@ -417,7 +417,7 @@ describe('Keyboard', function () {
await page.evaluate(() => { await page.evaluate(() => {
window.addEventListener( window.addEventListener(
'keydown', 'keydown',
(event) => { event => {
return ((globalThis as any).keyLocation = event.location); return ((globalThis as any).keyLocation = event.location);
}, },
true true
@ -443,19 +443,19 @@ describe('Keyboard', function () {
let error = await page.keyboard let error = await page.keyboard
// @ts-expect-error bad input // @ts-expect-error bad input
.press('NotARealKey') .press('NotARealKey')
.catch((error_) => { .catch(error_ => {
return error_; return error_;
}); });
expect(error.message).toBe('Unknown key: "NotARealKey"'); expect(error.message).toBe('Unknown key: "NotARealKey"');
// @ts-expect-error bad input // @ts-expect-error bad input
error = await page.keyboard.press('ё').catch((error_) => { error = await page.keyboard.press('ё').catch(error_ => {
return error_; return error_;
}); });
expect(error && error.message).toBe('Unknown key: "ё"'); expect(error && error.message).toBe('Unknown key: "ё"');
// @ts-expect-error bad input // @ts-expect-error bad input
error = await page.keyboard.press('😊').catch((error_) => { error = await page.keyboard.press('😊').catch(error_ => {
return error_; return error_;
}); });
expect(error && error.message).toBe('Unknown key: "😊"'); expect(error && error.message).toBe('Unknown key: "😊"');
@ -466,7 +466,7 @@ describe('Keyboard', function () {
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 🇯🇵');
expect( expect(
await page.$eval('textarea', (textarea) => { await page.$eval('textarea', textarea => {
return (textarea as HTMLInputElement).value; return (textarea as HTMLInputElement).value;
}) })
).toBe('👹 Tokyo street Japan 🇯🇵'); ).toBe('👹 Tokyo street Japan 🇯🇵');
@ -484,7 +484,7 @@ describe('Keyboard', function () {
const textarea = (await frame.$('textarea'))!; const textarea = (await frame.$('textarea'))!;
await textarea.type('👹 Tokyo street Japan 🇯🇵'); await textarea.type('👹 Tokyo street Japan 🇯🇵');
expect( expect(
await frame.$eval('textarea', (textarea) => { await frame.$eval('textarea', textarea => {
return (textarea as HTMLInputElement).value; return (textarea as HTMLInputElement).value;
}) })
).toBe('👹 Tokyo street Japan 🇯🇵'); ).toBe('👹 Tokyo street Japan 🇯🇵');
@ -494,7 +494,7 @@ describe('Keyboard', function () {
await page.evaluate(() => { await page.evaluate(() => {
(globalThis as any).result = null; (globalThis as any).result = null;
document.addEventListener('keydown', (event) => { document.addEventListener('keydown', event => {
(globalThis as any).result = [event.key, event.code, event.metaKey]; (globalThis as any).result = [event.key, event.code, event.metaKey];
}); });
}); });

View File

@ -148,7 +148,7 @@ describe('Launcher specs', function () {
const page = await remote.newPage(); const page = await remote.newPage();
const navigationPromise = page const navigationPromise = page
.goto(server.PREFIX + '/one-style.html', {timeout: 60000}) .goto(server.PREFIX + '/one-style.html', {timeout: 60000})
.catch((error_) => { .catch(error_ => {
return error_; return error_;
}); });
await server.waitForRequest('/one-style.css'); await server.waitForRequest('/one-style.css');
@ -173,7 +173,7 @@ describe('Launcher specs', function () {
const page = await remote.newPage(); const page = await remote.newPage();
const watchdog = page const watchdog = page
.waitForSelector('div', {timeout: 60000}) .waitForSelector('div', {timeout: 60000})
.catch((error_) => { .catch(error_ => {
return error_; return error_;
}); });
remote.disconnect(); remote.disconnect();
@ -192,10 +192,10 @@ describe('Launcher specs', function () {
}); });
const newPage = await remote.newPage(); const newPage = await remote.newPage();
const results = await Promise.all([ const results = await Promise.all([
newPage.waitForRequest(server.EMPTY_PAGE).catch((error) => { newPage.waitForRequest(server.EMPTY_PAGE).catch(error => {
return error; return error;
}), }),
newPage.waitForResponse(server.EMPTY_PAGE).catch((error) => { newPage.waitForResponse(server.EMPTY_PAGE).catch(error => {
return error; return error;
}), }),
browser.close(), browser.close(),
@ -218,7 +218,7 @@ describe('Launcher specs', function () {
.evaluate(() => { .evaluate(() => {
return new Promise(() => {}); return new Promise(() => {});
}) })
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
await browser.close(); await browser.close();
@ -232,7 +232,7 @@ describe('Launcher specs', function () {
const options = Object.assign({}, defaultBrowserOptions, { const options = Object.assign({}, defaultBrowserOptions, {
executablePath: 'random-invalid-path', executablePath: 'random-invalid-path',
}); });
await puppeteer.launch(options).catch((error) => { await puppeteer.launch(options).catch(error => {
return (waitError = error); return (waitError = error);
}); });
expect(waitError.message).toContain('Failed to launch'); expect(waitError.message).toContain('Failed to launch');
@ -401,9 +401,7 @@ describe('Launcher specs', function () {
expect(puppeteer.defaultArgs({userDataDir: 'foo'})).toContain( expect(puppeteer.defaultArgs({userDataDir: 'foo'})).toContain(
'--profile' '--profile'
); );
expect(puppeteer.defaultArgs({ userDataDir: 'foo' })).toContain( expect(puppeteer.defaultArgs({userDataDir: 'foo'})).toContain('foo');
'foo'
);
} else { } else {
expect(puppeteer.defaultArgs()).toContain('-headless'); expect(puppeteer.defaultArgs()).toContain('-headless');
expect(puppeteer.defaultArgs({headless: false})).not.toContain( expect(puppeteer.defaultArgs({headless: false})).not.toContain(
@ -481,7 +479,7 @@ 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, puppeteer} = getTestState(); const {defaultBrowserOptions, puppeteer} = getTestState();
const browser = await puppeteer.launch(defaultBrowserOptions); const browser = await puppeteer.launch(defaultBrowserOptions);
const pages = (await browser.pages()).map((page) => { const pages = (await browser.pages()).map(page => {
return page.url(); return page.url();
}); });
expect(pages).toEqual(['about:blank']); expect(pages).toEqual(['about:blank']);
@ -511,7 +509,7 @@ describe('Launcher specs', function () {
timeout: 1, timeout: 1,
}); });
let error!: Error; let error!: Error;
await puppeteer.launch(options).catch((error_) => { await puppeteer.launch(options).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -577,7 +575,7 @@ describe('Launcher specs', function () {
}); });
let error!: Error; let error!: Error;
await puppeteer.launch(options).catch((error_) => { await puppeteer.launch(options).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain('either pipe or debugging port'); expect(error.message).toContain('either pipe or debugging port');
@ -695,8 +693,7 @@ describe('Launcher specs', function () {
]); ]);
}); });
it('should support ignoreHTTPSErrors option', async () => { it('should support ignoreHTTPSErrors option', async () => {
const { httpsServer, puppeteer, defaultBrowserOptions } = const {httpsServer, puppeteer, defaultBrowserOptions} = getTestState();
getTestState();
const originalBrowser = await puppeteer.launch(defaultBrowserOptions); const originalBrowser = await puppeteer.launch(defaultBrowserOptions);
const browserWSEndpoint = originalBrowser.wsEndpoint(); const browserWSEndpoint = originalBrowser.wsEndpoint();
@ -709,7 +706,7 @@ describe('Launcher specs', function () {
let error!: Error; let error!: Error;
const [serverRequest, response] = await Promise.all([ const [serverRequest, response] = await Promise.all([
httpsServer.waitForRequest('/empty.html'), httpsServer.waitForRequest('/empty.html'),
page.goto(httpsServer.EMPTY_PAGE).catch((error_) => { page.goto(httpsServer.EMPTY_PAGE).catch(error_ => {
return (error = error_); return (error = error_);
}), }),
]); ]);
@ -771,7 +768,7 @@ describe('Launcher specs', function () {
const browser = await puppeteer.connect({browserWSEndpoint}); const browser = await puppeteer.connect({browserWSEndpoint});
const pages = await browser.pages(); const pages = await browser.pages();
const restoredPage = pages.find((page) => { const restoredPage = pages.find(page => {
return page.url() === server.PREFIX + '/frames/nested-frames.html'; return page.url() === server.PREFIX + '/frames/nested-frames.html';
})!; })!;
expect(utils.dumpFrames(restoredPage.mainFrame())).toEqual([ expect(utils.dumpFrames(restoredPage.mainFrame())).toEqual([
@ -800,8 +797,8 @@ describe('Launcher specs', function () {
browserWSEndpoint: browserOne.wsEndpoint(), browserWSEndpoint: browserOne.wsEndpoint(),
}); });
const [page1, page2] = await Promise.all([ const [page1, page2] = await Promise.all([
new Promise<Page>((x) => { new Promise<Page>(x => {
return browserOne.once('targetcreated', (target) => { return browserOne.once('targetcreated', target => {
return x(target.page()); return x(target.page());
}); });
}), }),
@ -830,7 +827,7 @@ describe('Launcher specs', function () {
const browserTwo = await puppeteer.connect({browserWSEndpoint}); const browserTwo = await puppeteer.connect({browserWSEndpoint});
const pages = await browserTwo.pages(); const pages = await browserTwo.pages();
const pageTwo = pages.find((page) => { const pageTwo = pages.find(page => {
return page.url() === server.EMPTY_PAGE; return page.url() === server.EMPTY_PAGE;
})!; })!;
await pageTwo.reload(); await pageTwo.reload();

View File

@ -259,7 +259,7 @@ console.log(
}` }`
); );
process.on('unhandledRejection', (reason) => { process.on('unhandledRejection', reason => {
throw reason; throw reason;
}); });
@ -331,7 +331,7 @@ export const expectCookieEquals = (
const {isChrome} = getTestState(); const {isChrome} = getTestState();
if (!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 {
domain: cookie.domain, domain: cookie.domain,
expires: cookie.expires, expires: cookie.expires,
@ -359,7 +359,7 @@ export const shortWaitForArrayToHaveAtLeastNElements = async (
if (data.length >= minLength) { if (data.length >= minLength) {
break; break;
} }
await new Promise((resolve) => { await new Promise(resolve => {
return setTimeout(resolve, timeout); return setTimeout(resolve, timeout);
}); });
} }

View File

@ -47,8 +47,8 @@ describe('Mouse', function () {
const {page} = getTestState(); const {page} = getTestState();
await page.evaluate(() => { await page.evaluate(() => {
(globalThis as any).clickPromise = new Promise((resolve) => { (globalThis as any).clickPromise = new Promise(resolve => {
document.addEventListener('click', (event) => { document.addEventListener('click', event => {
resolve({ resolve({
type: event.type, type: event.type,
detail: event.detail, detail: event.detail,
@ -165,7 +165,7 @@ describe('Mouse', function () {
await page.evaluate(() => { await page.evaluate(() => {
return document.querySelector('#button-3')!.addEventListener( return document.querySelector('#button-3')!.addEventListener(
'mousedown', 'mousedown',
(e) => { e => {
return ((globalThis as any).lastEvent = e); return ((globalThis as any).lastEvent = e);
}, },
true true
@ -233,7 +233,7 @@ describe('Mouse', function () {
await page.mouse.move(100, 100); await page.mouse.move(100, 100);
await page.evaluate(() => { await page.evaluate(() => {
(globalThis as any).result = []; (globalThis as any).result = [];
document.addEventListener('mousemove', (event) => { document.addEventListener('mousemove', event => {
(globalThis as any).result.push([event.clientX, event.clientY]); (globalThis as any).result.push([event.clientX, event.clientY]);
}); });
}); });
@ -254,7 +254,7 @@ describe('Mouse', function () {
await page.setViewport({width: 360, height: 640, isMobile: true}); await page.setViewport({width: 360, height: 640, isMobile: true});
await page.goto(server.CROSS_PROCESS_PREFIX + '/mobile.html'); await page.goto(server.CROSS_PROCESS_PREFIX + '/mobile.html');
await page.evaluate(() => { await page.evaluate(() => {
document.addEventListener('click', (event) => { document.addEventListener('click', event => {
(globalThis as any).result = {x: event.clientX, y: event.clientY}; (globalThis as any).result = {x: event.clientX, y: event.clientY};
}); });
}); });

View File

@ -77,7 +77,7 @@ describe('navigation', function () {
let error!: Error; let error!: Error;
await page await page
.goto(server.PREFIX + '/frames/one-frame.html') .goto(server.PREFIX + '/frames/one-frame.html')
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeUndefined(); expect(error).toBeUndefined();
@ -90,7 +90,7 @@ describe('navigation', function () {
res.end(); res.end();
}); });
let error!: Error; let error!: Error;
await page.goto(server.EMPTY_PAGE).catch((error_) => { await page.goto(server.EMPTY_PAGE).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).not.toBe(null); expect(error).not.toBe(null);
@ -150,7 +150,7 @@ describe('navigation', function () {
const {page, isChrome} = getTestState(); const {page, isChrome} = getTestState();
let error!: Error; let error!: Error;
await page.goto('asdfasdf').catch((error_) => { await page.goto('asdfasdf').catch(error_ => {
return (error = error_); return (error = error_);
}); });
if (isChrome) { if (isChrome) {
@ -187,7 +187,7 @@ describe('navigation', function () {
}); });
let error!: Error; let error!: Error;
await page.goto(httpsServer.EMPTY_PAGE).catch((error_) => { await page.goto(httpsServer.EMPTY_PAGE).catch(error_ => {
return (error = error_); return (error = error_);
}); });
if (isChrome) { if (isChrome) {
@ -206,9 +206,7 @@ describe('navigation', function () {
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');
let error!: Error; let error!: Error;
await page await page.goto(httpsServer.PREFIX + '/redirect/1.html').catch(error_ => {
.goto(httpsServer.PREFIX + '/redirect/1.html')
.catch((error_) => {
return (error = error_); return (error = error_);
}); });
if (isChrome) { if (isChrome) {
@ -224,7 +222,7 @@ describe('navigation', function () {
await page await page
// @ts-expect-error purposefully passing an old option // @ts-expect-error purposefully passing an old option
.goto(server.EMPTY_PAGE, {waitUntil: 'networkidle'}) .goto(server.EMPTY_PAGE, {waitUntil: 'networkidle'})
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain( expect(error.message).toContain(
@ -237,7 +235,7 @@ describe('navigation', function () {
let error!: Error; let error!: Error;
await page await page
.goto('http://localhost:44123/non-existing-url') .goto('http://localhost:44123/non-existing-url')
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
if (isChrome) { if (isChrome) {
@ -254,7 +252,7 @@ describe('navigation', function () {
let error!: Error; let error!: Error;
await page await page
.goto(server.PREFIX + '/empty.html', {timeout: 1}) .goto(server.PREFIX + '/empty.html', {timeout: 1})
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain('Navigation timeout of 1 ms exceeded'); expect(error.message).toContain('Navigation timeout of 1 ms exceeded');
@ -267,7 +265,7 @@ describe('navigation', function () {
server.setRoute('/empty.html', () => {}); server.setRoute('/empty.html', () => {});
let error!: Error; let error!: Error;
page.setDefaultNavigationTimeout(1); page.setDefaultNavigationTimeout(1);
await page.goto(server.PREFIX + '/empty.html').catch((error_) => { await page.goto(server.PREFIX + '/empty.html').catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain('Navigation timeout of 1 ms exceeded'); expect(error.message).toContain('Navigation timeout of 1 ms exceeded');
@ -280,7 +278,7 @@ describe('navigation', function () {
server.setRoute('/empty.html', () => {}); server.setRoute('/empty.html', () => {});
let error!: Error; let error!: Error;
page.setDefaultTimeout(1); page.setDefaultTimeout(1);
await page.goto(server.PREFIX + '/empty.html').catch((error_) => { await page.goto(server.PREFIX + '/empty.html').catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain('Navigation timeout of 1 ms exceeded'); expect(error.message).toContain('Navigation timeout of 1 ms exceeded');
@ -294,7 +292,7 @@ describe('navigation', function () {
let error!: Error; let error!: Error;
page.setDefaultTimeout(0); page.setDefaultTimeout(0);
page.setDefaultNavigationTimeout(1); page.setDefaultNavigationTimeout(1);
await page.goto(server.PREFIX + '/empty.html').catch((error_) => { await page.goto(server.PREFIX + '/empty.html').catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain('Navigation timeout of 1 ms exceeded'); expect(error.message).toContain('Navigation timeout of 1 ms exceeded');
@ -310,7 +308,7 @@ describe('navigation', function () {
}); });
await page await page
.goto(server.PREFIX + '/grid.html', {timeout: 0, waitUntil: ['load']}) .goto(server.PREFIX + '/grid.html', {timeout: 0, waitUntil: ['load']})
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeUndefined(); expect(error).toBeUndefined();
@ -388,7 +386,7 @@ describe('navigation', function () {
}); });
// Wait for the page's 'load' event. // Wait for the page's 'load' event.
await new Promise((fulfill) => { await new Promise(fulfill => {
return page.once('load', fulfill); return page.once('load', fulfill);
}); });
expect(navigationFinished).toBe(false); expect(navigationFinished).toBe(false);
@ -428,7 +426,7 @@ describe('navigation', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
let warning = null; let warning = null;
const warningHandler: NodeJS.WarningListener = (w) => { const warningHandler: NodeJS.WarningListener = w => {
return (warning = w); return (warning = w);
}; };
process.on('warning', warningHandler); process.on('warning', warningHandler);
@ -442,7 +440,7 @@ describe('navigation', function () {
const {page} = getTestState(); const {page} = getTestState();
let warning = null; let warning = null;
const warningHandler: NodeJS.WarningListener = (w) => { const warningHandler: NodeJS.WarningListener = w => {
return (warning = w); return (warning = w);
}; };
process.on('warning', warningHandler); process.on('warning', warningHandler);
@ -458,7 +456,7 @@ describe('navigation', function () {
const {context, server} = getTestState(); const {context, server} = getTestState();
let warning = null; let warning = null;
const warningHandler: NodeJS.WarningListener = (w) => { const warningHandler: NodeJS.WarningListener = w => {
return (warning = w); return (warning = w);
}; };
process.on('warning', warningHandler); process.on('warning', warningHandler);
@ -478,7 +476,7 @@ describe('navigation', function () {
const {page} = getTestState(); const {page} = getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request); return !utils.isFavicon(request) && requests.push(request);
}); });
const dataURL = 'data:text/html,<div>yo</div>'; const dataURL = 'data:text/html,<div>yo</div>';
@ -494,7 +492,7 @@ describe('navigation', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request); return !utils.isFavicon(request) && requests.push(request);
}); });
const response = (await page.goto(server.EMPTY_PAGE + '#hash'))!; const response = (await page.goto(server.EMPTY_PAGE + '#hash'))!;
@ -668,8 +666,8 @@ describe('navigation', function () {
server.PREFIX + '/frames/one-frame.html' server.PREFIX + '/frames/one-frame.html'
); );
const frame = await utils.waitEvent(page, 'frameattached'); const frame = await utils.waitEvent(page, 'frameattached');
await new Promise<void>((fulfill) => { await new Promise<void>(fulfill => {
page.on('framenavigated', (f) => { page.on('framenavigated', f => {
if (f === frame) { if (f === frame) {
fulfill(); fulfill();
} }
@ -743,12 +741,12 @@ describe('navigation', function () {
const navigationPromise = page const navigationPromise = page
.frames()[1]! .frames()[1]!
.goto(server.EMPTY_PAGE) .goto(server.EMPTY_PAGE)
.catch((error_) => { .catch(error_ => {
return error_; return error_;
}); });
await server.waitForRequest('/empty.html'); await server.waitForRequest('/empty.html');
await page.$eval('iframe', (frame) => { await page.$eval('iframe', frame => {
return frame.remove(); return frame.remove();
}); });
const error = await navigationPromise; const error = await navigationPromise;
@ -812,7 +810,7 @@ describe('navigation', function () {
server.setRoute('/empty.html', () => {}); server.setRoute('/empty.html', () => {});
let error!: Error; let error!: Error;
const navigationPromise = frame.waitForNavigation().catch((error_) => { const navigationPromise = frame.waitForNavigation().catch(error_ => {
return (error = error_); return (error = error_);
}); });
await Promise.all([ await Promise.all([
@ -821,7 +819,7 @@ describe('navigation', function () {
return ((window as any).location = '/empty.html'); return ((window as any).location = '/empty.html');
}), }),
]); ]);
await page.$eval('iframe', (frame) => { await page.$eval('iframe', frame => {
return frame.remove(); return frame.remove();
}); });
await navigationPromise; await navigationPromise;

View File

@ -40,7 +40,7 @@ describe('network', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request); return !utils.isFavicon(request) && requests.push(request);
}); });
(await page.goto(server.EMPTY_PAGE))!; (await page.goto(server.EMPTY_PAGE))!;
@ -50,7 +50,7 @@ describe('network', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request); return !utils.isFavicon(request) && requests.push(request);
}); });
(await page.goto(server.EMPTY_PAGE))!; (await page.goto(server.EMPTY_PAGE))!;
@ -61,7 +61,7 @@ describe('network', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request); return !utils.isFavicon(request) && requests.push(request);
}); });
(await page.goto(server.EMPTY_PAGE))!; (await page.goto(server.EMPTY_PAGE))!;
@ -76,7 +76,7 @@ describe('network', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request); return !utils.isFavicon(request) && requests.push(request);
}); });
(await page.goto(server.EMPTY_PAGE))!; (await page.goto(server.EMPTY_PAGE))!;
@ -88,7 +88,7 @@ describe('network', function () {
(await page.goto(server.EMPTY_PAGE))!; (await page.goto(server.EMPTY_PAGE))!;
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request); return !utils.isFavicon(request) && requests.push(request);
}); });
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE); await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
@ -100,13 +100,13 @@ describe('network', function () {
(await page.goto(server.EMPTY_PAGE))!; (await page.goto(server.EMPTY_PAGE))!;
let requests: HTTPRequest[] = []; let requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
return !utils.isFavicon(request) && requests.push(request); return !utils.isFavicon(request) && requests.push(request);
}); });
await page.evaluate(() => { await page.evaluate(() => {
return fetch('/digits/1.png'); return fetch('/digits/1.png');
}); });
requests = requests.filter((request) => { requests = requests.filter(request => {
return !request.url().includes('favicon'); return !request.url().includes('favicon');
}); });
expect(requests.length).toBe(1); expect(requests.length).toBe(1);
@ -147,7 +147,7 @@ describe('network', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const initiators = new Map(); const initiators = new Map();
page.on('request', (request) => { page.on('request', request => {
return initiators.set( return initiators.set(
request.url().split('/').pop(), request.url().split('/').pop(),
request.initiator() request.initiator()
@ -199,7 +199,7 @@ describe('network', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const responses = new Map(); const responses = new Map();
page.on('response', (r) => { page.on('response', r => {
return ( return (
!utils.isFavicon(r.request()) && !utils.isFavicon(r.request()) &&
responses.set(r.url().split('/').pop(), r) responses.set(r.url().split('/').pop(), r)
@ -230,7 +230,7 @@ describe('network', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const responses = new Map(); const responses = new Map();
page.on('response', (r) => { page.on('response', r => {
return ( return (
!utils.isFavicon(r) && responses.set(r.url().split('/').pop(), r) !utils.isFavicon(r) && responses.set(r.url().split('/').pop(), r)
); );
@ -262,7 +262,7 @@ describe('network', function () {
return res.end(); return res.end();
}); });
let request!: HTTPRequest; let request!: HTTPRequest;
page.on('request', (r) => { page.on('request', r => {
if (!utils.isFavicon(r)) { if (!utils.isFavicon(r)) {
request = r; request = r;
} }
@ -311,7 +311,7 @@ describe('network', function () {
const redirected = redirectChain[0]!.response()!; const redirected = redirectChain[0]!.response()!;
expect(redirected.status()).toBe(302); expect(redirected.status()).toBe(302);
let error!: Error; let error!: Error;
await redirected.text().catch((error_) => { await redirected.text().catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain( expect(error.message).toContain(
@ -333,12 +333,12 @@ describe('network', function () {
}); });
// Setup page to trap response. // Setup page to trap response.
let requestFinished = false; let requestFinished = false;
page.on('requestfinished', (r) => { page.on('requestfinished', r => {
return (requestFinished = requestFinished || r.url().includes('/get')); return (requestFinished = requestFinished || r.url().includes('/get'));
}); });
// send request and wait for server response // send request and wait for server response
const [pageResponse] = await Promise.all([ const [pageResponse] = await Promise.all([
page.waitForResponse((r) => { page.waitForResponse(r => {
return !utils.isFavicon(r.request()); return !utils.isFavicon(r.request());
}), }),
page.evaluate(() => { page.evaluate(() => {
@ -354,11 +354,11 @@ describe('network', function () {
const responseText = pageResponse.text(); const responseText = pageResponse.text();
// Write part of the response and wait for it to be flushed. // Write part of the response and wait for it to be flushed.
await new Promise((x) => { await new Promise(x => {
return serverResponse.write('wor', x); return serverResponse.write('wor', x);
}); });
// Finish response. // Finish response.
await new Promise<void>((x) => { await new Promise<void>(x => {
serverResponse.end('ld!', () => { serverResponse.end('ld!', () => {
return x(); return x();
}); });
@ -409,8 +409,8 @@ describe('network', function () {
res.end('Hello World'); res.end('Hello World');
}); });
const url = server.CROSS_PROCESS_PREFIX + '/test.html'; const url = server.CROSS_PROCESS_PREFIX + '/test.html';
const responsePromise = new Promise<HTTPResponse>((resolve) => { const responsePromise = new Promise<HTTPResponse>(resolve => {
page.on('response', (response) => { page.on('response', response => {
// Get the preflight response. // Get the preflight response.
if ( if (
response.request().method() === 'OPTIONS' && response.request().method() === 'OPTIONS' &&
@ -422,7 +422,7 @@ describe('network', function () {
}); });
// Trigger a request with a preflight. // Trigger a request with a preflight.
await page.evaluate<(src: string) => void>(async (src) => { await page.evaluate<(src: string) => void>(async src => {
const response = await fetch(src, { const response = await fetch(src, {
method: 'POST', method: 'POST',
headers: {'x-ping': 'pong'}, headers: {'x-ping': 'pong'},
@ -465,7 +465,7 @@ describe('network', function () {
it('returns timing information', async () => { it('returns timing information', async () => {
const {page, server} = getTestState(); const {page, server} = getTestState();
const responses: HTTPResponse[] = []; const responses: HTTPResponse[] = [];
page.on('response', (response) => { page.on('response', response => {
return responses.push(response); return responses.push(response);
}); });
(await page.goto(server.EMPTY_PAGE))!; (await page.goto(server.EMPTY_PAGE))!;
@ -479,7 +479,7 @@ describe('network', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
return requests.push(request); return requests.push(request);
}); });
(await page.goto(server.EMPTY_PAGE))!; (await page.goto(server.EMPTY_PAGE))!;
@ -495,7 +495,7 @@ describe('network', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const cached: string[] = []; const cached: string[] = [];
page.on('requestservedfromcache', (r) => { page.on('requestservedfromcache', r => {
return cached.push(r.url().split('/').pop()!); return cached.push(r.url().split('/').pop()!);
}); });
@ -509,7 +509,7 @@ describe('network', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const responses: HTTPResponse[] = []; const responses: HTTPResponse[] = [];
page.on('response', (response) => { page.on('response', response => {
return responses.push(response); return responses.push(response);
}); });
(await page.goto(server.EMPTY_PAGE))!; (await page.goto(server.EMPTY_PAGE))!;
@ -530,7 +530,7 @@ describe('network', function () {
const {page, server, isChrome} = getTestState(); const {page, server, isChrome} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
if (request.url().endsWith('css')) { if (request.url().endsWith('css')) {
request.abort(); request.abort();
} else { } else {
@ -538,7 +538,7 @@ describe('network', function () {
} }
}); });
const failedRequests: HTTPRequest[] = []; const failedRequests: HTTPRequest[] = [];
page.on('requestfailed', (request) => { page.on('requestfailed', request => {
return failedRequests.push(request); return failedRequests.push(request);
}); });
await page.goto(server.PREFIX + '/one-style.html'); await page.goto(server.PREFIX + '/one-style.html');
@ -559,7 +559,7 @@ describe('network', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('requestfinished', (request) => { page.on('requestfinished', request => {
return requests.push(request); return requests.push(request);
}); });
(await page.goto(server.EMPTY_PAGE))!; (await page.goto(server.EMPTY_PAGE))!;
@ -589,16 +589,16 @@ describe('network', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const events: string[] = []; const events: string[] = [];
page.on('request', (request) => { page.on('request', request => {
return events.push(`${request.method()} ${request.url()}`); return events.push(`${request.method()} ${request.url()}`);
}); });
page.on('response', (response) => { page.on('response', response => {
return events.push(`${response.status()} ${response.url()}`); return events.push(`${response.status()} ${response.url()}`);
}); });
page.on('requestfinished', (request) => { page.on('requestfinished', request => {
return events.push(`DONE ${request.url()}`); return events.push(`DONE ${request.url()}`);
}); });
page.on('requestfailed', (request) => { page.on('requestfailed', request => {
return events.push(`FAIL ${request.url()}`); return events.push(`FAIL ${request.url()}`);
}); });
server.setRedirect('/foo.html', '/empty.html'); server.setRedirect('/foo.html', '/empty.html');
@ -628,7 +628,7 @@ describe('network', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const requests = new Map(); const requests = new Map();
page.on('request', (request) => { page.on('request', request => {
return requests.set(request.url().split('/').pop(), request); return requests.set(request.url().split('/').pop(), request);
}); });
server.setRedirect('/rrredirect', '/frames/one-frame.html'); server.setRedirect('/rrredirect', '/frames/one-frame.html');
@ -643,7 +643,7 @@ describe('network', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const requests = new Map(); const requests = new Map();
page.on('request', (request) => { page.on('request', request => {
requests.set(request.url().split('/').pop(), request); requests.set(request.url().split('/').pop(), request);
request.continue(); request.continue();
}); });
@ -660,7 +660,7 @@ describe('network', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
return requests.push(request); return requests.push(request);
}); });
(await page.goto(server.PREFIX + '/pptr.png'))!; (await page.goto(server.PREFIX + '/pptr.png'))!;
@ -779,7 +779,7 @@ describe('network', function () {
}); });
const responses = new Map(); const responses = new Map();
page.on('response', (r) => { page.on('response', r => {
return responses.set(r.url().split('/').pop(), r); return responses.set(r.url().split('/').pop(), r);
}); });
@ -817,8 +817,8 @@ describe('network', function () {
res.end('hello world'); res.end('hello world');
}); });
const responsePromise = new Promise<HTTPResponse>((resolve) => { const responsePromise = new Promise<HTTPResponse>(resolve => {
return page.on('response', (response) => { return page.on('response', response => {
return resolve(response); return resolve(response);
}); });
}); });
@ -852,10 +852,10 @@ describe('network', function () {
}); });
await page.goto(httpsServer.PREFIX + '/setcookie.html'); await page.goto(httpsServer.PREFIX + '/setcookie.html');
const response = await new Promise<HTTPResponse>((resolve) => { const response = await new Promise<HTTPResponse>(resolve => {
page.on('response', resolve); page.on('response', resolve);
const url = httpsServer.CROSS_PROCESS_PREFIX + '/setcookie.html'; const url = httpsServer.CROSS_PROCESS_PREFIX + '/setcookie.html';
page.evaluate<(src: string) => void>((src) => { page.evaluate<(src: string) => void>(src => {
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.open('GET', src); xhr.open('GET', src);
xhr.send(); xhr.send();

View File

@ -63,7 +63,7 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState(); const {server} = getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const framePromise = page.waitForFrame((frame) => { const framePromise = page.waitForFrame(frame => {
return frame.url().endsWith('/empty.html'); return frame.url().endsWith('/empty.html');
}); });
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE); await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
@ -79,7 +79,7 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState(); const {server} = 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;
}); });
await utils.attachFrame( await utils.attachFrame(
@ -100,7 +100,7 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState(); const {server} = 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;
}); });
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE); await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
@ -121,10 +121,10 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState(); const {server} = getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const frame1Promise = page.waitForFrame((frame) => { const frame1Promise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1; return page.frames().indexOf(frame) === 1;
}); });
const frame2Promise = page.waitForFrame((frame) => { const frame2Promise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 2; return page.frames().indexOf(frame) === 2;
}); });
await utils.attachFrame( await utils.attachFrame(
@ -150,7 +150,7 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState(); const {server} = 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;
}); });
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE); await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
@ -171,7 +171,7 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState(); const {server} = 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;
}); });
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE); await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
@ -194,7 +194,7 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState(); const {server} = 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;
}); });
await utils.attachFrame( await utils.attachFrame(
@ -211,7 +211,7 @@ describeChromeOnly('OOPIF', function () {
const {server} = getTestState(); const {server} = 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;
}); });
await utils.attachFrame( await utils.attachFrame(
@ -250,7 +250,7 @@ describeChromeOnly('OOPIF', function () {
} }
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;
}); });
await utils.attachFrame( await utils.attachFrame(
@ -281,7 +281,7 @@ describeChromeOnly('OOPIF', function () {
it('should report oopif frames', async () => { it('should report oopif frames', async () => {
const {server} = getTestState(); const {server} = getTestState();
const frame = page.waitForFrame((frame) => { const frame = page.waitForFrame(frame => {
return frame.url().endsWith('/oopif.html'); return frame.url().endsWith('/oopif.html');
}); });
await page.goto(server.PREFIX + '/dynamic-oopif.html'); await page.goto(server.PREFIX + '/dynamic-oopif.html');
@ -293,12 +293,12 @@ describeChromeOnly('OOPIF', function () {
it('should wait for inner OOPIFs', async () => { it('should wait for inner OOPIFs', async () => {
const {server} = getTestState(); const {server} = 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');
}); });
expect(oopifs(context).length).toBe(2); expect(oopifs(context).length).toBe(2);
expect( expect(
page.frames().filter((frame) => { page.frames().filter(frame => {
return frame.isOOPFrame(); return frame.isOOPFrame();
}).length }).length
).toBe(2); ).toBe(2);
@ -312,11 +312,11 @@ describeChromeOnly('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} = getTestState();
const frame = page.waitForFrame((frame) => { const frame = page.waitForFrame(frame => {
return frame.url().endsWith('/oopif.html'); return frame.url().endsWith('/oopif.html');
}); });
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue(); return request.continue();
}); });
await page.goto(server.PREFIX + '/dynamic-oopif.html'); await page.goto(server.PREFIX + '/dynamic-oopif.html');
@ -326,7 +326,7 @@ describeChromeOnly('OOPIF', function () {
it('should support frames within OOP iframes', async () => { it('should support frames within OOP iframes', async () => {
const {server} = getTestState(); const {server} = getTestState();
const oopIframePromise = page.waitForFrame((frame) => { const oopIframePromise = page.waitForFrame(frame => {
return frame.url().endsWith('/oopif.html'); return frame.url().endsWith('/oopif.html');
}); });
await page.goto(server.PREFIX + '/dynamic-oopif.html'); await page.goto(server.PREFIX + '/dynamic-oopif.html');
@ -357,7 +357,7 @@ describeChromeOnly('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} = 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;
}); });
await utils.attachFrame( await utils.attachFrame(
@ -403,7 +403,7 @@ describeChromeOnly('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} = getTestState();
const frame = page.waitForFrame((frame) => { const frame = page.waitForFrame(frame => {
return frame.url().endsWith('/oopif.html'); return frame.url().endsWith('/oopif.html');
}); });
await page.goto(server.PREFIX + '/dynamic-oopif.html'); await page.goto(server.PREFIX + '/dynamic-oopif.html');
@ -413,7 +413,7 @@ describeChromeOnly('OOPIF', function () {
const browserURL = 'http://127.0.0.1:21222'; const browserURL = 'http://127.0.0.1:21222';
const browser1 = await puppeteer.connect({browserURL}); const browser1 = await puppeteer.connect({browserURL});
const target = await browser1.waitForTarget((target) => { const target = await browser1.waitForTarget(target => {
return target.url().endsWith('dynamic-oopif.html'); return target.url().endsWith('dynamic-oopif.html');
}); });
await target.page(); await target.page();
@ -426,7 +426,7 @@ describeChromeOnly('OOPIF', function () {
await page.setViewport({width: 1000, height: 1000}); await page.setViewport({width: 1000, height: 1000});
expect( expect(
page.frames().map((frame) => { page.frames().map(frame => {
return frame._hasStartedLoading; return frame._hasStartedLoading;
}) })
).toEqual([true, true, false]); ).toEqual([true, true, false]);
@ -443,7 +443,7 @@ describeChromeOnly('OOPIF', function () {
server.CROSS_PROCESS_PREFIX + '/empty.html' server.CROSS_PROCESS_PREFIX + '/empty.html'
); );
await page.waitForFrame((frame) => { await page.waitForFrame(frame => {
return frame.url().endsWith('/empty.html'); return frame.url().endsWith('/empty.html');
}); });
}); });
@ -451,7 +451,7 @@ describeChromeOnly('OOPIF', function () {
}); });
function oopifs(context: BrowserContext) { function oopifs(context: BrowserContext) {
return context.targets().filter((target) => { return context.targets().filter(target => {
return target._getTargetInfo().type === 'iframe'; return target._getTargetInfo().type === 'iframe';
}); });
} }

View File

@ -45,7 +45,7 @@ describe('Page', function () {
.evaluate(() => { .evaluate(() => {
return new Promise(() => {}); return new Promise(() => {});
}) })
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}), }),
newPage.close(), newPage.close(),
@ -103,10 +103,10 @@ describe('Page', function () {
const newPage = await context.newPage(); const newPage = await context.newPage();
const results = await Promise.all([ const results = await Promise.all([
newPage.waitForRequest(server.EMPTY_PAGE).catch((error) => { newPage.waitForRequest(server.EMPTY_PAGE).catch(error => {
return error; return error;
}), }),
newPage.waitForResponse(server.EMPTY_PAGE).catch((error) => { newPage.waitForResponse(server.EMPTY_PAGE).catch(error => {
return error; return error;
}), }),
newPage.close(), newPage.close(),
@ -188,7 +188,7 @@ describe('Page', function () {
const {page} = getTestState(); const {page} = getTestState();
let error!: Error; let error!: Error;
page.on('error', (err) => { page.on('error', err => {
return (error = err); return (error = err);
}); });
page.goto('chrome://crash').catch(() => {}); page.goto('chrome://crash').catch(() => {});
@ -202,7 +202,7 @@ describe('Page', function () {
const {page} = getTestState(); const {page} = getTestState();
const [popup] = await Promise.all([ const [popup] = await Promise.all([
new Promise<Page>((x) => { new Promise<Page>(x => {
return page.once('popup', x); return page.once('popup', x);
}), }),
page.evaluate(() => { page.evaluate(() => {
@ -224,7 +224,7 @@ describe('Page', function () {
const {page} = getTestState(); const {page} = getTestState();
const [popup] = await Promise.all([ const [popup] = await Promise.all([
new Promise<Page>((x) => { new Promise<Page>(x => {
return page.once('popup', x); return page.once('popup', x);
}), }),
page.evaluate(() => { page.evaluate(() => {
@ -248,7 +248,7 @@ describe('Page', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setContent('<a target=_blank href="/one-style.html">yo</a>'); await page.setContent('<a target=_blank href="/one-style.html">yo</a>');
const [popup] = await Promise.all([ const [popup] = await Promise.all([
new Promise<Page>((x) => { new Promise<Page>(x => {
return page.once('popup', x); return page.once('popup', x);
}), }),
page.click('a'), page.click('a'),
@ -272,7 +272,7 @@ describe('Page', function () {
'<a target=_blank rel=opener href="/one-style.html">yo</a>' '<a target=_blank rel=opener href="/one-style.html">yo</a>'
); );
const [popup] = await Promise.all([ const [popup] = await Promise.all([
new Promise<Page>((x) => { new Promise<Page>(x => {
return page.once('popup', x); return page.once('popup', x);
}), }),
page.click('a'), page.click('a'),
@ -296,10 +296,10 @@ describe('Page', function () {
'<a target=_blank rel=noopener href="/one-style.html">yo</a>' '<a target=_blank rel=noopener href="/one-style.html">yo</a>'
); );
const [popup] = await Promise.all([ const [popup] = await Promise.all([
new Promise<Page>((x) => { new Promise<Page>(x => {
return page.once('popup', x); return page.once('popup', x);
}), }),
page.$eval('a', (a) => { page.$eval('a', a => {
return (a as HTMLAnchorElement).click(); return (a as HTMLAnchorElement).click();
}), }),
]); ]);
@ -322,7 +322,7 @@ describe('Page', function () {
'<a target=_blank rel=noopener href="/one-style.html">yo</a>' '<a target=_blank rel=noopener href="/one-style.html">yo</a>'
); );
const [popup] = await Promise.all([ const [popup] = await Promise.all([
new Promise<Page>((x) => { new Promise<Page>(x => {
return page.once('popup', x); return page.once('popup', x);
}), }),
page.click('a'), page.click('a'),
@ -343,7 +343,7 @@ describe('Page', function () {
describe('BrowserContext.overridePermissions', function () { describe('BrowserContext.overridePermissions', function () {
function getPermission(page: Page, name: string) { function getPermission(page: Page, name: string) {
return page.evaluate((name: PermissionName) => { return page.evaluate((name: PermissionName) => {
return navigator.permissions.query({ name }).then((result) => { return navigator.permissions.query({name}).then(result => {
return result.state; return result.state;
}); });
}, name); }, name);
@ -370,7 +370,7 @@ describe('Page', function () {
await context await context
// @ts-expect-error purposeful bad input for test // @ts-expect-error purposeful bad input for test
.overridePermissions(server.EMPTY_PAGE, ['foo']) .overridePermissions(server.EMPTY_PAGE, ['foo'])
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toBe('Unknown permission: foo'); expect(error.message).toBe('Unknown permission: foo');
@ -483,8 +483,8 @@ describe('Page', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setGeolocation({longitude: 10, latitude: 10}); await page.setGeolocation({longitude: 10, latitude: 10});
const geolocation = await page.evaluate(() => { const geolocation = await page.evaluate(() => {
return new Promise((resolve) => { return new Promise(resolve => {
return navigator.geolocation.getCurrentPosition((position) => { return navigator.geolocation.getCurrentPosition(position => {
resolve({ resolve({
latitude: position.coords.latitude, latitude: position.coords.latitude,
longitude: position.coords.longitude, longitude: position.coords.longitude,
@ -516,7 +516,7 @@ describe('Page', function () {
await page.setOfflineMode(true); await page.setOfflineMode(true);
let error!: Error; let error!: Error;
await page.goto(server.EMPTY_PAGE).catch((error_) => { await page.goto(server.EMPTY_PAGE).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeTruthy(); expect(error).toBeTruthy();
@ -563,7 +563,7 @@ describe('Page', function () {
return objects.length; return objects.length;
}, objectsHandle); }, objectsHandle);
expect(count).toBe(1); expect(count).toBe(1);
const values = await page.evaluate((objects) => { const values = await page.evaluate(objects => {
return Array.from(objects[0]!.values()); return Array.from(objects[0]!.values());
}, objectsHandle); }, objectsHandle);
expect(values).toEqual(['hello', 'world']); expect(values).toEqual(['hello', 'world']);
@ -593,7 +593,7 @@ describe('Page', function () {
}); });
await prototypeHandle.dispose(); await prototypeHandle.dispose();
let error!: Error; let error!: Error;
await page.queryObjects(prototypeHandle).catch((error_) => { await page.queryObjects(prototypeHandle).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toBe('Prototype JSHandle is disposed!'); expect(error.message).toBe('Prototype JSHandle is disposed!');
@ -605,7 +605,7 @@ describe('Page', function () {
return 42; return 42;
}); });
let error!: Error; let error!: Error;
await page.queryObjects(prototypeHandle).catch((error_) => { await page.queryObjects(prototypeHandle).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toBe( expect(error.message).toBe(
@ -619,7 +619,7 @@ describe('Page', function () {
const {page} = getTestState(); const {page} = getTestState();
let message!: ConsoleMessage; let message!: ConsoleMessage;
page.once('console', (m) => { page.once('console', m => {
return (message = m); return (message = m);
}); });
await Promise.all([ await Promise.all([
@ -645,7 +645,7 @@ describe('Page', function () {
const {page} = getTestState(); const {page} = getTestState();
const messages: any[] = []; const messages: any[] = [];
page.on('console', (msg) => { page.on('console', msg => {
return messages.push(msg); return messages.push(msg);
}); });
// All console events will be reported before `page.evaluate` is finished. // All console events will be reported before `page.evaluate` is finished.
@ -660,13 +660,13 @@ describe('Page', function () {
console.log(Promise.resolve('should not wait until resolved!')); console.log(Promise.resolve('should not wait until resolved!'));
}); });
expect( expect(
messages.map((msg) => { messages.map(msg => {
return msg.type(); return msg.type();
}) })
).toEqual(['timeEnd', 'trace', 'dir', 'warning', 'error', 'log']); ).toEqual(['timeEnd', 'trace', 'dir', 'warning', 'error', 'log']);
expect(messages[0]!.text()).toContain('calling console.time'); expect(messages[0]!.text()).toContain('calling console.time');
expect( expect(
messages.slice(1).map((msg) => { messages.slice(1).map(msg => {
return msg.text(); return msg.text();
}) })
).toEqual([ ).toEqual([
@ -681,7 +681,7 @@ describe('Page', function () {
const {page} = getTestState(); const {page} = getTestState();
let message!: ConsoleMessage; let message!: ConsoleMessage;
page.once('console', (msg) => { page.once('console', msg => {
return (message = msg); return (message = msg);
}); });
await Promise.all([ await Promise.all([
@ -771,13 +771,13 @@ describe('Page', function () {
'Title', 'Title',
'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=0,left=0' 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=0,left=0'
)!; )!;
await new Promise((x) => { await new Promise(x => {
return (win.onload = x); return (win.onload = x);
}); });
// 2. In this popup, create an iframe that console.logs a message. // 2. In this popup, create an iframe that console.logs a message.
win.document.body.innerHTML = `<iframe src='/consolelog.html'></iframe>`; win.document.body.innerHTML = `<iframe src='/consolelog.html'></iframe>`;
const frame = win.document.querySelector('iframe')!; const frame = win.document.querySelector('iframe')!;
await new Promise((x) => { await new Promise(x => {
return (frame.onload = x); return (frame.onload = x);
}); });
// 3. After that, remove the iframe. // 3. After that, remove the iframe.
@ -786,7 +786,7 @@ describe('Page', function () {
const popupTarget = page const popupTarget = page
.browserContext() .browserContext()
.targets() .targets()
.find((target) => { .find(target => {
return target !== page.target(); return target !== page.target();
})!; })!;
// 4. Connect to the popup and make sure it doesn't throw. // 4. Connect to the popup and make sure it doesn't throw.
@ -815,7 +815,7 @@ describe('Page', function () {
const {page} = getTestState(); const {page} = getTestState();
const metricsPromise = new Promise<{metrics: Metrics; title: string}>( const metricsPromise = new Promise<{metrics: Metrics; title: string}>(
(fulfill) => { fulfill => {
return page.once('metrics', fulfill); return page.once('metrics', fulfill);
} }
); );
@ -871,7 +871,7 @@ describe('Page', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const [request] = await Promise.all([ const [request] = await Promise.all([
page.waitForRequest((request) => { page.waitForRequest(request => {
return request.url() === server.PREFIX + '/digits/2.png'; return request.url() === server.PREFIX + '/digits/2.png';
}), }),
page.evaluate(() => { page.evaluate(() => {
@ -893,7 +893,7 @@ describe('Page', function () {
}, },
{timeout: 1} {timeout: 1}
) )
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -907,7 +907,7 @@ describe('Page', function () {
.waitForRequest(() => { .waitForRequest(() => {
return false; return false;
}) })
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -956,7 +956,7 @@ describe('Page', function () {
}, },
{timeout: 1} {timeout: 1}
) )
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -970,7 +970,7 @@ describe('Page', function () {
.waitForResponse(() => { .waitForResponse(() => {
return false; return false;
}) })
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -980,7 +980,7 @@ describe('Page', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const [response] = await Promise.all([ const [response] = await Promise.all([
page.waitForResponse((response) => { page.waitForResponse(response => {
return response.url() === server.PREFIX + '/digits/2.png'; return response.url() === server.PREFIX + '/digits/2.png';
}), }),
page.evaluate(() => { page.evaluate(() => {
@ -995,7 +995,7 @@ describe('Page', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const [response] = await Promise.all([ const [response] = await Promise.all([
page.waitForResponse(async (response) => { page.waitForResponse(async response => {
return response.url() === server.PREFIX + '/digits/2.png'; return response.url() === server.PREFIX + '/digits/2.png';
}), }),
page.evaluate(() => { page.evaluate(() => {
@ -1030,7 +1030,7 @@ describe('Page', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
let res; let res;
const [t1, t2] = await Promise.all([ const [t1, t2] = await Promise.all([
page.waitForNetworkIdle().then((r) => { page.waitForNetworkIdle().then(r => {
res = r; res = r;
return Date.now(); return Date.now();
}), }),
@ -1041,11 +1041,11 @@ describe('Page', function () {
fetch('/digits/1.png'), fetch('/digits/1.png'),
fetch('/digits/2.png'), fetch('/digits/2.png'),
]); ]);
await new Promise((resolve) => { await new Promise(resolve => {
return setTimeout(resolve, 200); return setTimeout(resolve, 200);
}); });
await fetch('/digits/3.png'); await fetch('/digits/3.png');
await new Promise((resolve) => { await new Promise(resolve => {
return setTimeout(resolve, 200); return setTimeout(resolve, 200);
}); });
await fetch('/digits/4.png'); await fetch('/digits/4.png');
@ -1062,7 +1062,7 @@ describe('Page', function () {
it('should respect timeout', async () => { it('should respect timeout', async () => {
const {page, puppeteer} = getTestState(); const {page, puppeteer} = getTestState();
let error!: Error; let error!: Error;
await page.waitForNetworkIdle({ timeout: 1 }).catch((error_) => { await page.waitForNetworkIdle({timeout: 1}).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -1081,7 +1081,7 @@ describe('Page', function () {
fetch('/digits/1.png'), fetch('/digits/1.png'),
fetch('/digits/2.png'), fetch('/digits/2.png'),
]); ]);
await new Promise((resolve) => { await new Promise(resolve => {
return setTimeout(resolve, 250); return setTimeout(resolve, 250);
}); });
})(); })();
@ -1274,7 +1274,7 @@ describe('Page', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
let error!: Error; let error!: Error;
page.once('pageerror', (e) => { page.once('pageerror', e => {
return (error = e); return (error = e);
}); });
await Promise.all([ await Promise.all([
@ -1411,7 +1411,7 @@ describe('Page', function () {
.setContent(`<img src="${server.PREFIX + imgPath}"></img>`, { .setContent(`<img src="${server.PREFIX + imgPath}"></img>`, {
timeout: 1, timeout: 1,
}) })
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -1426,7 +1426,7 @@ describe('Page', function () {
let error!: Error; let error!: Error;
await page await page
.setContent(`<img src="${server.PREFIX + imgPath}"></img>`) .setContent(`<img src="${server.PREFIX + imgPath}"></img>`)
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -1462,7 +1462,7 @@ describe('Page', function () {
await page.setContent('<div>hello world</div>' + '\x7F'); await page.setContent('<div>hello world</div>' + '\x7F');
expect( expect(
await page.$eval('div', (div) => { await page.$eval('div', div => {
return div.textContent; return div.textContent;
}) })
).toBe('hello world'); ).toBe('hello world');
@ -1472,7 +1472,7 @@ describe('Page', function () {
await page.setContent('<div>aberración</div>'); await page.setContent('<div>aberración</div>');
expect( expect(
await page.$eval('div', (div) => { await page.$eval('div', div => {
return div.textContent; return div.textContent;
}) })
).toBe('aberración'); ).toBe('aberración');
@ -1482,7 +1482,7 @@ describe('Page', function () {
await page.setContent('<div>🐥</div>'); await page.setContent('<div>🐥</div>');
expect( expect(
await page.$eval('div', (div) => { await page.$eval('div', div => {
return div.textContent; return div.textContent;
}) })
).toBe('🐥'); ).toBe('🐥');
@ -1492,7 +1492,7 @@ describe('Page', function () {
await page.setContent('<div>\n</div>'); await page.setContent('<div>\n</div>');
expect( expect(
await page.$eval('div', (div) => { await page.$eval('div', div => {
return div.textContent; return div.textContent;
}) })
).toBe('\n'); ).toBe('\n');
@ -1507,7 +1507,7 @@ describe('Page', function () {
await page.goto(server.PREFIX + '/csp.html'); await page.goto(server.PREFIX + '/csp.html');
await page await page
.addScriptTag({content: 'window.__injected = 42;'}) .addScriptTag({content: 'window.__injected = 42;'})
.catch((error) => { .catch(error => {
return void error; return void error;
}); });
expect( expect(
@ -1535,7 +1535,7 @@ describe('Page', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page await page
.addScriptTag({content: 'window.__injected = 42;'}) .addScriptTag({content: 'window.__injected = 42;'})
.catch((error) => { .catch(error => {
return void error; return void error;
}); });
expect( expect(
@ -1588,7 +1588,7 @@ describe('Page', function () {
))!; ))!;
await frame await frame
.addScriptTag({content: 'window.__injected = 42;'}) .addScriptTag({content: 'window.__injected = 42;'})
.catch((error) => { .catch(error => {
return void error; return void error;
}); });
expect( expect(
@ -1610,7 +1610,7 @@ describe('Page', function () {
))!; ))!;
await frame await frame
.addScriptTag({content: 'window.__injected = 42;'}) .addScriptTag({content: 'window.__injected = 42;'})
.catch((error) => { .catch(error => {
return void error; return void error;
}); });
expect( expect(
@ -1768,7 +1768,7 @@ describe('Page', function () {
let error!: Error; let error!: Error;
await page await page
.addScriptTag({content: 'window.__injected = 35;'}) .addScriptTag({content: 'window.__injected = 35;'})
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeTruthy(); expect(error).toBeTruthy();
@ -1781,7 +1781,7 @@ describe('Page', function () {
let error!: Error; let error!: Error;
await page await page
.addScriptTag({url: server.CROSS_PROCESS_PREFIX + '/injectedfile.js'}) .addScriptTag({url: server.CROSS_PROCESS_PREFIX + '/injectedfile.js'})
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeTruthy(); expect(error).toBeTruthy();
@ -1883,7 +1883,7 @@ describe('Page', function () {
let error!: Error; let error!: Error;
await page await page
.addStyleTag({content: 'body { background-color: green; }'}) .addStyleTag({content: 'body { background-color: green; }'})
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeTruthy(); expect(error).toBeTruthy();
@ -1899,7 +1899,7 @@ describe('Page', function () {
.addStyleTag({ .addStyleTag({
url: server.CROSS_PROCESS_PREFIX + '/injectedstyle.css', url: server.CROSS_PROCESS_PREFIX + '/injectedstyle.css',
}) })
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeTruthy(); expect(error).toBeTruthy();
@ -1925,7 +1925,7 @@ describe('Page', function () {
'data:text/html, <script>var something = "forbidden"</script>' 'data:text/html, <script>var something = "forbidden"</script>'
); );
let error!: Error; let error!: Error;
await page.evaluate('something').catch((error_) => { await page.evaluate('something').catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain('something is not defined'); expect(error.message).toContain('something is not defined');
@ -2016,7 +2016,7 @@ describe('Page', function () {
await page.goto(server.PREFIX + '/pdf.html'); await page.goto(server.PREFIX + '/pdf.html');
let error!: Error; let error!: Error;
await page.pdf({ timeout: 1 }).catch((_error) => { await page.pdf({timeout: 1}).catch(_error => {
return (error = _error); return (error = _error);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -2069,7 +2069,7 @@ describe('Page', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.goto(server.PREFIX + '/input/select.html'); await page.goto(server.PREFIX + '/input/select.html');
await page.$eval('select', (select) => { await page.$eval('select', select => {
return select.addEventListener('input', () => { return select.addEventListener('input', () => {
return ((window as any).location = '/empty.html'); return ((window as any).location = '/empty.html');
}); });
@ -2120,7 +2120,7 @@ describe('Page', function () {
let error!: Error; let error!: Error;
await page.goto(server.PREFIX + '/input/select.html'); await page.goto(server.PREFIX + '/input/select.html');
await page.select('body', '').catch((error_) => { await page.select('body', '').catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain('Element is not a <select> element.'); expect(error.message).toContain('Element is not a <select> element.');
@ -2176,9 +2176,9 @@ describe('Page', function () {
await page.select('select', 'blue', 'black', 'magenta'); await page.select('select', 'blue', 'black', 'magenta');
await page.select('select'); await page.select('select');
expect( expect(
await page.$eval('select', (select) => { await page.$eval('select', select => {
return Array.from((select as HTMLSelectElement).options).every( return Array.from((select as HTMLSelectElement).options).every(
(option) => { option => {
return !option.selected; return !option.selected;
} }
); );
@ -2192,9 +2192,9 @@ describe('Page', function () {
await page.select('select', 'blue', 'black', 'magenta'); await page.select('select', 'blue', 'black', 'magenta');
await page.select('select'); await page.select('select');
expect( expect(
await page.$eval('select', (select) => { await page.$eval('select', select => {
return Array.from((select as HTMLSelectElement).options).filter( return Array.from((select as HTMLSelectElement).options).filter(
(option) => { option => {
return option.selected; return option.selected;
} }
)[0]!.value; )[0]!.value;
@ -2244,8 +2244,8 @@ describe('Page', function () {
itFailsFirefox('should work with window.close', async () => { itFailsFirefox('should work with window.close', async () => {
const {page, context} = getTestState(); const {page, context} = getTestState();
const newPagePromise = new Promise<Page>((fulfill) => { const newPagePromise = new Promise<Page>(fulfill => {
return context.once('targetcreated', (target) => { return context.once('targetcreated', target => {
return fulfill(target.page()); return fulfill(target.page());
}); });
}); });
@ -2253,7 +2253,7 @@ describe('Page', function () {
return ((window as any)['newPage'] = window.open('about:blank')); return ((window as any)['newPage'] = window.open('about:blank'));
}); });
const newPage = await newPagePromise; const newPage = await newPagePromise;
const closedPromise = new Promise((x) => { const closedPromise = new Promise(x => {
return newPage.on('close', x); return newPage.on('close', x);
}); });
await page.evaluate(() => { await page.evaluate(() => {
@ -2265,7 +2265,7 @@ describe('Page', function () {
const {context} = getTestState(); const {context} = getTestState();
const newPage = await context.newPage(); const newPage = await context.newPage();
const closedPromise = new Promise((x) => { const closedPromise = new Promise(x => {
return newPage.on('close', x); return newPage.on('close', x);
}); });
await newPage.close(); await newPage.close();

View File

@ -65,7 +65,7 @@ describeFailsFirefox('request proxy', () => {
method: originalRequest.method, method: originalRequest.method,
headers: originalRequest.headers, headers: originalRequest.headers,
}, },
(proxyResponse) => { proxyResponse => {
originalResponse.writeHead( originalResponse.writeHead(
proxyResponse.statusCode as number, proxyResponse.statusCode as number,
proxyResponse.headers proxyResponse.headers
@ -88,7 +88,7 @@ describeFailsFirefox('request proxy', () => {
await browser.close(); await browser.close();
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
proxyServer.close((error) => { proxyServer.close(error => {
if (error) { if (error) {
reject(error); reject(error);
} else { } else {

View File

@ -29,7 +29,7 @@ describe('querySelector', function () {
const {page} = getTestState(); const {page} = 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 => {
return e.id; return e.id;
}); });
expect(idAttribute).toBe('testAttribute'); expect(idAttribute).toBe('testAttribute');
@ -66,10 +66,10 @@ describe('querySelector', function () {
let error!: Error; let error!: Error;
await page await page
.$eval('section', (e) => { .$eval('section', e => {
return e.id; return e.id;
}) })
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error.message).toContain( expect(error.message).toContain(
@ -109,7 +109,7 @@ describe('querySelector', function () {
const {page} = getTestState(); const {page} = getTestState();
const divs = await page.$$('pierce/.foo'); const divs = await page.$$('pierce/.foo');
const text = await Promise.all( const text = await Promise.all(
divs.map((div) => { divs.map(div => {
return div.evaluate((element: Element) => { return div.evaluate((element: Element) => {
return element.textContent; return element.textContent;
}); });
@ -131,7 +131,7 @@ describe('querySelector', function () {
const parentElement = (await page.$('html > div'))!; const parentElement = (await page.$('html > div'))!;
const childElements = await parentElement.$$('pierce/div'); const childElements = await parentElement.$$('pierce/div');
const text = await Promise.all( const text = await Promise.all(
childElements.map((div) => { childElements.map(div => {
return div.evaluate((element: Element) => { return div.evaluate((element: Element) => {
return element.textContent; return element.textContent;
}); });
@ -151,7 +151,7 @@ describe('querySelector', function () {
await page.setContent( await page.setContent(
'<div>hello</div><div>beautiful</div><div>world!</div>' '<div>hello</div><div>beautiful</div><div>world!</div>'
); );
const divsCount = await page.$$eval('div', (divs) => { const divsCount = await page.$$eval('div', divs => {
return divs.length; return divs.length;
}); });
expect(divsCount).toBe(3); expect(divsCount).toBe(3);
@ -201,7 +201,7 @@ describe('querySelector', function () {
} }
` `
); );
const sum = await page.$$eval('section', (sections) => { const sum = await page.$$eval('section', sections => {
return sections.reduce((acc, section) => { return sections.reduce((acc, section) => {
return acc + Number(section.textContent); return acc + Number(section.textContent);
}, 0); }, 0);
@ -233,7 +233,7 @@ describe('querySelector', function () {
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');
expect(elements.length).toBe(2); expect(elements.length).toBe(2);
const promises = elements.map((element) => { const promises = elements.map(element => {
return page.evaluate((e: HTMLElement) => { return page.evaluate((e: HTMLElement) => {
return e.textContent; return e.textContent;
}, element); }, element);
@ -309,7 +309,7 @@ describe('querySelector', function () {
'<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>'
); );
const tweet = (await page.$('.tweet'))!; const tweet = (await page.$('.tweet'))!;
const content = await tweet.$eval('.like', (node) => { const content = await tweet.$eval('.like', node => {
return (node as HTMLElement).innerText; return (node as HTMLElement).innerText;
}); });
expect(content).toBe('100'); expect(content).toBe('100');
@ -322,7 +322,7 @@ describe('querySelector', function () {
'<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>';
await page.setContent(htmlContent); await page.setContent(htmlContent);
const elementHandle = (await page.$('#myId'))!; const elementHandle = (await page.$('#myId'))!;
const content = await elementHandle.$eval('.a', (node) => { const content = await elementHandle.$eval('.a', node => {
return (node as HTMLElement).innerText; return (node as HTMLElement).innerText;
}); });
expect(content).toBe('a-child-div'); expect(content).toBe('a-child-div');
@ -336,10 +336,10 @@ describe('querySelector', function () {
await page.setContent(htmlContent); await page.setContent(htmlContent);
const elementHandle = (await page.$('#myId'))!; const elementHandle = (await page.$('#myId'))!;
const errorMessage = await elementHandle const errorMessage = await elementHandle
.$eval('.a', (node) => { .$eval('.a', node => {
return (node as HTMLElement).innerText; return (node as HTMLElement).innerText;
}) })
.catch((error) => { .catch(error => {
return error.message; return error.message;
}); });
expect(errorMessage).toBe( expect(errorMessage).toBe(
@ -355,8 +355,8 @@ describe('querySelector', function () {
'<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>'
); );
const tweet = (await page.$('.tweet'))!; const tweet = (await page.$('.tweet'))!;
const content = await tweet.$$eval('.like', (nodes) => { const content = await tweet.$$eval('.like', nodes => {
return (nodes as HTMLElement[]).map((n) => { return (nodes as HTMLElement[]).map(n => {
return n.innerText; return n.innerText;
}); });
}); });
@ -370,8 +370,8 @@ describe('querySelector', function () {
'<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>';
await page.setContent(htmlContent); await page.setContent(htmlContent);
const elementHandle = (await page.$('#myId'))!; const elementHandle = (await page.$('#myId'))!;
const content = await elementHandle.$$eval('.a', (nodes) => { const content = await elementHandle.$$eval('.a', nodes => {
return (nodes as HTMLElement[]).map((n) => { return (nodes as HTMLElement[]).map(n => {
return n.innerText; return n.innerText;
}); });
}); });
@ -385,7 +385,7 @@ describe('querySelector', function () {
'<div class="a">not-a-child-div</div><div id="myId"></div>'; '<div class="a">not-a-child-div</div><div id="myId"></div>';
await page.setContent(htmlContent); await page.setContent(htmlContent);
const elementHandle = (await page.$('#myId'))!; const elementHandle = (await page.$('#myId'))!;
const nodesLength = await elementHandle.$$eval('.a', (nodes) => { const nodesLength = await elementHandle.$$eval('.a', nodes => {
return nodes.length; return nodes.length;
}); });
expect(nodesLength).toBe(0); expect(nodesLength).toBe(0);
@ -402,7 +402,7 @@ describe('querySelector', function () {
const html = (await page.$('html'))!; const html = (await page.$('html'))!;
const elements = await html.$$('div'); const elements = await html.$$('div');
expect(elements.length).toBe(2); expect(elements.length).toBe(2);
const promises = elements.map((element) => { const promises = elements.map(element => {
return page.evaluate((e: HTMLElement) => { return page.evaluate((e: HTMLElement) => {
return e.textContent; return e.textContent;
}, element); }, element);
@ -479,7 +479,7 @@ describe('querySelector', function () {
const html = (await page.$('html'))!; const html = (await page.$('html'))!;
const elements = await html.$$('allArray/div'); const elements = await html.$$('allArray/div');
expect(elements.length).toBe(2); expect(elements.length).toBe(2);
const promises = elements.map((element) => { const promises = elements.map(element => {
return page.evaluate((e: HTMLElement) => { return page.evaluate((e: HTMLElement) => {
return e.textContent; return e.textContent;
}, element); }, element);
@ -503,7 +503,7 @@ describe('querySelector', function () {
await page.setContent( await page.setContent(
'<div>hello</div><div>beautiful</div><div>world!</div>' '<div>hello</div><div>beautiful</div><div>world!</div>'
); );
const divsCount = await page.$$eval('allArray/div', (divs) => { const divsCount = await page.$$eval('allArray/div', divs => {
return divs.length; return divs.length;
}); });
expect(divsCount).toBe(3); expect(divsCount).toBe(3);
@ -553,7 +553,7 @@ describe('querySelector', function () {
} }
` `
); );
const sum = await page.$$eval('allArray/section', (sections) => { const sum = await page.$$eval('allArray/section', sections => {
return sections.reduce((acc, section) => { return sections.reduce((acc, section) => {
return acc + Number(section.textContent); return acc + Number(section.textContent);
}, 0); }, 0);

View File

@ -43,7 +43,7 @@ describe('request interception', function () {
const actionResults: ActionResult[] = []; const actionResults: ActionResult[] = [];
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
if (request.url().endsWith('.css')) { if (request.url().endsWith('.css')) {
request.continue( request.continue(
{headers: {...request.headers(), xaction: 'continue'}}, {headers: {...request.headers(), xaction: 'continue'}},
@ -53,7 +53,7 @@ describe('request interception', function () {
request.continue({}, 0); request.continue({}, 0);
} }
}); });
page.on('request', (request) => { page.on('request', request => {
if (request.url().endsWith('.css')) { if (request.url().endsWith('.css')) {
request.respond( request.respond(
{headers: {xaction: 'respond'}}, {headers: {xaction: 'respond'}},
@ -63,20 +63,20 @@ describe('request interception', function () {
request.continue({}, 0); request.continue({}, 0);
} }
}); });
page.on('request', (request) => { page.on('request', request => {
if (request.url().endsWith('.css')) { if (request.url().endsWith('.css')) {
request.abort('aborted', expectedAction === 'abort' ? 1 : 0); request.abort('aborted', expectedAction === 'abort' ? 1 : 0);
} else { } else {
request.continue({}, 0); request.continue({}, 0);
} }
}); });
page.on('response', (response) => { page.on('response', response => {
const {xaction} = response!.headers(); const {xaction} = response!.headers();
if (response!.url().endsWith('.css') && !!xaction) { if (response!.url().endsWith('.css') && !!xaction) {
actionResults.push(xaction as ActionResult); actionResults.push(xaction as ActionResult);
} }
}); });
page.on('requestfailed', (request) => { page.on('requestfailed', request => {
if (request.url().endsWith('.css')) { if (request.url().endsWith('.css')) {
actionResults.push('abort'); actionResults.push('abort');
} }
@ -107,7 +107,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
if (utils.isFavicon(request)) { if (utils.isFavicon(request)) {
request.continue({}, 0); request.continue({}, 0);
return; return;
@ -133,7 +133,7 @@ describe('request interception', function () {
server.setRedirect('/rredirect', '/empty.html'); server.setRedirect('/rredirect', '/empty.html');
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue({}, 0); return request.continue({}, 0);
}); });
await page.setContent(` await page.setContent(`
@ -142,7 +142,7 @@ describe('request interception', function () {
</form> </form>
`); `);
await Promise.all([ await Promise.all([
page.$eval('form', (form) => { page.$eval('form', form => {
return (form as HTMLFormElement).submit(); return (form as HTMLFormElement).submit();
}), }),
page.waitForNavigation(), page.waitForNavigation(),
@ -154,7 +154,7 @@ describe('request interception', function () {
server.setRedirect('/rrredirect', '/empty.html'); server.setRedirect('/rrredirect', '/empty.html');
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
const headers = Object.assign({}, request.headers(), { const headers = Object.assign({}, request.headers(), {
foo: 'bar', foo: 'bar',
}); });
@ -170,7 +170,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
const headers = Object.assign({}, request.headers(), { const headers = Object.assign({}, request.headers(), {
foo: 'bar', foo: 'bar',
origin: undefined, // remove "origin" header origin: undefined, // remove "origin" header
@ -190,7 +190,7 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
if (!utils.isFavicon(request)) { if (!utils.isFavicon(request)) {
requests.push(request); requests.push(request);
} }
@ -209,7 +209,7 @@ describe('request interception', function () {
// Setup request interception. // Setup request interception.
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue({}, 0); return request.continue({}, 0);
}); });
const response = await page.reload(); const response = await page.reload();
@ -219,7 +219,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.once('request', (request) => { page.once('request', request => {
return request.continue({}, 0); return request.continue({}, 0);
}); });
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -233,7 +233,7 @@ describe('request interception', function () {
foo: 'bar', foo: 'bar',
}); });
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
expect(request.headers()['foo']).toBe('bar'); expect(request.headers()['foo']).toBe('bar');
request.continue({}, 0); request.continue({}, 0);
}); });
@ -247,7 +247,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
server.setRedirect('/logo.png', '/pptr.png'); server.setRedirect('/logo.png', '/pptr.png');
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue({}, 0); return request.continue({}, 0);
}); });
const status = await page.evaluate(async () => { const status = await page.evaluate(async () => {
@ -263,7 +263,7 @@ describe('request interception', function () {
await page.setExtraHTTPHeaders({referer: server.EMPTY_PAGE}); await page.setExtraHTTPHeaders({referer: server.EMPTY_PAGE});
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
expect(request.headers()['referer']).toBe(server.EMPTY_PAGE); expect(request.headers()['referer']).toBe(server.EMPTY_PAGE);
request.continue({}, 0); request.continue({}, 0);
}); });
@ -274,7 +274,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
if (request.url().endsWith('.css')) { if (request.url().endsWith('.css')) {
request.abort('failed', 0); request.abort('failed', 0);
} else { } else {
@ -294,11 +294,11 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.abort('failed', 0); request.abort('failed', 0);
}); });
let abortReason = null; let abortReason = null;
page.on('request', (request) => { page.on('request', request => {
abortReason = request.abortErrorReason(); abortReason = request.abortErrorReason();
request.continue({}, 0); request.continue({}, 0);
}); });
@ -309,11 +309,11 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.abort('internetdisconnected', 0); request.abort('internetdisconnected', 0);
}); });
let failedRequest!: HTTPRequest; let failedRequest!: HTTPRequest;
page.on('requestfailed', (request) => { page.on('requestfailed', request => {
return (failedRequest = request); return (failedRequest = request);
}); });
await page.goto(server.EMPTY_PAGE).catch(() => {}); await page.goto(server.EMPTY_PAGE).catch(() => {});
@ -329,7 +329,7 @@ describe('request interception', function () {
referer: 'http://google.com/', referer: 'http://google.com/',
}); });
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue({}, 0); return request.continue({}, 0);
}); });
const [request] = await Promise.all([ const [request] = await Promise.all([
@ -342,11 +342,11 @@ describe('request interception', function () {
const {page, server, isChrome} = getTestState(); const {page, server, isChrome} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.abort('failed', 0); return request.abort('failed', 0);
}); });
let error!: Error; let error!: Error;
await page.goto(server.EMPTY_PAGE).catch((error_) => { await page.goto(server.EMPTY_PAGE).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeTruthy(); expect(error).toBeTruthy();
@ -361,7 +361,7 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
request.continue({}, 0); request.continue({}, 0);
requests.push(request); requests.push(request);
}); });
@ -401,7 +401,7 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
request.continue({}, 0); request.continue({}, 0);
if (!utils.isFavicon(request)) { if (!utils.isFavicon(request)) {
requests.push(request); requests.push(request);
@ -432,7 +432,7 @@ describe('request interception', function () {
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');
server.setRedirect('/non-existing-2.json', '/simple.html'); server.setRedirect('/non-existing-2.json', '/simple.html');
page.on('request', (request) => { page.on('request', request => {
if (request.url().includes('non-existing-2')) { if (request.url().includes('non-existing-2')) {
request.abort('failed', 0); request.abort('failed', 0);
} else { } else {
@ -465,7 +465,7 @@ describe('request interception', function () {
let spinner = false; let spinner = false;
// Cancel 2nd request. // Cancel 2nd request.
page.on('request', (request) => { page.on('request', request => {
if (utils.isFavicon(request)) { if (utils.isFavicon(request)) {
request.continue({}, 0); request.continue({}, 0);
return; return;
@ -476,21 +476,21 @@ describe('request interception', function () {
const results = await page.evaluate(() => { const results = await page.evaluate(() => {
return Promise.all([ return Promise.all([
fetch('/zzz') fetch('/zzz')
.then((response) => { .then(response => {
return response!.text(); return response!.text();
}) })
.catch(() => { .catch(() => {
return 'FAILED'; return 'FAILED';
}), }),
fetch('/zzz') fetch('/zzz')
.then((response) => { .then(response => {
return response!.text(); return response!.text();
}) })
.catch(() => { .catch(() => {
return 'FAILED'; return 'FAILED';
}), }),
fetch('/zzz') fetch('/zzz')
.then((response) => { .then(response => {
return response!.text(); return response!.text();
}) })
.catch(() => { .catch(() => {
@ -505,7 +505,7 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
requests.push(request); requests.push(request);
request.continue({}, 0); request.continue({}, 0);
}); });
@ -521,13 +521,13 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
!utils.isFavicon(request) && requests.push(request); !utils.isFavicon(request) && requests.push(request);
request.continue({}, 0); request.continue({}, 0);
}); });
const dataURL = 'data:text/html,<div>yo</div>'; const dataURL = 'data:text/html,<div>yo</div>';
const text = await page.evaluate((url: string) => { const text = await page.evaluate((url: string) => {
return fetch(url).then((r) => { return fetch(url).then(r => {
return r.text(); return r.text();
}); });
}, dataURL); }, dataURL);
@ -540,7 +540,7 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
requests.push(request); requests.push(request);
request.continue({}, 0); request.continue({}, 0);
}); });
@ -556,7 +556,7 @@ describe('request interception', function () {
// 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
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue({}, 0); return request.continue({}, 0);
}); });
const response = await page.goto( const response = await page.goto(
@ -571,7 +571,7 @@ describe('request interception', function () {
server.setRoute('/malformed?rnd=%911', (_req, res) => { server.setRoute('/malformed?rnd=%911', (_req, res) => {
return res.end(); return res.end();
}); });
page.on('request', (request) => { page.on('request', request => {
return request.continue({}, 0); return request.continue({}, 0);
}); });
const response = await page.goto(server.PREFIX + '/malformed?rnd=%911'); const response = await page.goto(server.PREFIX + '/malformed?rnd=%911');
@ -584,7 +584,7 @@ describe('request interception', function () {
// report encoded URL for stylesheet. @see crbug.com/759388 // report encoded URL for stylesheet. @see crbug.com/759388
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
request.continue({}, 0); request.continue({}, 0);
requests.push(request); requests.push(request);
}); });
@ -601,7 +601,7 @@ describe('request interception', function () {
await page.setContent('<iframe></iframe>'); await page.setContent('<iframe></iframe>');
await page.setRequestInterception(true); await page.setRequestInterception(true);
let request!: HTTPRequest; let request!: HTTPRequest;
page.on('request', async (r) => { page.on('request', async r => {
return (request = r); return (request = r);
}); });
page.$eval( page.$eval(
@ -614,11 +614,11 @@ describe('request interception', function () {
// Wait for request interception. // Wait for request interception.
await utils.waitEvent(page, 'request'); await utils.waitEvent(page, 'request');
// Delete frame to cause request to be canceled. // Delete frame to cause request to be canceled.
await page.$eval('iframe', (frame) => { await page.$eval('iframe', frame => {
return frame.remove(); return frame.remove();
}); });
let error!: Error; let error!: Error;
await request.continue({}, 0).catch((error_) => { await request.continue({}, 0).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeUndefined(); expect(error).toBeUndefined();
@ -627,7 +627,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
let error!: Error; let error!: Error;
page.on('request', async (request) => { page.on('request', async request => {
try { try {
await request.continue({}, 0); await request.continue({}, 0);
} catch (error_) { } catch (error_) {
@ -642,7 +642,7 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
const urls = new Set(); const urls = new Set();
page.on('request', (request) => { page.on('request', request => {
urls.add(request.url().split('/').pop()); urls.add(request.url().split('/').pop());
request.continue({}, 0); request.continue({}, 0);
}); });
@ -661,12 +661,12 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
await page.setCacheEnabled(false); await page.setCacheEnabled(false);
page.on('request', (request) => { page.on('request', request => {
return request.continue({}, 0); return request.continue({}, 0);
}); });
const cached = []; const cached = [];
page.on('requestservedfromcache', (r) => { page.on('requestservedfromcache', r => {
return cached.push(r); return cached.push(r);
}); });
@ -681,12 +681,12 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
await page.setCacheEnabled(true); await page.setCacheEnabled(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue({}, 0); return request.continue({}, 0);
}); });
const cached = []; const cached = [];
page.on('requestservedfromcache', (r) => { page.on('requestservedfromcache', r => {
return cached.push(r); return cached.push(r);
}); });
@ -698,12 +698,12 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
await page.setCacheEnabled(true); await page.setCacheEnabled(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue({}, 0); return request.continue({}, 0);
}); });
await page.goto(server.PREFIX + '/cached/one-style-font.html'); await page.goto(server.PREFIX + '/cached/one-style-font.html');
await page.waitForResponse((r) => { await page.waitForResponse(r => {
return r.url().endsWith('/one-style.woff'); return r.url().endsWith('/one-style.woff');
}); });
}); });
@ -714,7 +714,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue({}, 0); return request.continue({}, 0);
}); });
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -723,7 +723,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
const headers = Object.assign({}, request.headers()); const headers = Object.assign({}, request.headers());
headers['FOO'] = 'bar'; headers['FOO'] = 'bar';
request.continue({headers}, 0); request.continue({headers}, 0);
@ -741,14 +741,14 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
const redirectURL = request.url().includes('/empty.html') const redirectURL = request.url().includes('/empty.html')
? server.PREFIX + '/consolelog.html' ? server.PREFIX + '/consolelog.html'
: undefined; : undefined;
request.continue({url: redirectURL}, 0); request.continue({url: redirectURL}, 0);
}); });
let consoleMessage!: ConsoleMessage; let consoleMessage!: ConsoleMessage;
page.on('console', (msg) => { page.on('console', msg => {
return (consoleMessage = msg); return (consoleMessage = msg);
}); });
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -761,7 +761,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.continue({method: 'POST'}, 0); request.continue({method: 'POST'}, 0);
}); });
const [request] = await Promise.all([ const [request] = await Promise.all([
@ -778,7 +778,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.continue({postData: 'doggo'}, 0); request.continue({postData: 'doggo'}, 0);
}); });
const [serverRequest] = await Promise.all([ const [serverRequest] = await Promise.all([
@ -793,7 +793,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.continue({method: 'POST', postData: 'doggo'}, 0); request.continue({method: 'POST', postData: 'doggo'}, 0);
}); });
const [serverRequest] = await Promise.all([ const [serverRequest] = await Promise.all([
@ -810,7 +810,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.respond( request.respond(
{ {
status: 201, status: 201,
@ -835,7 +835,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.respond( request.respond(
{ {
status: 200, status: 200,
@ -845,7 +845,7 @@ describe('request interception', function () {
); );
}); });
let response = null; let response = null;
page.on('request', (request) => { page.on('request', request => {
response = request.responseForRequest(); response = request.responseForRequest();
request.continue({}, 0); request.continue({}, 0);
}); });
@ -856,7 +856,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.respond( request.respond(
{ {
status: 422, status: 422,
@ -878,7 +878,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
if (!request.url().includes('rrredirect')) { if (!request.url().includes('rrredirect')) {
request.continue({}, 0); request.continue({}, 0);
return; return;
@ -904,7 +904,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
const imageBuffer = fs.readFileSync( const imageBuffer = fs.readFileSync(
path.join(__dirname, '../assets', 'pptr.png') path.join(__dirname, '../assets', 'pptr.png')
); );
@ -916,11 +916,11 @@ describe('request interception', function () {
0 0
); );
}); });
await page.evaluate((PREFIX) => { await page.evaluate(PREFIX => {
const img = document.createElement('img'); const img = document.createElement('img');
img.src = PREFIX + '/does-not-exist.png'; img.src = PREFIX + '/does-not-exist.png';
document.body.appendChild(img); document.body.appendChild(img);
return new Promise((fulfill) => { return new Promise(fulfill => {
return (img.onload = fulfill); return (img.onload = fulfill);
}); });
}, server.PREFIX); }, server.PREFIX);
@ -931,7 +931,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.respond( request.respond(
{ {
status: 200, status: 200,
@ -957,13 +957,13 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.continue(); request.continue();
}); });
page.on('request', (request) => { page.on('request', request => {
expect(request.isInterceptResolutionHandled()).toBeTruthy(); expect(request.isInterceptResolutionHandled()).toBeTruthy();
}); });
page.on('request', (request) => { page.on('request', request => {
const {action} = request.interceptResolutionState(); const {action} = request.interceptResolutionState();
expect(action).toBe(InterceptResolutionAction.AlreadyHandled); expect(action).toBe(InterceptResolutionAction.AlreadyHandled);
}); });

View File

@ -35,7 +35,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
if (utils.isFavicon(request)) { if (utils.isFavicon(request)) {
request.continue(); request.continue();
return; return;
@ -62,7 +62,7 @@ describe('request interception', function () {
server.setRedirect('/rredirect', '/empty.html'); server.setRedirect('/rredirect', '/empty.html');
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue(); return request.continue();
}); });
await page.setContent(` await page.setContent(`
@ -71,7 +71,7 @@ describe('request interception', function () {
</form> </form>
`); `);
await Promise.all([ await Promise.all([
page.$eval('form', (form) => { page.$eval('form', form => {
return (form as HTMLFormElement).submit(); return (form as HTMLFormElement).submit();
}), }),
page.waitForNavigation(), page.waitForNavigation(),
@ -83,7 +83,7 @@ describe('request interception', function () {
server.setRedirect('/rrredirect', '/empty.html'); server.setRedirect('/rrredirect', '/empty.html');
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
const headers = Object.assign({}, request.headers(), { const headers = Object.assign({}, request.headers(), {
foo: 'bar', foo: 'bar',
}); });
@ -96,7 +96,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
const headers = Object.assign({}, request.headers(), { const headers = Object.assign({}, request.headers(), {
foo: 'bar', foo: 'bar',
origin: undefined, // remove "origin" header origin: undefined, // remove "origin" header
@ -116,7 +116,7 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
if (!utils.isFavicon(request)) { if (!utils.isFavicon(request)) {
requests.push(request); requests.push(request);
} }
@ -135,7 +135,7 @@ describe('request interception', function () {
// Setup request interception. // Setup request interception.
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue(); return request.continue();
}); });
const response = (await page.reload())!; const response = (await page.reload())!;
@ -145,7 +145,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.once('request', (request) => { page.once('request', request => {
return request.continue(); return request.continue();
}); });
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -159,7 +159,7 @@ describe('request interception', function () {
foo: 'bar', foo: 'bar',
}); });
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
expect(request.headers()['foo']).toBe('bar'); expect(request.headers()['foo']).toBe('bar');
request.continue(); request.continue();
}); });
@ -173,7 +173,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
server.setRedirect('/logo.png', '/pptr.png'); server.setRedirect('/logo.png', '/pptr.png');
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue(); return request.continue();
}); });
const status = await page.evaluate(async () => { const status = await page.evaluate(async () => {
@ -189,7 +189,7 @@ describe('request interception', function () {
await page.setExtraHTTPHeaders({referer: server.EMPTY_PAGE}); await page.setExtraHTTPHeaders({referer: server.EMPTY_PAGE});
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
expect(request.headers()['referer']).toBe(server.EMPTY_PAGE); expect(request.headers()['referer']).toBe(server.EMPTY_PAGE);
request.continue(); request.continue();
}); });
@ -200,7 +200,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
if (request.url().endsWith('.css')) { if (request.url().endsWith('.css')) {
request.abort(); request.abort();
} else { } else {
@ -220,11 +220,11 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.abort('internetdisconnected'); request.abort('internetdisconnected');
}); });
let failedRequest!: HTTPRequest; let failedRequest!: HTTPRequest;
page.on('requestfailed', (request) => { page.on('requestfailed', request => {
return (failedRequest = request); return (failedRequest = request);
}); });
await page.goto(server.EMPTY_PAGE).catch(() => {}); await page.goto(server.EMPTY_PAGE).catch(() => {});
@ -240,7 +240,7 @@ describe('request interception', function () {
referer: 'http://google.com/', referer: 'http://google.com/',
}); });
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue(); return request.continue();
}); });
const [request] = await Promise.all([ const [request] = await Promise.all([
@ -253,11 +253,11 @@ describe('request interception', function () {
const {page, server, isChrome} = getTestState(); const {page, server, isChrome} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.abort(); return request.abort();
}); });
let error!: Error; let error!: Error;
await page.goto(server.EMPTY_PAGE).catch((error_) => { await page.goto(server.EMPTY_PAGE).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeTruthy(); expect(error).toBeTruthy();
@ -272,7 +272,7 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
request.continue(); request.continue();
requests.push(request); requests.push(request);
}); });
@ -312,7 +312,7 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
request.continue(); request.continue();
if (!utils.isFavicon(request)) { if (!utils.isFavicon(request)) {
requests.push(request); requests.push(request);
@ -343,7 +343,7 @@ describe('request interception', function () {
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');
server.setRedirect('/non-existing-2.json', '/simple.html'); server.setRedirect('/non-existing-2.json', '/simple.html');
page.on('request', (request) => { page.on('request', request => {
if (request.url().includes('non-existing-2')) { if (request.url().includes('non-existing-2')) {
request.abort(); request.abort();
} else { } else {
@ -376,7 +376,7 @@ describe('request interception', function () {
let spinner = false; let spinner = false;
// Cancel 2nd request. // Cancel 2nd request.
page.on('request', (request) => { page.on('request', request => {
if (utils.isFavicon(request)) { if (utils.isFavicon(request)) {
request.continue(); request.continue();
return; return;
@ -387,21 +387,21 @@ describe('request interception', function () {
const results = await page.evaluate(() => { const results = await page.evaluate(() => {
return Promise.all([ return Promise.all([
fetch('/zzz') fetch('/zzz')
.then((response) => { .then(response => {
return response.text(); return response.text();
}) })
.catch(() => { .catch(() => {
return 'FAILED'; return 'FAILED';
}), }),
fetch('/zzz') fetch('/zzz')
.then((response) => { .then(response => {
return response.text(); return response.text();
}) })
.catch(() => { .catch(() => {
return 'FAILED'; return 'FAILED';
}), }),
fetch('/zzz') fetch('/zzz')
.then((response) => { .then(response => {
return response.text(); return response.text();
}) })
.catch(() => { .catch(() => {
@ -416,7 +416,7 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
requests.push(request); requests.push(request);
request.continue(); request.continue();
}); });
@ -432,13 +432,13 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
!utils.isFavicon(request) && requests.push(request); !utils.isFavicon(request) && requests.push(request);
request.continue(); request.continue();
}); });
const dataURL = 'data:text/html,<div>yo</div>'; const dataURL = 'data:text/html,<div>yo</div>';
const text = await page.evaluate((url: string) => { const text = await page.evaluate((url: string) => {
return fetch(url).then((r) => { return fetch(url).then(r => {
return r.text(); return r.text();
}); });
}, dataURL); }, dataURL);
@ -451,7 +451,7 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
requests.push(request); requests.push(request);
request.continue(); request.continue();
}); });
@ -467,7 +467,7 @@ describe('request interception', function () {
// 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
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue(); return request.continue();
}); });
const response = (await page.goto( const response = (await page.goto(
@ -482,7 +482,7 @@ describe('request interception', function () {
server.setRoute('/malformed?rnd=%911', (_req, res) => { server.setRoute('/malformed?rnd=%911', (_req, res) => {
return res.end(); return res.end();
}); });
page.on('request', (request) => { page.on('request', request => {
return request.continue(); return request.continue();
}); });
const response = (await page.goto( const response = (await page.goto(
@ -497,7 +497,7 @@ describe('request interception', function () {
// report encoded URL for stylesheet. @see crbug.com/759388 // report encoded URL for stylesheet. @see crbug.com/759388
await page.setRequestInterception(true); await page.setRequestInterception(true);
const requests: HTTPRequest[] = []; const requests: HTTPRequest[] = [];
page.on('request', (request) => { page.on('request', request => {
request.continue(); request.continue();
requests.push(request); requests.push(request);
}); });
@ -514,7 +514,7 @@ describe('request interception', function () {
await page.setContent('<iframe></iframe>'); await page.setContent('<iframe></iframe>');
await page.setRequestInterception(true); await page.setRequestInterception(true);
let request!: HTTPRequest; let request!: HTTPRequest;
page.on('request', async (r) => { page.on('request', async r => {
return (request = r); return (request = r);
}); });
page.$eval( page.$eval(
@ -527,11 +527,11 @@ describe('request interception', function () {
// Wait for request interception. // Wait for request interception.
await utils.waitEvent(page, 'request'); await utils.waitEvent(page, 'request');
// Delete frame to cause request to be canceled. // Delete frame to cause request to be canceled.
await page.$eval('iframe', (frame) => { await page.$eval('iframe', frame => {
return frame.remove(); return frame.remove();
}); });
let error!: Error; let error!: Error;
await request.continue().catch((error_) => { await request.continue().catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeUndefined(); expect(error).toBeUndefined();
@ -540,7 +540,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
let error!: Error; let error!: Error;
page.on('request', async (request) => { page.on('request', async request => {
try { try {
await request.continue(); await request.continue();
} catch (error_) { } catch (error_) {
@ -555,7 +555,7 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
const urls = new Set(); const urls = new Set();
page.on('request', (request) => { page.on('request', request => {
urls.add(request.url().split('/').pop()); urls.add(request.url().split('/').pop());
request.continue(); request.continue();
}); });
@ -574,12 +574,12 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
await page.setCacheEnabled(false); await page.setCacheEnabled(false);
page.on('request', (request) => { page.on('request', request => {
return request.continue(); return request.continue();
}); });
const cached = []; const cached = [];
page.on('requestservedfromcache', (r) => { page.on('requestservedfromcache', r => {
return cached.push(r); return cached.push(r);
}); });
@ -594,12 +594,12 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
await page.setCacheEnabled(true); await page.setCacheEnabled(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue(); return request.continue();
}); });
const cached = []; const cached = [];
page.on('requestservedfromcache', (r) => { page.on('requestservedfromcache', r => {
return cached.push(r); return cached.push(r);
}); });
@ -611,12 +611,12 @@ describe('request interception', function () {
await page.setRequestInterception(true); await page.setRequestInterception(true);
await page.setCacheEnabled(true); await page.setCacheEnabled(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue(); return request.continue();
}); });
await page.goto(server.PREFIX + '/cached/one-style-font.html'); await page.goto(server.PREFIX + '/cached/one-style-font.html');
await page.waitForResponse((r) => { await page.waitForResponse(r => {
return r.url().endsWith('/one-style.woff'); return r.url().endsWith('/one-style.woff');
}); });
}); });
@ -627,7 +627,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
return request.continue(); return request.continue();
}); });
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -636,7 +636,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
const headers = Object.assign({}, request.headers()); const headers = Object.assign({}, request.headers());
headers['FOO'] = 'bar'; headers['FOO'] = 'bar';
request.continue({headers}); request.continue({headers});
@ -654,14 +654,14 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
const redirectURL = request.url().includes('/empty.html') const redirectURL = request.url().includes('/empty.html')
? server.PREFIX + '/consolelog.html' ? server.PREFIX + '/consolelog.html'
: undefined; : undefined;
request.continue({url: redirectURL}); request.continue({url: redirectURL});
}); });
let consoleMessage!: ConsoleMessage; let consoleMessage!: ConsoleMessage;
page.on('console', (msg) => { page.on('console', msg => {
return (consoleMessage = msg); return (consoleMessage = msg);
}); });
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -674,7 +674,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.continue({method: 'POST'}); request.continue({method: 'POST'});
}); });
const [request] = await Promise.all([ const [request] = await Promise.all([
@ -691,7 +691,7 @@ describe('request interception', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.continue({postData: 'doggo'}); request.continue({postData: 'doggo'});
}); });
const [serverRequest] = await Promise.all([ const [serverRequest] = await Promise.all([
@ -706,7 +706,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.continue({method: 'POST', postData: 'doggo'}); request.continue({method: 'POST', postData: 'doggo'});
}); });
const [serverRequest] = await Promise.all([ const [serverRequest] = await Promise.all([
@ -721,14 +721,14 @@ describe('request interception', function () {
let error!: Error; let error!: Error;
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', async (request) => { page.on('request', async request => {
await request await request
.continue({ .continue({
headers: { headers: {
'X-Invalid-Header': 'a\nb', 'X-Invalid-Header': 'a\nb',
}, },
}) })
.catch((error_) => { .catch(error_ => {
error = error_ as Error; error = error_ as Error;
}); });
await request.continue(); await request.continue();
@ -743,7 +743,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.respond({ request.respond({
status: 201, status: 201,
headers: { headers: {
@ -765,7 +765,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.respond({ request.respond({
status: 422, status: 422,
body: 'Yo, page!', body: 'Yo, page!',
@ -784,7 +784,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
if (!request.url().includes('rrredirect')) { if (!request.url().includes('rrredirect')) {
request.continue(); request.continue();
return; return;
@ -807,7 +807,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.respond({ request.respond({
status: 200, status: 200,
headers: { headers: {
@ -820,10 +820,10 @@ describe('request interception', function () {
}); });
const response = (await page.goto(server.EMPTY_PAGE))!; const response = (await page.goto(server.EMPTY_PAGE))!;
const cookies = await page.cookies(); const cookies = await page.cookies();
const firstCookie = cookies.find((cookie) => { const firstCookie = cookies.find(cookie => {
return cookie.name === 'first'; return cookie.name === 'first';
}); });
const secondCookie = cookies.find((cookie) => { const secondCookie = cookies.find(cookie => {
return cookie.name === 'second'; return cookie.name === 'second';
}); });
expect(response.status()).toBe(200); expect(response.status()).toBe(200);
@ -838,7 +838,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
const imageBuffer = fs.readFileSync( const imageBuffer = fs.readFileSync(
path.join(__dirname, '../assets', 'pptr.png') path.join(__dirname, '../assets', 'pptr.png')
); );
@ -847,11 +847,11 @@ describe('request interception', function () {
body: imageBuffer, body: imageBuffer,
}); });
}); });
await page.evaluate((PREFIX) => { await page.evaluate(PREFIX => {
const img = document.createElement('img'); const img = document.createElement('img');
img.src = PREFIX + '/does-not-exist.png'; img.src = PREFIX + '/does-not-exist.png';
document.body.appendChild(img); document.body.appendChild(img);
return new Promise((fulfill) => { return new Promise(fulfill => {
return (img.onload = fulfill); return (img.onload = fulfill);
}); });
}, server.PREFIX); }, server.PREFIX);
@ -862,7 +862,7 @@ describe('request interception', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', (request) => { page.on('request', request => {
request.respond({ request.respond({
status: 200, status: 200,
headers: { headers: {
@ -886,14 +886,14 @@ describe('request interception', function () {
let error!: Error; let error!: Error;
await page.setRequestInterception(true); await page.setRequestInterception(true);
page.on('request', async (request) => { page.on('request', async request => {
await request await request
.respond({ .respond({
headers: { headers: {
'X-Invalid-Header': 'a\nb', 'X-Invalid-Header': 'a\nb',
}, },
}) })
.catch((error_) => { .catch(error_ => {
error = error_ as Error; error = error_ as Error;
}); });
await request.respond({ await request.respond({

View File

@ -124,7 +124,7 @@ describe('Screenshots', function () {
expect(screenshots[i]).toBeGolden(`grid-cell-${i}.png`); expect(screenshots[i]).toBeGolden(`grid-cell-${i}.png`);
} }
await Promise.all( await Promise.all(
pages.map((page) => { pages.map(page => {
return page.close(); return page.close();
}) })
); );
@ -310,9 +310,7 @@ describe('Screenshots', function () {
await page.evaluate((element: HTMLElement) => { await page.evaluate((element: HTMLElement) => {
return element.remove(); return element.remove();
}, elementHandle); }, elementHandle);
const screenshotError = await elementHandle const screenshotError = await elementHandle.screenshot().catch(error => {
.screenshot()
.catch((error) => {
return error; return error;
}); });
expect(screenshotError.message).toBe( expect(screenshotError.message).toBe(
@ -324,7 +322,7 @@ describe('Screenshots', function () {
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'))!;
const error = await div.screenshot().catch((error_) => { const error = await div.screenshot().catch(error_ => {
return error_; return error_;
}); });
expect(error.message).toBe('Node has 0 height.'); expect(error.message).toBe('Node has 0 height.');

View File

@ -37,12 +37,12 @@ describe('Target', function () {
// 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();
expect( expect(
targets.some((target) => { targets.some(target => {
return target.type() === 'page' && target.url() === 'about:blank'; return target.type() === 'page' && target.url() === 'about:blank';
}) })
).toBeTruthy(); ).toBeTruthy();
expect( expect(
targets.some((target) => { targets.some(target => {
return target.type() === 'browser'; return target.type() === 'browser';
}) })
).toBeTruthy(); ).toBeTruthy();
@ -59,7 +59,7 @@ describe('Target', function () {
const {browser} = getTestState(); const {browser} = getTestState();
const targets = browser.targets(); const targets = browser.targets();
const browserTarget = targets.find((target) => { const browserTarget = targets.find(target => {
return target.type() === 'browser'; return target.type() === 'browser';
}); });
expect(browserTarget).toBeTruthy(); expect(browserTarget).toBeTruthy();
@ -69,7 +69,7 @@ describe('Target', function () {
// 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();
const originalPage = allPages.find((p) => { const originalPage = allPages.find(p => {
return p !== page; return p !== page;
})!; })!;
expect( expect(
@ -84,12 +84,12 @@ describe('Target', function () {
const [otherPage] = await Promise.all([ const [otherPage] = await Promise.all([
context context
.waitForTarget((target) => { .waitForTarget(target => {
return target.page().then((page) => { return target.page().then(page => {
return page!.url() === server.CROSS_PROCESS_PREFIX + '/empty.html'; return page!.url() === server.CROSS_PROCESS_PREFIX + '/empty.html';
}); });
}) })
.then((target) => { .then(target => {
return target.page(); return target.page();
}), }),
page.evaluate((url: string) => { page.evaluate((url: string) => {
@ -108,10 +108,10 @@ describe('Target', function () {
const [otherPage] = await Promise.all([ const [otherPage] = await Promise.all([
context context
.waitForTarget((target) => { .waitForTarget(target => {
return target.url() === server.CROSS_PROCESS_PREFIX + '/empty.html'; return target.url() === server.CROSS_PROCESS_PREFIX + '/empty.html';
}) })
.then((target) => { .then(target => {
return target.page(); return target.page();
}), }),
page.evaluate((url: string) => { page.evaluate((url: string) => {
@ -130,8 +130,8 @@ describe('Target', function () {
expect(allPages).toContain(page); expect(allPages).toContain(page);
expect(allPages).toContain(otherPage); expect(allPages).toContain(otherPage);
const closePagePromise = new Promise((fulfill) => { const closePagePromise = new Promise(fulfill => {
return context.once('targetdestroyed', (target) => { return context.once('targetdestroyed', target => {
return fulfill(target.page()); return fulfill(target.page());
}); });
}); });
@ -139,7 +139,7 @@ describe('Target', function () {
expect(await closePagePromise).toBe(otherPage); expect(await closePagePromise).toBe(otherPage);
allPages = (await Promise.all( allPages = (await Promise.all(
context.targets().map((target) => { context.targets().map(target => {
return target.page(); return target.page();
}) })
)) as Page[]; )) as Page[];
@ -153,8 +153,8 @@ describe('Target', function () {
const {page, server, context} = getTestState(); const {page, server, context} = getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const createdTarget = new Promise<Target>((fulfill) => { const createdTarget = new Promise<Target>(fulfill => {
return context.once('targetcreated', (target) => { return context.once('targetcreated', target => {
return fulfill(target); return fulfill(target);
}); });
}); });
@ -166,8 +166,8 @@ describe('Target', function () {
server.PREFIX + '/serviceworkers/empty/sw.js' server.PREFIX + '/serviceworkers/empty/sw.js'
); );
const destroyedTarget = new Promise((fulfill) => { const destroyedTarget = new Promise(fulfill => {
return context.once('targetdestroyed', (target) => { return context.once('targetdestroyed', target => {
return fulfill(target); return fulfill(target);
}); });
}); });
@ -186,7 +186,7 @@ describe('Target', function () {
await page.goto(server.PREFIX + '/serviceworkers/empty/sw.html'); await page.goto(server.PREFIX + '/serviceworkers/empty/sw.html');
const target = await context.waitForTarget((target) => { const target = await context.waitForTarget(target => {
return target.type() === 'service_worker'; return target.type() === 'service_worker';
}); });
const worker = (await target.worker())!; const worker = (await target.worker())!;
@ -203,7 +203,7 @@ describe('Target', function () {
await page.evaluate(() => { await page.evaluate(() => {
new SharedWorker('data:text/javascript,console.log("hi")'); new SharedWorker('data:text/javascript,console.log("hi")');
}); });
const target = await context.waitForTarget((target) => { const target = await context.waitForTarget(target => {
return target.type() === 'shared_worker'; return target.type() === 'shared_worker';
}); });
const worker = (await target.worker())!; const worker = (await target.worker())!;
@ -217,16 +217,16 @@ describe('Target', function () {
const {page, server, context} = getTestState(); const {page, server, context} = getTestState();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
let changedTarget = new Promise<Target>((fulfill) => { let changedTarget = new Promise<Target>(fulfill => {
return context.once('targetchanged', (target) => { return context.once('targetchanged', target => {
return fulfill(target); return fulfill(target);
}); });
}); });
await page.goto(server.CROSS_PROCESS_PREFIX + '/'); await page.goto(server.CROSS_PROCESS_PREFIX + '/');
expect((await changedTarget).url()).toBe(server.CROSS_PROCESS_PREFIX + '/'); expect((await changedTarget).url()).toBe(server.CROSS_PROCESS_PREFIX + '/');
changedTarget = new Promise((fulfill) => { changedTarget = new Promise(fulfill => {
return context.once('targetchanged', (target) => { return context.once('targetchanged', target => {
return fulfill(target); return fulfill(target);
}); });
}); });
@ -241,8 +241,8 @@ describe('Target', function () {
return (targetChanged = true); return (targetChanged = true);
}; };
context.on('targetchanged', listener); context.on('targetchanged', listener);
const targetPromise = new Promise<Target>((fulfill) => { const targetPromise = new Promise<Target>(fulfill => {
return context.once('targetcreated', (target) => { return context.once('targetcreated', target => {
return fulfill(target); return fulfill(target);
}); });
}); });
@ -251,8 +251,8 @@ describe('Target', function () {
expect(target.url()).toBe('about:blank'); expect(target.url()).toBe('about:blank');
const newPage = await newPagePromise; const newPage = await newPagePromise;
const targetPromise2 = new Promise<Target>((fulfill) => { const targetPromise2 = new Promise<Target>(fulfill => {
return context.once('targetcreated', (target) => { return context.once('targetcreated', target => {
return fulfill(target); return fulfill(target);
}); });
}); });
@ -283,7 +283,7 @@ describe('Target', function () {
server.waitForRequest('/one-style.css'), server.waitForRequest('/one-style.css'),
]); ]);
// Connect to the opened page. // Connect to the opened page.
const target = await context.waitForTarget((target) => { const target = await context.waitForTarget(target => {
return target.url().includes('one-style.html'); return target.url().includes('one-style.html');
}); });
const newPage = (await target.page())!; const newPage = (await target.page())!;
@ -301,8 +301,8 @@ describe('Target', function () {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const [createdTarget] = await Promise.all([ const [createdTarget] = await Promise.all([
new Promise<Target>((fulfill) => { new Promise<Target>(fulfill => {
return context.once('targetcreated', (target) => { return context.once('targetcreated', target => {
return fulfill(target); return fulfill(target);
}); });
}), }),
@ -320,14 +320,14 @@ describe('Target', function () {
const {browser, puppeteer, server} = getTestState(); const {browser, puppeteer, server} = getTestState();
let resolved = false; let resolved = false;
const targetPromise = browser.waitForTarget((target) => { const targetPromise = browser.waitForTarget(target => {
return target.url() === server.EMPTY_PAGE; return target.url() === server.EMPTY_PAGE;
}); });
targetPromise targetPromise
.then(() => { .then(() => {
return (resolved = true); return (resolved = true);
}) })
.catch((error) => { .catch(error => {
resolved = true; resolved = true;
if (error instanceof puppeteer.errors.TimeoutError) { if (error instanceof puppeteer.errors.TimeoutError) {
console.error(error); console.error(error);
@ -356,14 +356,14 @@ describe('Target', function () {
let error!: Error; let error!: Error;
await browser await browser
.waitForTarget( .waitForTarget(
(target) => { target => {
return target.url() === server.EMPTY_PAGE; return target.url() === server.EMPTY_PAGE;
}, },
{ {
timeout: 1, timeout: 1,
} }
) )
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);

View File

@ -93,7 +93,7 @@ describeChromeOnly('Tracing', function () {
await page.tracing.start({path: outputFile}); await page.tracing.start({path: outputFile});
const newPage = await browser.newPage(); const newPage = await browser.newPage();
let error!: Error; let error!: Error;
await newPage.tracing.start({ path: outputFile }).catch((error_) => { await newPage.tracing.start({path: outputFile}).catch(error_ => {
return (error = error_); return (error = error_);
}); });
await newPage.close(); await newPage.close();

View File

@ -72,16 +72,14 @@ export const attachFrame = async (
frame.src = url; frame.src = url;
frame.id = frameId; frame.id = frameId;
document.body.appendChild(frame); document.body.appendChild(frame);
await new Promise((x) => { await new Promise(x => {
return (frame.onload = x); return (frame.onload = x);
}); });
return frame; return frame;
} }
}; };
export const isFavicon = (request: { export const isFavicon = (request: {url: () => string | string[]}): boolean => {
url: () => string | string[];
}): boolean => {
return request.url().includes('favicon.ico'); return request.url().includes('favicon.ico');
}; };
@ -107,7 +105,7 @@ export async function navigateFrame(
function navigateFrame(frameId: string, url: any) { function navigateFrame(frameId: string, url: any) {
const frame = document.getElementById(frameId) as HTMLIFrameElement; const frame = document.getElementById(frameId) as HTMLIFrameElement;
frame.src = url; frame.src = url;
return new Promise((x) => { return new Promise(x => {
return (frame.onload = x); return (frame.onload = x);
}); });
} }
@ -136,7 +134,7 @@ export const waitEvent = (
return true; return true;
} }
): Promise<any> => { ): Promise<any> => {
return new Promise((fulfill) => { return new Promise(fulfill => {
emitter.on(eventName, function listener(event: any) { emitter.on(eventName, function listener(event: any) {
if (!predicate(event)) { if (!predicate(event)) {
return; return;

View File

@ -82,7 +82,7 @@ describe('waittask specs', function () {
await page.setContent(`<div>some text</div>`); await page.setContent(`<div>some text</div>`);
let error!: Error; let error!: Error;
await page.waitFor('/html/body/div').catch((error_) => { await page.waitFor('/html/body/div').catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeTruthy(); expect(error).toBeTruthy();
@ -321,7 +321,7 @@ describe('waittask specs', function () {
polling: 'raf', polling: 'raf',
} }
) )
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}), }),
page.evaluate(() => { page.evaluate(() => {
@ -417,7 +417,7 @@ describe('waittask specs', function () {
const {page, puppeteer} = getTestState(); const {page, puppeteer} = getTestState();
let error!: Error; let error!: Error;
await page.waitForFunction('false', { timeout: 10 }).catch((error_) => { await page.waitForFunction('false', {timeout: 10}).catch(error_ => {
return (error = error_); return (error = error_);
}); });
@ -429,7 +429,7 @@ describe('waittask specs', function () {
page.setDefaultTimeout(1); page.setDefaultTimeout(1);
let error!: Error; let error!: Error;
await page.waitForFunction('false').catch((error_) => { await page.waitForFunction('false').catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -618,7 +618,7 @@ describe('waittask specs', function () {
await attachFrame(page, 'frame1', server.EMPTY_PAGE); await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = page.frames()[1]!; const frame = page.frames()[1]!;
let waitError: Error | undefined; let waitError: Error | undefined;
const waitPromise = frame.waitForSelector('.box').catch((error) => { const waitPromise = frame.waitForSelector('.box').catch(error => {
return (waitError = error); return (waitError = error);
}); });
await detachFrame(page, 'frame1'); await detachFrame(page, 'frame1');
@ -763,7 +763,7 @@ describe('waittask specs', function () {
const {page, puppeteer} = getTestState(); const {page, puppeteer} = getTestState();
let error!: Error; let error!: Error;
await page.waitForSelector('div', { timeout: 10 }).catch((error_) => { await page.waitForSelector('div', {timeout: 10}).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -778,7 +778,7 @@ describe('waittask specs', function () {
let error!: Error; let error!: Error;
await page await page
.waitForSelector('div', {hidden: true, timeout: 10}) .waitForSelector('div', {hidden: true, timeout: 10})
.catch((error_) => { .catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeTruthy(); expect(error).toBeTruthy();
@ -816,7 +816,7 @@ describe('waittask specs', function () {
const {page} = getTestState(); const {page} = getTestState();
let error!: Error; let error!: Error;
await page.waitForSelector('.zombo', { timeout: 10 }).catch((error_) => { await page.waitForSelector('.zombo', {timeout: 10}).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error?.stack).toContain('waiting for selector `.zombo` failed'); expect(error?.stack).toContain('waiting for selector `.zombo` failed');
@ -847,7 +847,7 @@ describe('waittask specs', function () {
const {page, puppeteer} = getTestState(); const {page, puppeteer} = getTestState();
let error!: Error; let error!: Error;
await page.waitForXPath('//div', { timeout: 10 }).catch((error_) => { await page.waitForXPath('//div', {timeout: 10}).catch(error_ => {
return (error = error_); return (error = error_);
}); });
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError); expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
@ -876,7 +876,7 @@ describe('waittask specs', function () {
let waitError: Error | undefined; let waitError: Error | undefined;
const waitPromise = frame const waitPromise = frame
.waitForXPath('//*[@class="box"]') .waitForXPath('//*[@class="box"]')
.catch((error) => { .catch(error => {
return (waitError = error); return (waitError = error);
}); });
await detachFrame(page, 'frame1'); await detachFrame(page, 'frame1');

View File

@ -32,7 +32,7 @@ describeFailsFirefox('Workers', function () {
const {page, server} = getTestState(); const {page, server} = getTestState();
await Promise.all([ await Promise.all([
new Promise((x) => { new Promise(x => {
return page.once('workercreated', x); return page.once('workercreated', x);
}), }),
page.goto(server.PREFIX + '/worker/worker.html'), page.goto(server.PREFIX + '/worker/worker.html'),
@ -52,7 +52,7 @@ describeFailsFirefox('Workers', function () {
it('should emit created and destroyed events', async () => { it('should emit created and destroyed events', async () => {
const {page} = getTestState(); const {page} = getTestState();
const workerCreatedPromise = new Promise<WebWorker>((x) => { const workerCreatedPromise = new Promise<WebWorker>(x => {
return page.once('workercreated', x); return page.once('workercreated', x);
}); });
const workerObj = await page.evaluateHandle(() => { const workerObj = await page.evaluateHandle(() => {
@ -62,14 +62,14 @@ describeFailsFirefox('Workers', function () {
const workerThisObj = await worker.evaluateHandle(() => { const workerThisObj = await worker.evaluateHandle(() => {
return this; return this;
}); });
const workerDestroyedPromise = new Promise((x) => { const workerDestroyedPromise = new Promise(x => {
return page.once('workerdestroyed', x); return page.once('workerdestroyed', x);
}); });
await page.evaluate((workerObj: Worker) => { await page.evaluate((workerObj: Worker) => {
return workerObj.terminate(); return workerObj.terminate();
}, workerObj); }, workerObj);
expect(await workerDestroyedPromise).toBe(worker); expect(await workerDestroyedPromise).toBe(worker);
const error = await workerThisObj.getProperty('self').catch((error) => { const error = await workerThisObj.getProperty('self').catch(error => {
return error; return error;
}); });
expect(error.message).toContain('Most likely the worker has been closed.'); expect(error.message).toContain('Most likely the worker has been closed.');
@ -93,7 +93,7 @@ describeFailsFirefox('Workers', function () {
it('should have JSHandles for console logs', async () => { it('should have JSHandles for console logs', async () => {
const {page} = getTestState(); const {page} = getTestState();
const logPromise = new Promise<ConsoleMessage>((x) => { const logPromise = new Promise<ConsoleMessage>(x => {
return page.on('console', x); return page.on('console', x);
}); });
await page.evaluate(() => { await page.evaluate(() => {
@ -109,7 +109,7 @@ describeFailsFirefox('Workers', function () {
it('should have an execution context', async () => { it('should have an execution context', async () => {
const {page} = getTestState(); const {page} = getTestState();
const workerCreatedPromise = new Promise<WebWorker>((x) => { const workerCreatedPromise = new Promise<WebWorker>(x => {
return page.once('workercreated', x); return page.once('workercreated', x);
}); });
await page.evaluate(() => { await page.evaluate(() => {
@ -121,7 +121,7 @@ describeFailsFirefox('Workers', function () {
it('should report errors', async () => { it('should report errors', async () => {
const {page} = getTestState(); const {page} = getTestState();
const errorPromise = new Promise<Error>((x) => { const errorPromise = new Promise<Error>(x => {
return page.on('pageerror', x); return page.on('pageerror', x);
}); });
await page.evaluate(() => { await page.evaluate(() => {

View File

@ -22,7 +22,7 @@ const { promisify } = require('util');
const exec = promisify(child_process.exec); const exec = promisify(child_process.exec);
const fsAccess = promisify(fs.access); const fsAccess = promisify(fs.access);
const fileExists = async (filePath) => { const fileExists = async filePath => {
return fsAccess(filePath) return fsAccess(filePath)
.then(() => { .then(() => {
return true; return true;
@ -45,7 +45,7 @@ const fileExists = async (filePath) => {
* place. * place.
*/ */
async function compileTypeScript() { async function compileTypeScript() {
return exec('npm run build:tsc').catch((error) => { return exec('npm run build:tsc').catch(error => {
console.error('Error running TypeScript', error); console.error('Error running TypeScript', error);
process.exit(1); process.exit(1);
}); });

View File

@ -168,10 +168,10 @@ function runScript(scriptPath, revisionInfo) {
}, },
}); });
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
child.on('error', (err) => { child.on('error', err => {
return reject(err); return reject(err);
}); });
child.on('exit', (code) => { child.on('exit', code => {
return resolve(code); return resolve(code);
}); });
}); });
@ -189,10 +189,10 @@ function runUnitTest(pattern, revisionInfo) {
}, },
}); });
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
child.on('error', (err) => { child.on('error', err => {
return reject(err); return reject(err);
}); });
child.on('exit', (code) => { child.on('exit', code => {
return resolve(code); return resolve(code);
}); });
}); });
@ -282,14 +282,14 @@ function fetchJSON(url) {
const req = agent.request(options, function (res) { const req = agent.request(options, function (res) {
let result = ''; let result = '';
res.setEncoding('utf8'); res.setEncoding('utf8');
res.on('data', (chunk) => { res.on('data', chunk => {
return (result += chunk); return (result += chunk);
}); });
res.on('end', () => { res.on('end', () => {
return resolve(JSON.parse(result)); return resolve(JSON.parse(result));
}); });
}); });
req.on('error', (err) => { req.on('error', err => {
return reject(err); return reject(err);
}); });
req.end(); req.end();

View File

@ -155,7 +155,7 @@ async function checkOmahaProxyAvailability() {
'https://storage.googleapis.com/chromium-browser-snapshots/Win_x64/LAST_CHANGE' 'https://storage.googleapis.com/chromium-browser-snapshots/Win_x64/LAST_CHANGE'
), ),
]) ])
).map((s) => { ).map(s => {
return parseInt(s, 10); return parseInt(s, 10);
}); });
const from = Math.max(...latestRevisions); const from = Math.max(...latestRevisions);
@ -185,7 +185,7 @@ async function printLatestRevisionForPlatform(platform) {
'https://storage.googleapis.com/chromium-browser-snapshots/Win_x64/LAST_CHANGE' 'https://storage.googleapis.com/chromium-browser-snapshots/Win_x64/LAST_CHANGE'
), ),
]) ])
).map((s) => { ).map(s => {
return parseInt(s, 10); return parseInt(s, 10);
}); });
const from = Math.max(...latestRevisions); const from = Math.max(...latestRevisions);
@ -246,7 +246,7 @@ async function checkRangeAvailability({
table.drawRow([''].concat(platforms)); table.drawRow([''].concat(platforms));
} }
const fetchers = platforms.map((platform) => { const fetchers = platforms.map(platform => {
return new BrowserFetcher('', {platform}); return new BrowserFetcher('', {platform});
}); });
@ -257,11 +257,11 @@ async function checkRangeAvailability({
revision !== revisionToStop; revision !== revisionToStop;
revision += inc revision += inc
) { ) {
const promises = fetchers.map((fetcher) => { const promises = fetchers.map(fetcher => {
return fetcher.canDownload(revision); return fetcher.canDownload(revision);
}); });
const availability = await Promise.all(promises); const availability = await Promise.all(promises);
const allAvailable = availability.every((e) => { const allAvailable = availability.every(e => {
return !!e; return !!e;
}); });
if (table) { if (table) {
@ -292,11 +292,11 @@ async function checkRangeAvailability({
*/ */
function fetch(url) { function fetch(url) {
let resolve; let resolve;
const promise = new Promise((x) => { const promise = new Promise(x => {
return (resolve = x); return (resolve = x);
}); });
https https
.get(url, (response) => { .get(url, response => {
if (response.statusCode !== 200) { if (response.statusCode !== 200) {
resolve(null); resolve(null);
return; return;

View File

@ -86,10 +86,10 @@ async function main(url) {
return; return;
} }
const devicePayloads = json.extensions const devicePayloads = json.extensions
.filter((extension) => { .filter(extension => {
return extension.type === 'emulated-device'; return extension.type === 'emulated-device';
}) })
.map((extension) => { .map(extension => {
return extension.device; return extension.device;
}); });
let devices = []; let devices = [];
@ -116,7 +116,7 @@ async function main(url) {
} }
} }
} }
devices = devices.filter((device) => { devices = devices.filter(device => {
return device.viewport.isMobile; return device.viewport.isMobile;
}); });
devices.sort((a, b) => { devices.sort((a, b) => {
@ -287,10 +287,10 @@ function httpGET(url) {
const driver = url.startsWith('https://') const driver = url.startsWith('https://')
? require('https') ? require('https')
: require('http'); : require('http');
const request = driver.get(url, (response) => { const request = driver.get(url, response => {
let data = ''; let data = '';
response.setEncoding('utf8'); response.setEncoding('utf8');
response.on('data', (chunk) => { response.on('data', chunk => {
return (data += chunk); return (data += chunk);
}); });
response.on('end', () => { response.on('end', () => {

View File

@ -67,7 +67,7 @@ export class TestServer {
static async create(dirPath: string, port: number): Promise<TestServer> { static async create(dirPath: string, port: number): Promise<TestServer> {
const server = new TestServer(dirPath, port); const server = new TestServer(dirPath, port);
await new Promise((x) => { await new Promise(x => {
return server.#server.once('listening', x); return server.#server.once('listening', x);
}); });
return server; return server;
@ -79,7 +79,7 @@ export class TestServer {
cert: readFileSync(join(__dirname, '..', 'cert.pem')), cert: readFileSync(join(__dirname, '..', 'cert.pem')),
passphrase: 'aaaa', passphrase: 'aaaa',
}); });
await new Promise((x) => { await new Promise(x => {
return server.#server.once('listening', x); return server.#server.once('listening', x);
}); });
return server; return server;
@ -103,7 +103,7 @@ export class TestServer {
this.#connections.add(connection); this.#connections.add(connection);
// ECONNRESET is a legit error given // ECONNRESET is a legit error given
// that tab closing simply kills process. // that tab closing simply kills process.
connection.on('error', (error) => { connection.on('error', error => {
if ((error as NodeJS.ErrnoException).code !== 'ECONNRESET') { if ((error as NodeJS.ErrnoException).code !== 'ECONNRESET') {
throw error; throw error;
} }
@ -135,7 +135,7 @@ export class TestServer {
socket.destroy(); socket.destroy();
} }
this.#connections.clear(); this.#connections.clear();
await new Promise((x) => { await new Promise(x => {
return this.#server.close(x); return this.#server.close(x);
}); });
} }
@ -192,7 +192,7 @@ export class TestServer {
throw error; throw error;
} }
}); });
request.postBody = new Promise((resolve) => { request.postBody = new Promise(resolve => {
let body = ''; let body = '';
request.on('data', (chunk: string) => { request.on('data', (chunk: string) => {
return (body += chunk); return (body += chunk);