chore(test): run eslint on tests (#3638)

This commit is contained in:
Joel Einbinder 2020-08-28 04:20:29 -07:00 committed by GitHub
parent 6ffdd4dfa1
commit e2057fb8bb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
122 changed files with 1334 additions and 1345 deletions

View File

@ -11,7 +11,7 @@ src/server/webkit/protocol.ts
/electron-types.d.ts
utils/generate_types/overrides.d.ts
utils/generate_types/test/test.ts
/test/
node_modules/
browser_patches/*/checkout/
packages/**/*.d.ts
output/

View File

@ -24,14 +24,14 @@ it('clicking on links which do not commit navigation', async({page, server, http
it('calling window.stop async', async ({page, server}) => {
server.setRoute('/empty.html', async (req, res) => {});
await page.evaluate((url) => {
await page.evaluate(url => {
window.location.href = url;
setTimeout(() => window.stop(), 100);
}, server.EMPTY_PAGE);
});
it('calling window.stop sync', async ({page, server}) => {
await page.evaluate((url) => {
await page.evaluate(url => {
window.location.href = url;
window.stop();
}, server.EMPTY_PAGE);

View File

@ -330,14 +330,14 @@ it('should(not) block third party cookies', async({context, page, server}) => {
if (allowsThirdParty) {
expect(cookies).toEqual([
{
"domain": "127.0.0.1",
"expires": -1,
"httpOnly": false,
"name": "username",
"path": "/",
"sameSite": "None",
"secure": false,
"value": "John Doe"
'domain': '127.0.0.1',
'expires': -1,
'httpOnly': false,
'name': 'username',
'path': '/',
'sameSite': 'None',
'secure': false,
'value': 'John Doe'
}
]);
} else {

View File

@ -126,7 +126,7 @@ it('close() should abort waitForEvent', async({ browser }) => {
const context = await browser.newContext();
const promise = context.waitForEvent('page').catch(e => e);
await context.close();
let error = await promise;
const error = await promise;
expect(error.message).toContain('Context closed');
});

View File

@ -67,7 +67,7 @@ it('should return resource body', async({browser, server}) => {
const page = await context.newPage();
const response = await page.goto(server.PREFIX + '/playground.html');
expect(response.status()).toBe(200);
expect(await page.title()).toBe("Playground");
expect((await response.body()).toString()).toContain("Playground");
expect(await page.title()).toBe('Playground');
expect((await response.body()).toString()).toContain('Playground');
await context.close();
});

View File

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { options } from './playwright.fixtures';
import './playwright.fixtures';
it('should affect accept-language header', async ({browser, server}) => {
const context = await browser.newContext({ locale: 'fr-CH' });

View File

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { options } from './playwright.fixtures';
import './playwright.fixtures';
it('should work', async ({ browser }) => {
const func = () => new Date(1479579154987).toString();
@ -48,7 +48,7 @@ it('should throw for invalid timezone IDs when creating pages', async({browser})
for (const timezoneId of ['Foo/Bar', 'Baz/Qux']) {
let error = null;
const context = await browser.newContext({ timezoneId });
const page = await context.newPage().catch(e => error = e);
await context.newPage().catch(e => error = e);
expect(error.message).toContain(`Invalid timezone ID: ${timezoneId}`);
await context.close();
}

View File

@ -82,7 +82,7 @@ it.skip(options.WIRE).slow()('disconnected event should be emitted when browser
});
it.skip(options.WIRE).slow()('should handle exceptions during connect', async ({browserType, remoteServer}) => {
const __testHookBeforeCreateBrowser = () => { throw new Error('Dummy') };
const __testHookBeforeCreateBrowser = () => { throw new Error('Dummy'); };
const error = await browserType.connect({ wsEndpoint: remoteServer.wsEndpoint(), __testHookBeforeCreateBrowser } as any).catch(e => e);
expect(error.message).toContain('Dummy');
});

View File

@ -23,7 +23,7 @@ it.fail(options.WEBKIT && WIN)('Web Assembly should work', async function({page,
});
it('WebSocket should work', async ({page, server}) => {
const value = await page.evaluate((port) => {
const value = await page.evaluate(port => {
let cb;
const result = new Promise(f => cb = f);
const ws = new WebSocket('ws://localhost:' + port + '/ws');

View File

@ -75,14 +75,14 @@ it.skip(!options.CHROMIUM)('should work with complicated usecases', async functi
expect(coverage).toEqual(
[
{
"ranges": [
'ranges': [
{
"start": 149,
"end": 297
'start': 149,
'end': 297
},
{
"start": 327,
"end": 433
'start': 327,
'end': 433
}
]
}

View File

@ -62,7 +62,7 @@ it.skip(!options.CHROMIUM)('should return background pages', async({browserType,
};
const context = await browserType.launchPersistentContext(userDataDir, extensionOptions) as ChromiumBrowserContext;
const backgroundPages = context.backgroundPages();
let backgroundPage = backgroundPages.length
const backgroundPage = backgroundPages.length
? backgroundPages[0]
: await context.waitForEvent('backgroundpage');
expect(backgroundPage).toBeTruthy();

View File

@ -117,7 +117,7 @@ it.skip(!options.CHROMIUM)('should emulate offline', async({browser, page, conte
});
it.skip(!options.CHROMIUM)('should support context options', async ({browser, server, playwright}) => {
const iPhone = playwright.devices['iPhone 6']
const iPhone = playwright.devices['iPhone 6'];
const context = await browser.newContext({ ...iPhone, timezoneId: 'America/Jamaica', locale: 'fr-CH', userAgent: 'UA' });
const page = await context.newPage();

View File

@ -14,7 +14,7 @@
* limitations under the License.
*/
import { options } from '../playwright.fixtures';
import type { ChromiumBrowserContext, ChromiumBrowser } from "../../types/types";
import type { ChromiumBrowserContext, ChromiumBrowser } from '../../types/types';
it.skip(!options.CHROMIUM)('should work', async function({page}) {
const client = await (page.context() as ChromiumBrowserContext).newCDPSession(page);

View File

@ -22,7 +22,7 @@ it.skip(options.WIRE)('should fail when element jumps during hit testing', async
let clicked = false;
const handle = await page.$('button');
const __testHookBeforeHitTarget = () => page.evaluate(() => {
const margin = parseInt(document.querySelector('button').style.marginLeft || '0') + 100;
const margin = parseInt(document.querySelector('button').style.marginLeft || '0', 10) + 100;
document.querySelector('button').style.marginLeft = margin + 'px';
});
const promise = handle.click({ timeout: 5000, __testHookBeforeHitTarget } as any).then(() => clicked = true).catch(e => e);

View File

@ -20,7 +20,7 @@ import fs from 'fs';
import utils from './utils';
it('context.cookies() should work', async ({server, launchPersistent}) => {
const {page, context} = await launchPersistent();
const {page} = await launchPersistent();
await page.goto(server.EMPTY_PAGE);
const documentCookie = await page.evaluate(() => {
document.cookie = 'username=John Doe';
@ -40,7 +40,7 @@ it('context.cookies() should work', async ({server, launchPersistent}) => {
});
it('context.addCookies() should work', async ({server, launchPersistent}) => {
const {page, context} = await launchPersistent();
const {page} = await launchPersistent();
await page.goto(server.EMPTY_PAGE);
await page.context().addCookies([{
url: server.EMPTY_PAGE,
@ -61,7 +61,7 @@ it('context.addCookies() should work', async ({server, launchPersistent}) => {
});
it('context.clearCookies() should work', async ({server, launchPersistent}) => {
const {page, context} = await launchPersistent();
const {page} = await launchPersistent();
await page.goto(server.EMPTY_PAGE);
await page.context().addCookies([{
url: server.EMPTY_PAGE,
@ -102,14 +102,14 @@ it('should(not) block third party cookies', async ({server, launchPersistent}) =
if (allowsThirdParty) {
expect(cookies).toEqual([
{
"domain": "127.0.0.1",
"expires": -1,
"httpOnly": false,
"name": "username",
"path": "/",
"sameSite": "None",
"secure": false,
"value": "John Doe"
'domain': '127.0.0.1',
'expires': -1,
'httpOnly': false,
'name': 'username',
'path': '/',
'sameSite': 'None',
'secure': false,
'value': 'John Doe'
}
]);
} else {
@ -125,12 +125,12 @@ it('should support viewport option', async ({launchPersistent}) => {
});
it('should support deviceScaleFactor option', async ({launchPersistent}) => {
const {page, context} = await launchPersistent({deviceScaleFactor: 3});
const {page} = await launchPersistent({deviceScaleFactor: 3});
expect(await page.evaluate('window.devicePixelRatio')).toBe(3);
});
it('should support userAgent option', async ({server, launchPersistent}) => {
const {page, context} = await launchPersistent({userAgent: 'foobar'});
const {page} = await launchPersistent({userAgent: 'foobar'});
expect(await page.evaluate(() => navigator.userAgent)).toBe('foobar');
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
@ -140,14 +140,14 @@ it('should support userAgent option', async ({server, launchPersistent}) => {
});
it('should support bypassCSP option', async ({server, launchPersistent}) => {
const {page, context} = await launchPersistent({bypassCSP: true});
const {page} = await launchPersistent({bypassCSP: true});
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window["__injected"] = 42;'});
expect(await page.evaluate('__injected')).toBe(42);
});
it('should support javascriptEnabled option', async ({launchPersistent}) => {
const {page, context} = await launchPersistent({javaScriptEnabled: false});
const {page} = await launchPersistent({javaScriptEnabled: false});
await page.goto('data:text/html, <script>var something = "forbidden"</script>');
let error = null;
await page.evaluate('something').catch(e => error = e);
@ -158,21 +158,21 @@ it('should support javascriptEnabled option', async ({launchPersistent}) => {
});
it('should support httpCredentials option', async ({server, launchPersistent}) => {
const {page, context} = await launchPersistent({httpCredentials: { username: 'user', password: 'pass' }});
const {page} = await launchPersistent({httpCredentials: { username: 'user', password: 'pass' }});
server.setAuth('/playground.html', 'user', 'pass');
const response = await page.goto(server.PREFIX + '/playground.html');
expect(response.status()).toBe(200);
});
it('should support offline option', async ({server, launchPersistent}) => {
const {page, context} = await launchPersistent({offline: true});
const {page} = await launchPersistent({offline: true});
const error = await page.goto(server.EMPTY_PAGE).catch(e => e);
expect(error).toBeTruthy();
});
it.skip(true)('should support acceptDownloads option', async ({server, launchPersistent}) => {
// TODO: unskip once we support downloads in persistent context.
const {page, context} = await launchPersistent({acceptDownloads: true});
const {page} = await launchPersistent({acceptDownloads: true});
server.setRoute('/download', (req, res) => {
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', 'attachment');

View File

@ -21,36 +21,36 @@ import utils from './utils';
const { removeUserDataDir, makeUserDataDir } = utils;
it('should support hasTouch option', async ({server, launchPersistent}) => {
const {page, context} = await launchPersistent({hasTouch: true});
const {page} = await launchPersistent({hasTouch: true});
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => 'ontouchstart' in window)).toBe(true);
});
it.skip(options.FIREFOX)('should work in persistent context', async ({server, launchPersistent}) => {
// Firefox does not support mobile.
const {page, context} = await launchPersistent({viewport: {width: 320, height: 480}, isMobile: true});
const {page} = await launchPersistent({viewport: {width: 320, height: 480}, isMobile: true});
await page.goto(server.PREFIX + '/empty.html');
expect(await page.evaluate(() => window.innerWidth)).toBe(980);
});
it('should support colorScheme option', async ({launchPersistent}) => {
const {page, context} = await launchPersistent({colorScheme: 'dark'});
const {page} = await launchPersistent({colorScheme: 'dark'});
expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches)).toBe(false);
expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches)).toBe(true);
});
it('should support timezoneId option', async ({launchPersistent}) => {
const {page, context} = await launchPersistent({timezoneId: 'America/Jamaica'});
const {page} = await launchPersistent({timezoneId: 'America/Jamaica'});
expect(await page.evaluate(() => new Date(1479579154987).toString())).toBe('Sat Nov 19 2016 13:12:34 GMT-0500 (Eastern Standard Time)');
});
it('should support locale option', async ({launchPersistent}) => {
const {page, context} = await launchPersistent({locale: 'fr-CH'});
const {page} = await launchPersistent({locale: 'fr-CH'});
expect(await page.evaluate(() => navigator.language)).toBe('fr-CH');
});
it('should support geolocation and permissions options', async ({server, launchPersistent}) => {
const {page, context} = await launchPersistent({geolocation: {longitude: 10, latitude: 10}, permissions: ['geolocation']});
const {page} = await launchPersistent({geolocation: {longitude: 10, latitude: 10}, permissions: ['geolocation']});
await page.goto(server.EMPTY_PAGE);
const geolocation = await page.evaluate(() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});
@ -59,7 +59,7 @@ it('should support geolocation and permissions options', async ({server, launchP
});
it('should support ignoreHTTPSErrors option', async ({httpsServer, launchPersistent}) => {
const {page, context} = await launchPersistent({ignoreHTTPSErrors: true});
const {page} = await launchPersistent({ignoreHTTPSErrors: true});
let error = null;
const response = await page.goto(httpsServer.EMPTY_PAGE).catch(e => error = e);
expect(error).toBe(null);
@ -67,7 +67,7 @@ it('should support ignoreHTTPSErrors option', async ({httpsServer, launchPersist
});
it('should support extraHTTPHeaders option', async ({server, launchPersistent}) => {
const {page, context} = await launchPersistent({extraHTTPHeaders: { foo: 'bar' }});
const {page} = await launchPersistent({extraHTTPHeaders: { foo: 'bar' }});
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
page.goto(server.EMPTY_PAGE),
@ -76,7 +76,7 @@ it('should support extraHTTPHeaders option', async ({server, launchPersistent})
});
it.flaky(options.CHROMIUM)('should accept userDataDir', async ({launchPersistent, tmpDir}) => {
const {page, context} = await launchPersistent();
const {context} = await launchPersistent();
// Note: we need an open page to make sure its functional.
expect(fs.readdirSync(tmpDir).length).toBeGreaterThan(0);
await context.close();
@ -142,7 +142,7 @@ it.slow()('should restore cookies from userDataDir', async({browserType, default
});
it('should have default URL when launching browser', async ({launchPersistent}) => {
const {page, context} = await launchPersistent();
const {context} = await launchPersistent();
const urls = context.pages().map(page => page.url());
expect(urls).toEqual(['about:blank']);
});
@ -183,7 +183,7 @@ it.skip(options.WIRE)('should handle exception', async({browserType, defaultBrow
});
it('should fire close event for a persistent context', async ({launchPersistent}) => {
const {page, context} = await launchPersistent();
const {context} = await launchPersistent();
let closed = false;
context.on('close', () => closed = true);
await context.close();
@ -191,7 +191,7 @@ it('should fire close event for a persistent context', async({launchPersistent})
});
it.skip(!options.CHROMIUM)('coverage should work', async ({server, launchPersistent}) => {
const {page, context} = await launchPersistent();
const {page} = await launchPersistent();
await page.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/simple.html', { waitUntil: 'load' });
const coverage = await page.coverage.stopJSCoverage();
@ -201,6 +201,6 @@ it.skip(!options.CHROMIUM)('coverage should work', async ({server, launchPersist
});
it.skip(options.CHROMIUM)('coverage should be missing', async ({launchPersistent}) => {
const {page, context} = await launchPersistent();
const {page} = await launchPersistent();
expect(page.coverage).toBe(null);
});

View File

@ -110,7 +110,7 @@ it('should be atomic', async({playwright, page}) => {
query(root, selector) {
const result = root.querySelector(selector);
if (result)
Promise.resolve().then(() => result.onclick = "");
Promise.resolve().then(() => result.onclick = '');
return result;
},
queryAll(root: HTMLElement, selector: string) {

View File

@ -69,7 +69,7 @@ it('should save to user-specified path', async({tmpDir, browser, server}) => {
page.waitForEvent('download'),
page.click('a')
]);
const userPath = path.join(tmpDir, "download.txt");
const userPath = path.join(tmpDir, 'download.txt');
await download.saveAs(userPath);
expect(fs.existsSync(userPath)).toBeTruthy();
expect(fs.readFileSync(userPath).toString()).toBe('Hello world');
@ -83,7 +83,7 @@ it('should save to user-specified path without updating original path', async({t
page.waitForEvent('download'),
page.click('a')
]);
const userPath = path.join(tmpDir, "download.txt");
const userPath = path.join(tmpDir, 'download.txt');
await download.saveAs(userPath);
expect(fs.existsSync(userPath)).toBeTruthy();
expect(fs.readFileSync(userPath).toString()).toBe('Hello world');
@ -101,12 +101,12 @@ it('should save to two different paths with multiple saveAs calls', async({tmpDi
page.waitForEvent('download'),
page.click('a')
]);
const userPath = path.join(tmpDir, "download.txt");
const userPath = path.join(tmpDir, 'download.txt');
await download.saveAs(userPath);
expect(fs.existsSync(userPath)).toBeTruthy();
expect(fs.readFileSync(userPath).toString()).toBe('Hello world');
const anotherUserPath = path.join(tmpDir, "download (2).txt");
const anotherUserPath = path.join(tmpDir, 'download (2).txt');
await download.saveAs(anotherUserPath);
expect(fs.existsSync(anotherUserPath)).toBeTruthy();
expect(fs.readFileSync(anotherUserPath).toString()).toBe('Hello world');
@ -120,7 +120,7 @@ it('should save to overwritten filepath', async({tmpDir, browser, server}) => {
page.waitForEvent('download'),
page.click('a')
]);
const userPath = path.join(tmpDir, "download.txt");
const userPath = path.join(tmpDir, 'download.txt');
await download.saveAs(userPath);
expect((await util.promisify(fs.readdir)(tmpDir)).length).toBe(1);
await download.saveAs(userPath);
@ -137,8 +137,8 @@ it('should create subdirectories when saving to non-existent user-specified path
page.waitForEvent('download'),
page.click('a')
]);
const nestedPath = path.join(tmpDir, "these", "are", "directories", "download.txt");
await download.saveAs(nestedPath)
const nestedPath = path.join(tmpDir, 'these', 'are', 'directories', 'download.txt');
await download.saveAs(nestedPath);
expect(fs.existsSync(nestedPath)).toBeTruthy();
expect(fs.readFileSync(nestedPath).toString()).toBe('Hello world');
await page.close();
@ -152,7 +152,7 @@ it.skip(options.WIRE)('should save when connected remotely', async({tmpDir, serv
page.waitForEvent('download'),
page.click('a')
]);
const nestedPath = path.join(tmpDir, "these", "are", "directories", "download.txt");
const nestedPath = path.join(tmpDir, 'these', 'are', 'directories', 'download.txt');
await download.saveAs(nestedPath);
expect(fs.existsSync(nestedPath)).toBeTruthy();
expect(fs.readFileSync(nestedPath).toString()).toBe('Hello world');
@ -168,7 +168,7 @@ it('should error when saving with downloads disabled', async({tmpDir, browser, s
page.waitForEvent('download'),
page.click('a')
]);
const userPath = path.join(tmpDir, "download.txt");
const userPath = path.join(tmpDir, 'download.txt');
const { message } = await download.saveAs(userPath).catch(e => e);
expect(message).toContain('Pass { acceptDownloads: true } when you are creating your browser context');
await page.close();
@ -181,7 +181,7 @@ it('should error when saving after deletion', async({tmpDir, browser, server}) =
page.waitForEvent('download'),
page.click('a')
]);
const userPath = path.join(tmpDir, "download.txt");
const userPath = path.join(tmpDir, 'download.txt');
await download.delete();
const { message } = await download.saveAs(userPath).catch(e => e);
expect(message).toContain('Download already deleted. Save before deleting.');
@ -196,7 +196,7 @@ it.skip(options.WIRE)('should error when saving after deletion when connected re
page.waitForEvent('download'),
page.click('a')
]);
const userPath = path.join(tmpDir, "download.txt");
const userPath = path.join(tmpDir, 'download.txt');
await download.delete();
const { message } = await download.saveAs(userPath).catch(e => e);
expect(message).toContain('Download already deleted. Save before deleting.');
@ -226,7 +226,7 @@ it('should report non-navigation downloads', async({browser, server}) => {
it(`should report download path within page.on('download', …) handler for Files`, async ({browser, server}) => {
const page = await browser.newPage({ acceptDownloads: true });
const onDownloadPath = new Promise<string>((res) => {
const onDownloadPath = new Promise<string>(res => {
page.on('download', dl => {
dl.path().then(res);
});
@ -236,10 +236,10 @@ it(`should report download path within page.on('download', …) handler for File
const path = await onDownloadPath;
expect(fs.readFileSync(path).toString()).toBe('Hello world');
await page.close();
})
});
it(`should report download path within page.on('download', …) handler for Blobs`, async ({browser, server}) => {
const page = await browser.newPage({ acceptDownloads: true });
const onDownloadPath = new Promise<string>((res) => {
const onDownloadPath = new Promise<string>(res => {
page.on('download', dl => {
dl.path().then(res);
});
@ -249,7 +249,7 @@ it(`should report download path within page.on('download', …) handler for Blob
const path = await onDownloadPath;
expect(fs.readFileSync(path).toString()).toBe('Hello world');
await page.close();
})
});
it.fixme(options.FIREFOX || options.WEBKIT)('should report alt-click downloads', async ({browser, server}) => {
// Firefox does not download on alt-click by default.
// Our WebKit embedder does not download on alt-click, although Safari does.

View File

@ -70,10 +70,10 @@ it.skip(!options.CHROMIUM)('should create multiple windows', async ({ applicatio
};
const page1 = await createPage(1);
const page2 = await createPage(2);
const page3 = await createPage(3);
await createPage(2);
await createPage(3);
await page1.close();
const page4 = await createPage(4);
await createPage(4);
const titles = [];
for (const window of application.windows())
titles.push(await window.title());
@ -86,7 +86,7 @@ it.skip(!options.CHROMIUM)('should route network', async ({ application }) => {
status: 200,
contentType: 'text/html',
body: '<title>Hello World</title>',
})
});
});
const page = await application.newBrowserWindow({ width: 800, height: 600 });
await page.goto('https://localhost:1000/empty.html');
@ -94,14 +94,13 @@ it.skip(!options.CHROMIUM)('should route network', async ({ application }) => {
});
it.skip(!options.CHROMIUM)('should support init script', async ({ application }) => {
await application.context().addInitScript('window.magic = 42;')
await application.context().addInitScript('window.magic = 42;');
const page = await application.newBrowserWindow({ width: 800, height: 600 });
await page.goto('data:text/html,<script>window.copy = magic</script>');
expect(await page.evaluate(() => window['copy'])).toBe(42);
});
it.skip(!options.CHROMIUM)('should expose function', async ({ application }) => {
const t = Date.now();
await application.context().exposeFunction('add', (a, b) => a + b);
const page = await application.newBrowserWindow({ width: 800, height: 600 });
await page.goto('data:text/html,<script>window["result"] = add(20, 22);</script>');

View File

@ -14,7 +14,7 @@
* limitations under the License.
*/
import { options } from '../playwright.fixtures';
import '../playwright.fixtures';
import { registerFixture } from '../../test-runner';
import type {ElectronApplication, ElectronLauncher, ElectronPage} from '../../electron-types';
import path from 'path';
@ -29,7 +29,7 @@ declare global {
}
declare module '../../index' {
const electron: ElectronLauncher
const electron: ElectronLauncher;
}
registerFixture('application', async ({playwright}, test) => {

View File

@ -78,7 +78,7 @@ it('should work for adopted elements', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window["__popup"] = window.open(url), server.EMPTY_PAGE),
page.evaluate(url => window['__popup'] = window.open(url), server.EMPTY_PAGE),
]);
const divHandle = await page.evaluateHandle(() => {
const div = document.createElement('div');
@ -89,7 +89,7 @@ it('should work for adopted elements', async ({ page, server }) => {
await popup.waitForLoadState('domcontentloaded');
await page.evaluate(() => {
const div = document.querySelector('div');
window["__popup"].document.body.appendChild(div);
window['__popup'].document.body.appendChild(div);
});
expect(await divHandle.ownerFrame()).toBe(popup.mainFrame());
});

View File

@ -38,7 +38,7 @@ it('should work for adopted elements', async({page,server}) => {
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window["__popup"] = window.open(url), server.EMPTY_PAGE),
page.evaluate(url => window['__popup'] = window.open(url), server.EMPTY_PAGE),
]);
const divHandle = await page.evaluateHandle(() => {
const div = document.createElement('div');
@ -54,7 +54,7 @@ it('should work for adopted elements', async({page,server}) => {
await popup.waitForLoadState('domcontentloaded');
await page.evaluate(() => {
const div = document.querySelector('div');
window["__popup"].document.body.appendChild(div);
window['__popup'].document.body.appendChild(div);
});
expect(await divHandle.$('span')).toBeTruthy();
expect(await divHandle.$eval('span', e => e.textContent)).toBe('hello');

View File

@ -288,7 +288,7 @@ it.skip(ffheadful || options.WIRE)('should restore viewport after page screensho
const context = await browser.newContext({ viewport: { width: 350, height: 360 } });
const page = await context.newPage();
await page.goto(server.PREFIX + '/grid.html');
const __testHookBeforeScreenshot = () => { throw new Error('oh my') };
const __testHookBeforeScreenshot = () => { throw new Error('oh my'); };
const error = await page.screenshot({ fullPage: true, __testHookBeforeScreenshot } as any).catch(e => e);
expect(error.message).toContain('oh my');
await utils.verifyViewport(page, 350, 360);
@ -344,7 +344,7 @@ it.skip(ffheadful || options.WIRE)('should restore viewport after element screen
const page = await context.newPage();
await page.setContent(`<div style="width:600px;height:600px;"></div>`);
const elementHandle = await page.$('div');
const __testHookBeforeScreenshot = () => { throw new Error('oh my') };
const __testHookBeforeScreenshot = () => { throw new Error('oh my'); };
const error = await elementHandle.screenshot({ __testHookBeforeScreenshot } as any).catch(e => e);
expect(error.message).toContain('oh my');
await utils.verifyViewport(page, 350, 360);

View File

@ -16,7 +16,6 @@
*/
import './playwright.fixtures';
import { options } from './playwright.fixtures';
async function giveItAChanceToResolve(page) {
for (let i = 0; i < 5; i++)

View File

@ -131,7 +131,7 @@ it('should change focused iframe', async({page, server}) => {
function logger() {
self['_events'] = [];
const element = document.querySelector('input');
element.onfocus = element.onblur = (e) => self['_events'].push(e.type);
element.onfocus = element.onblur = e => self['_events'].push(e.type);
}
await Promise.all([
frame1.evaluate(logger),

View File

@ -52,9 +52,9 @@ it('should traverse focus', async function({page}) {
await page.$eval('#i2', i2 => (i2 as HTMLInputElement).addEventListener('focus', window['focusEvent']));
await page.focus('#i1');
await page.keyboard.type("First");
await page.keyboard.press("Tab");
await page.keyboard.type("Last");
await page.keyboard.type('First');
await page.keyboard.press('Tab');
await page.keyboard.type('Last');
expect(focused).toBe(true);
expect(await page.$eval('#i1', e => (e as HTMLInputElement).value)).toBe('First');

View File

@ -22,10 +22,10 @@ it('should have different execution contexts', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
expect(page.frames().length).toBe(2);
await page.frames()[0].evaluate(() => window["FOO"] = 'foo');
await page.frames()[1].evaluate(() => window["FOO"] = 'bar');
expect(await page.frames()[0].evaluate(() => window["FOO"])).toBe('foo');
expect(await page.frames()[1].evaluate(() => window["FOO"])).toBe('bar');
await page.frames()[0].evaluate(() => window['FOO'] = 'foo');
await page.frames()[1].evaluate(() => window['FOO'] = 'bar');
expect(await page.frames()[0].evaluate(() => window['FOO'])).toBe('foo');
expect(await page.frames()[1].evaluate(() => window['FOO'])).toBe('bar');
});
it('should have correct execution contexts', async ({ page, server }) => {
@ -115,8 +115,8 @@ it('should be isolated between frames', async({page, server}) => {
expect(frame1 !== frame2).toBeTruthy();
await Promise.all([
frame1.evaluate(() => window["a"] = 1),
frame2.evaluate(() => window["a"] = 2)
frame1.evaluate(() => window['a'] = 1),
frame2.evaluate(() => window['a'] = 2)
]);
const [a1, a2] = await Promise.all([
frame1.evaluate(() => window['a']),

View File

@ -22,7 +22,7 @@ import utils from './utils';
it('should work', async ({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const frame1 = await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame2 = await utils.attachFrame(page, 'frame2', server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame2', server.EMPTY_PAGE);
const frame3 = await utils.attachFrame(page, 'frame3', server.EMPTY_PAGE);
const frame1handle1 = await page.$('#frame1');
const frame1handle2 = await frame1.frameElement();

View File

@ -185,7 +185,7 @@ it.fixme(options.FIREFOX)('should refuse to display x-frame-options:deny iframe'
});
});
await page.setContent(`<iframe src="${server.CROSS_PROCESS_PREFIX}/x-frame-options-deny.html"></iframe>`);
expect(await refusalText).toMatch(/Refused to display 'http.*\/x-frame-options-deny\.html' in a frame because it set 'X-Frame-Options' to 'deny'./i)
expect(await refusalText).toMatch(/Refused to display 'http.*\/x-frame-options-deny\.html' in a frame because it set 'X-Frame-Options' to 'deny'./i);
});
it('should return frame.page()', async ({page, server}) => {

View File

@ -148,7 +148,7 @@ it('should use context options for popup', async({page, context, server}) => {
await context.setGeolocation({ longitude: 10, latitude: 10 });
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window["_popup"] = window.open(url), server.PREFIX + '/geolocation.html'),
page.evaluate(url => window['_popup'] = window.open(url), server.PREFIX + '/geolocation.html'),
]);
await popup.waitForLoadState();
const geolocation = await popup.evaluate(() => window['geolocationPromise']);

View File

@ -60,12 +60,12 @@ it('should not crash when creating second context', async ({browserType, default
const browser = await browserType.launch({...defaultBrowserOptions, headless: false });
{
const browserContext = await browser.newContext();
const page = await browserContext.newPage();
await browserContext.newPage();
await browserContext.close();
}
{
const browserContext = await browser.newContext();
const page = await browserContext.newPage();
await browserContext.newPage();
await browserContext.close();
}
await browser.close();
@ -112,14 +112,14 @@ it('should(not) block third party cookies', async({browserType, defaultBrowserOp
if (allowsThirdParty) {
expect(cookies).toEqual([
{
"domain": "127.0.0.1",
"expires": -1,
"httpOnly": false,
"name": "username",
"path": "/",
"sameSite": "None",
"secure": false,
"value": "John Doe"
'domain': '127.0.0.1',
'expires': -1,
'httpOnly': false,
'name': 'username',
'path': '/',
'sameSite': 'None',
'secure': false,
'value': 'John Doe'
}
]);
} else {
@ -150,9 +150,9 @@ it.fixme(options.WEBKIT)('should not override viewport size when passed null', a
it('Page.bringToFront should work', async ({browserType, defaultBrowserOptions}) => {
const browser = await browserType.launch({...defaultBrowserOptions, headless: false });
const page1 = await browser.newPage();
await page1.setContent('Page1')
await page1.setContent('Page1');
const page2 = await browser.newPage();
await page2.setContent('Page2')
await page2.setContent('Page2');
await page1.bringToFront();
expect(await page1.evaluate('document.visibilityState')).toBe('visible');

View File

@ -46,10 +46,10 @@ it('should work with ignoreHTTPSErrors', async({browser, httpsServer}) => {
it('should intercept after a service worker', async ({browser, page, server, context}) => {
await page.goto(server.PREFIX + '/serviceworkers/fetchdummy/sw.html');
await page.evaluate(() => window["activationPromise"]);
await page.evaluate(() => window['activationPromise']);
// Sanity check.
const swResponse = await page.evaluate(() => window["fetchDummy"]('foo'));
const swResponse = await page.evaluate(() => window['fetchDummy']('foo'));
expect(swResponse).toBe('responseFromServiceWorker:foo');
await page.route('**/foo', route => {
@ -63,11 +63,11 @@ it('should intercept after a service worker', async({browser, page, server, cont
});
// Page route is applied after service worker fetch event.
const swResponse2 = await page.evaluate(() => window["fetchDummy"]('foo'));
const swResponse2 = await page.evaluate(() => window['fetchDummy']('foo'));
expect(swResponse2).toBe('responseFromServiceWorker:foo');
// Page route is not applied to service worker initiated fetch.
const nonInterceptedResponse = await page.evaluate(() => window["fetchDummy"]('passthrough'));
const nonInterceptedResponse = await page.evaluate(() => window['fetchDummy']('passthrough'));
expect(nonInterceptedResponse).toBe('FAILURE: Not Found');
});

View File

@ -30,7 +30,7 @@ function dimensions() {
it.flaky(options.FIREFOX && WIN)('should click the document', async ({page, server}) => {
// Occasionally times out on options.FIREFOX on Windows: https://github.com/microsoft/playwright/pull/1911/checks?check_run_id=607149016
await page.evaluate(() => {
window["clickPromise"] = new Promise(resolve => {
window['clickPromise'] = new Promise(resolve => {
document.addEventListener('click', event => {
resolve({
type: event.type,
@ -44,7 +44,7 @@ it.flaky(options.FIREFOX && WIN)('should click the document', async({page, serve
});
});
await page.mouse.click(50, 60);
const event = await page.evaluate(() => window["clickPromise"]);
const event = await page.evaluate(() => window['clickPromise']);
expect(event.type).toBe('click');
expect(event.detail).toBe(1);
expect(event.clientX).toBe(50);
@ -56,7 +56,7 @@ it.flaky(options.FIREFOX && WIN)('should click the document', async({page, serve
it('should dblclick the div', async ({page, server}) => {
await page.setContent(`<div style='width: 100px; height: 100px;'>Click me</div>`);
await page.evaluate(() => {
window["dblclickPromise"] = new Promise(resolve => {
window['dblclickPromise'] = new Promise(resolve => {
document.querySelector('div').addEventListener('dblclick', event => {
resolve({
type: event.type,
@ -70,7 +70,7 @@ it('should dblclick the div', async({page, server}) => {
});
});
await page.mouse.dblclick(50, 60);
const event = await page.evaluate(() => window["dblclickPromise"]);
const event = await page.evaluate(() => window['dblclickPromise']);
expect(event.type).toBe('dblclick');
expect(event.detail).toBe(2);
expect(event.clientX).toBe(50);
@ -124,7 +124,7 @@ it('should trigger hover state with removed window.Node', async({page, server})
it('should set modifier keys on click', async ({page, server}) => {
await page.goto(server.PREFIX + '/input/scrollable.html');
await page.evaluate(() => document.querySelector('#button-3').addEventListener('mousedown', e => window["lastEvent"] = e, true));
await page.evaluate(() => document.querySelector('#button-3').addEventListener('mousedown', e => window['lastEvent'] = e, true));
const modifiers = {'Shift': 'shiftKey', 'Control': 'ctrlKey', 'Alt': 'altKey', 'Meta': 'metaKey'};
// In Firefox, the Meta modifier only exists on Mac
if (options.FIREFOX && !MAC)
@ -132,13 +132,13 @@ it('should set modifier keys on click', async({page, server}) => {
for (const modifier in modifiers) {
await page.keyboard.down(modifier);
await page.click('#button-3');
if (!(await page.evaluate(mod => window["lastEvent"][mod], modifiers[modifier])))
if (!(await page.evaluate(mod => window['lastEvent'][mod], modifiers[modifier])))
throw new Error(modifiers[modifier] + ' should be true');
await page.keyboard.up(modifier);
}
await page.click('#button-3');
for (const modifier in modifiers) {
if ((await page.evaluate(mod => window["lastEvent"][mod], modifiers[modifier])))
if ((await page.evaluate(mod => window['lastEvent'][mod], modifiers[modifier])))
throw new Error(modifiers[modifier] + ' should be false');
}
});
@ -149,9 +149,9 @@ it('should tween mouse movement', async({page}) => {
await page.evaluate(() => new Promise(requestAnimationFrame));
await page.mouse.move(100, 100);
await page.evaluate(() => {
window["result"] = [];
window['result'] = [];
document.addEventListener('mousemove', event => {
window["result"].push([event.clientX, event.clientY]);
window['result'].push([event.clientX, event.clientY]);
});
});
await page.mouse.move(200, 300, {steps: 5});
@ -172,7 +172,7 @@ it.skip(options.FIREFOX)('should work with mobile viewports and cross process na
await page.goto(server.CROSS_PROCESS_PREFIX + '/mobile.html');
await page.evaluate(() => {
document.addEventListener('click', event => {
window["result"] = {x: event.clientX, y: event.clientY};
window['result'] = {x: event.clientX, y: event.clientY};
});
});
@ -190,5 +190,5 @@ xdescribe('Drag and Drop', function() {
await page.hover('#target');
await page.mouse.up();
expect(await page.$eval('#target', target => target.contains(document.querySelector('#source')))).toBe(true); // could not find source in target
})
});
});

View File

@ -89,7 +89,7 @@ it('should work with binary post data', async({page, server}) => {
let request = null;
page.on('request', r => request = r);
await page.evaluate(async () => {
await fetch('./post', { method: 'POST', body: new Uint8Array(Array.from(Array(256).keys())) })
await fetch('./post', { method: 'POST', body: new Uint8Array(Array.from(Array(256).keys())) });
});
expect(request).toBeTruthy();
const buffer = request.postDataBuffer();
@ -105,7 +105,7 @@ it('should work with binary post data and interception', async({page, server}) =
await page.route('/post', route => route.continue());
page.on('request', r => request = r);
await page.evaluate(async () => {
await fetch('./post', { method: 'POST', body: new Uint8Array(Array.from(Array(256).keys())) })
await fetch('./post', { method: 'POST', body: new Uint8Array(Array.from(Array(256).keys())) });
});
expect(request).toBeTruthy();
const buffer = request.postDataBuffer();
@ -126,7 +126,7 @@ it('should parse the json post data', async ({ page, server }) => {
page.on('request', r => request = r);
await page.evaluate(() => fetch('./post', { method: 'POST', body: JSON.stringify({ foo: 'bar' }) }));
expect(request).toBeTruthy();
expect(request.postDataJSON()).toEqual({ "foo": "bar" });
expect(request.postDataJSON()).toEqual({ 'foo': 'bar' });
});
it('should parse the data if content-type is application/x-www-form-urlencoded', async ({page, server}) => {
@ -138,7 +138,7 @@ it('should parse the data if content-type is application/x-www-form-urlencoded',
await page.click('input[type=submit]');
expect(request).toBeTruthy();
expect(request.postDataJSON()).toEqual({'foo': 'bar','baz': '123'});
})
});
it('should be |undefined| when there is no post data', async ({ page, server }) => {
const response = await page.goto(server.EMPTY_PAGE);

View File

@ -20,22 +20,22 @@ import path from 'path';
it('should evaluate before anything else on the page', async ({ page, server }) => {
await page.addInitScript(function() {
window["injected"] = 123;
window['injected'] = 123;
});
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window["result"])).toBe(123);
expect(await page.evaluate(() => window['result'])).toBe(123);
});
it('should work with a path', async ({ page, server }) => {
await page.addInitScript({ path: path.join(__dirname, 'assets/injectedfile.js') });
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window["result"])).toBe(123);
expect(await page.evaluate(() => window['result'])).toBe(123);
});
it('should work with content', async ({ page, server }) => {
await page.addInitScript({ content: 'window["injected"] = 123' });
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window["result"])).toBe(123);
expect(await page.evaluate(() => window['result'])).toBe(123);
});
it('should throw without path and content', async ({ page, server }) => {
@ -45,11 +45,11 @@ it('should throw without path and content', async ({ page, server }) => {
it('should work with browser context scripts', async ({ browser, server }) => {
const context = await browser.newContext();
await context.addInitScript(() => window["temp"] = 123);
await context.addInitScript(() => window['temp'] = 123);
const page = await context.newPage();
await page.addInitScript(() => window["injected"] = window["temp"]);
await page.addInitScript(() => window['injected'] = window['temp']);
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window["result"])).toBe(123);
expect(await page.evaluate(() => window['result'])).toBe(123);
await context.close();
});
@ -58,39 +58,39 @@ it('should work with browser context scripts with a path', async ({ browser, ser
await context.addInitScript({ path: path.join(__dirname, 'assets/injectedfile.js') });
const page = await context.newPage();
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window["result"])).toBe(123);
expect(await page.evaluate(() => window['result'])).toBe(123);
await context.close();
});
it('should work with browser context scripts for already created pages', async ({ browser, server }) => {
const context = await browser.newContext();
const page = await context.newPage();
await context.addInitScript(() => window["temp"] = 123);
await page.addInitScript(() => window["injected"] = window["temp"]);
await context.addInitScript(() => window['temp'] = 123);
await page.addInitScript(() => window['injected'] = window['temp']);
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window["result"])).toBe(123);
expect(await page.evaluate(() => window['result'])).toBe(123);
await context.close();
});
it('should support multiple scripts', async ({ page, server }) => {
await page.addInitScript(function() {
window["script1"] = 1;
window['script1'] = 1;
});
await page.addInitScript(function() {
window["script2"] = 2;
window['script2'] = 2;
});
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window["script1"])).toBe(1);
expect(await page.evaluate(() => window["script2"])).toBe(2);
expect(await page.evaluate(() => window['script1'])).toBe(1);
expect(await page.evaluate(() => window['script2'])).toBe(2);
});
it('should work with CSP', async ({ page, server }) => {
server.setCSP('/empty.html', 'script-src ' + server.PREFIX);
await page.addInitScript(function() {
window["injected"] = 123;
window['injected'] = 123;
});
await page.goto(server.PREFIX + '/empty.html');
expect(await page.evaluate(() => window["injected"])).toBe(123);
expect(await page.evaluate(() => window['injected'])).toBe(123);
// Make sure CSP works.
await page.addScriptTag({ content: 'window.e = 10;' }).catch(e => void e);
@ -100,8 +100,8 @@ it('should work with CSP', async ({ page, server }) => {
it('should work after a cross origin navigation', async ({ page, server }) => {
await page.goto(server.CROSS_PROCESS_PREFIX);
await page.addInitScript(function() {
window["injected"] = 123;
window['injected'] = 123;
});
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window["result"])).toBe(123);
expect(await page.evaluate(() => window['result'])).toBe(123);
});

View File

@ -153,7 +153,7 @@ it('page.url should include hashes', async({page, server}) => {
await page.goto(server.EMPTY_PAGE + '#hash');
expect(page.url()).toBe(server.EMPTY_PAGE + '#hash');
await page.evaluate(() => {
window.location.hash = "dynamic";
window.location.hash = 'dynamic';
});
expect(page.url()).toBe(server.EMPTY_PAGE + '#dynamic');
});
@ -201,7 +201,7 @@ it('should have sane user agent', async ({page}) => {
const userAgent = await page.evaluate(() => navigator.userAgent);
const [
part1,
part2,
/* part2 */,
part3,
part4,
part5,
@ -245,11 +245,11 @@ it('frame.press should work', async({page, server}) => {
});
it.fail(options.FIREFOX)('frame.focus should work multiple times', async ({ context, server }) => {
const page1 = await context.newPage()
const page2 = await context.newPage()
const page1 = await context.newPage();
const page2 = await context.newPage();
for (const page of [page1, page2]) {
await page.setContent(`<button id="foo" onfocus="window.gotFocus=true"></button>`)
await page.focus("#foo")
expect(await page.evaluate(() => !!window['gotFocus'])).toBe(true)
await page.setContent(`<button id="foo" onfocus="window.gotFocus=true"></button>`);
await page.focus('#foo');
expect(await page.evaluate(() => !!window['gotFocus'])).toBe(true);
}
});

View File

@ -15,7 +15,7 @@
* limitations under the License.
*/
import { options } from './playwright.fixtures';
import './playwright.fixtures';
import utils from './utils';
it('should emulate type', async ({page, server}) => {
@ -137,12 +137,12 @@ it('should change the actual colors in css', async({page}) => {
return page.$eval('div', div => window.getComputedStyle(div).backgroundColor);
}
await page.emulateMedia({ colorScheme: "light" });
await page.emulateMedia({ colorScheme: 'light' });
expect(await getBackgroundColor()).toBe('rgb(255, 255, 255)');
await page.emulateMedia({ colorScheme: "dark" });
await page.emulateMedia({ colorScheme: 'dark' });
expect(await getBackgroundColor()).toBe('rgb(0, 0, 0)');
await page.emulateMedia({ colorScheme: "light" });
await page.emulateMedia({ colorScheme: 'light' });
expect(await getBackgroundColor()).toBe('rgb(255, 255, 255)');
})
});

View File

@ -253,7 +253,7 @@ it('should work with overwritten Promise', async ({ page, server }) => {
finally(f) {
return wrap(this._promise.finally(f));
}
};
}
const wrap = p => {
const result = new Promise2(() => { });
result._promise = p;
@ -261,13 +261,13 @@ it('should work with overwritten Promise', async ({ page, server }) => {
};
// @ts-ignore;
window.Promise = Promise2;
window["__Promise2"] = Promise2;
window['__Promise2'] = Promise2;
});
// Sanity check.
expect(await page.evaluate(() => {
const p = Promise.all([Promise.race([]), new Promise(() => { }).then(() => { })]);
return p instanceof window["__Promise2"];
return p instanceof window['__Promise2'];
})).toBe(true);
// Now, the new promise should be awaitable.
@ -279,7 +279,7 @@ it('should throw when passed more than one parameter', async ({ page, server })
let error;
await f().catch(e => error = e);
expect('' + error).toContain('Too many arguments');
}
};
// @ts-ignore
await expectThrow(() => page.evaluate((a, b) => false, 1, 2));
// @ts-ignore
@ -480,7 +480,7 @@ it('should work with non-strict expressions', async ({ page, server }) => {
it('should respect use strict expression', async ({ page, server }) => {
const error = await page.evaluate(() => {
"use strict";
'use strict';
// @ts-ignore
variableY = 3.14;
// @ts-ignore

View File

@ -43,7 +43,7 @@ it('should use text() for inspection', async({page}) => {
let text;
const inspect = value => {
text = util.inspect(value);
}
};
page.on('console', inspect);
await page.evaluate(() => console.log('Hello world'));
expect(text).toEqual('Hello world');
@ -120,7 +120,7 @@ it('should not throw when there are console messages in detached iframes', async
page.evaluate(async () => {
// 1. Create a popup that Playwright is not connected to.
const win = window.open('');
window["_popup"] = win;
window['_popup'] = win;
if (window.document.readyState !== 'complete')
await new Promise(f => window.addEventListener('load', f));
// 2. In this popup, create an iframe that console.logs a message.

View File

@ -87,7 +87,7 @@ it('should fire events in proper order', async({page, server}) => {
page.on('response', response => events.push('response'));
const response = await page.goto(server.EMPTY_PAGE);
expect(await response.finished()).toBe(null);
events.push('requestfinished')
events.push('requestfinished');
expect(events).toEqual(['request', 'response', 'requestfinished']);
});

View File

@ -21,7 +21,7 @@ it('should work', async({browser}) => {
const page = await context.newPage();
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window["__popup"] = window.open('about:blank')),
page.evaluate(() => window['__popup'] = window.open('about:blank')),
]);
expect(await page.evaluate(() => !!window.opener)).toBe(false);
expect(await popup.evaluate(() => !!window.opener)).toBe(true);
@ -34,7 +34,7 @@ it('should work with window features', async({browser, server}) => {
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window["__popup"] = window.open(window.location.href, 'Title', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=0,left=0')),
page.evaluate(() => window['__popup'] = window.open(window.location.href, 'Title', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=0,left=0')),
]);
expect(await page.evaluate(() => !!window.opener)).toBe(false);
expect(await popup.evaluate(() => !!window.opener)).toBe(true);
@ -90,7 +90,7 @@ it('should work with empty url', async({browser}) => {
const page = await context.newPage();
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window["__popup"] = window.open('')),
page.evaluate(() => window['__popup'] = window.open('')),
]);
expect(await page.evaluate(() => !!window.opener)).toBe(false);
expect(await popup.evaluate(() => !!window.opener)).toBe(true);
@ -102,7 +102,7 @@ it('should work with noopener and no url', async({browser}) => {
const page = await context.newPage();
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window["__popup"] = window.open(undefined, null, 'noopener')),
page.evaluate(() => window['__popup'] = window.open(undefined, null, 'noopener')),
]);
// Chromium reports `about:blank#blocked` here.
expect(popup.url().split('#')[0]).toBe('about:blank');
@ -116,7 +116,7 @@ it('should work with noopener and about:blank', async({browser}) => {
const page = await context.newPage();
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window["__popup"] = window.open('about:blank', null, 'noopener')),
page.evaluate(() => window['__popup'] = window.open('about:blank', null, 'noopener')),
]);
expect(await page.evaluate(() => !!window.opener)).toBe(false);
expect(await popup.evaluate(() => !!window.opener)).toBe(false);
@ -129,7 +129,7 @@ it('should work with noopener and url', async({browser, server}) => {
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window["__popup"] = window.open(url, null, 'noopener'), server.EMPTY_PAGE),
page.evaluate(url => window['__popup'] = window.open(url, null, 'noopener'), server.EMPTY_PAGE),
]);
expect(await page.evaluate(() => !!window.opener)).toBe(false);
expect(await popup.evaluate(() => !!window.opener)).toBe(false);

View File

@ -43,9 +43,9 @@ it('should fire for fetches', async({page, server}) => {
it('should report requests and responses handled by service worker', async ({page, server}) => {
await page.goto(server.PREFIX + '/serviceworkers/fetchdummy/sw.html');
await page.evaluate(() => window["activationPromise"]);
await page.evaluate(() => window['activationPromise']);
const [swResponse, request] = await Promise.all([
page.evaluate(() => window["fetchDummy"]('foo')),
page.evaluate(() => window['fetchDummy']('foo')),
page.waitForEvent('request'),
]);
expect(swResponse).toBe('responseFromServiceWorker:foo');

View File

@ -67,7 +67,7 @@ it('should throw exception in page context', async({page, server}) => {
});
const {message, stack} = await page.evaluate(async () => {
try {
await window["woof"]();
await window['woof']();
} catch (e) {
return {message: e.message, stack: e.stack};
}
@ -82,7 +82,7 @@ it('should support throwing "null"', async({page, server}) => {
});
const thrown = await page.evaluate(async () => {
try {
await window["woof"]();
await window['woof']();
} catch (e) {
return e;
}
@ -95,7 +95,7 @@ it('should be callable from-inside addInitScript', async({page, server}) => {
await page.exposeFunction('woof', function() {
called = true;
});
await page.addInitScript(() => window["woof"]());
await page.addInitScript(() => window['woof']());
await page.reload();
expect(called).toBe(true);
});

View File

@ -199,7 +199,6 @@ it('should not crash when navigating to bad SSL after a cross origin navigation'
});
it('should not throw if networkidle0 is passed as an option', async ({page, server}) => {
let error = null;
await page.goto(server.EMPTY_PAGE, {waitUntil: 'networkidle0' as any});
});
@ -420,7 +419,7 @@ it('should fail when navigating and show the url at the error message', async fu
it('should be able to navigate to a page controlled by service worker', async ({page, server}) => {
await page.goto(server.PREFIX + '/serviceworkers/fetch/sw.html');
await page.evaluate(() => window["activationPromise"]);
await page.evaluate(() => window['activationPromise']);
await page.goto(server.PREFIX + '/serviceworkers/fetch/sw.html');
});

View File

@ -79,9 +79,9 @@ it.fail(options.WEBKIT && MAC)('page.goBack should work for file urls', async ({
it('page.reload should work', async ({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => window["_foo"] = 10);
await page.evaluate(() => window['_foo'] = 10);
await page.reload();
expect(await page.evaluate(() => window["_foo"])).toBe(undefined);
expect(await page.evaluate(() => window['_foo'])).toBe(undefined);
});
it('page.reload should work with data url', async ({page, server}) => {

View File

@ -34,8 +34,8 @@ async function networkIdleTest(frame: Frame, server: TestServer, action: () => P
server.waitForRequest(suffix),
(frame['_page'] as Page).waitForRequest(server.PREFIX + suffix),
]);
}
let responses = {};
};
const responses = {};
// Hold on to a bunch of requests without answering.
server.setRoute('/fetch-request-a.js', (req, res) => responses['a'] = res);
const firstFetchResourceRequested = waitForRequest('/fetch-request-a.js');
@ -61,8 +61,6 @@ async function networkIdleTest(frame: Frame, server: TestServer, action: () => P
expect(actionFinished).toBe(false);
expect(responses['a']).toBeTruthy();
let timer;
let timerTriggered = false;
// Finishing response should trigger the second round.
finishResponse(responses['a']);
@ -70,7 +68,8 @@ async function networkIdleTest(frame: Frame, server: TestServer, action: () => P
await secondFetchResourceRequested;
expect(actionFinished).toBe(false);
// Finishing the last response should trigger networkidle.
timer = setTimeout(() => timerTriggered = true, 500);
let timerTriggered = false;
const timer = setTimeout(() => timerTriggered = true, 500);
finishResponse(responses['d']);
const response = await actionPromise;

View File

@ -446,7 +446,7 @@ it('should support cors with GET', async({page, server}) => {
it('should support cors with POST', async ({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.route('**/cars', async (route) => {
await page.route('**/cars', async route => {
await route.fulfill({
contentType: 'application/json',
headers: { 'Access-Control-Allow-Origin': '*' },
@ -468,7 +468,7 @@ it('should support cors with POST', async({page, server}) => {
it('should support cors with credentials', async ({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.route('**/cars', async (route) => {
await page.route('**/cars', async route => {
await route.fulfill({
contentType: 'application/json',
headers: {
@ -494,7 +494,7 @@ it('should support cors with credentials', async({page, server}) => {
it('should reject cors with disallowed credentials', async ({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.route('**/cars', async (route) => {
await page.route('**/cars', async route => {
await route.fulfill({
contentType: 'application/json',
headers: {
@ -508,7 +508,7 @@ it('should reject cors with disallowed credentials', async({page, server}) => {
});
let error = '';
try {
const resp = await page.evaluate(async () => {
await page.evaluate(async () => {
const response = await fetch('https://example.com/cars', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },

View File

@ -72,7 +72,8 @@ it('should select only first option', async({page, server}) => {
expect(await page.evaluate(() => window['result'].onChange)).toEqual(['blue']);
});
it('should not throw when select causes navigation', async({page, server}) => { await page.goto(server.PREFIX + '/input/select.html');
it('should not throw when select causes navigation', async ({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.$eval('select', select => select.addEventListener('input', () => window.location.href = '/empty.html'));
await Promise.all([
page.selectOption('select', 'blue'),
@ -139,7 +140,7 @@ it('should return [] on no values',async({page, server}) => {
it('should not allow null items',async ({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.evaluate(() => window['makeMultiple']());
let error = null
let error = null;
await page.selectOption('select', ['blue', null, 'black','magenta']).catch(e => error = e);
expect(error.message).toContain('options[1]: expected object, got null');
});

View File

@ -71,7 +71,7 @@ it('should emit event on/off', async({page, server}) => {
const listener = chooser => {
page.off('filechooser', listener);
f(chooser);
}
};
page.on('filechooser', listener);
}),
page.click('input'),
@ -86,7 +86,7 @@ it('should emit event addListener/removeListener', async({page, server}) => {
const listener = chooser => {
page.removeListener('filechooser', listener);
f(chooser);
}
};
page.addListener('filechooser', listener);
}),
page.click('input'),
@ -185,7 +185,7 @@ it('should detect mime type', async({page, server}) => {
<input type="file" name="file1">
<input type="file" name="file2">
<input type="submit" value="Submit">
</form>`)
</form>`);
await (await page.$('input[name=file1]')).setInputFiles(path.join(__dirname, '/assets/file-to-upload.txt'));
await (await page.$('input[name=file2]')).setInputFiles(path.join(__dirname, '/assets/pptr.png'));
await Promise.all([

View File

@ -60,7 +60,7 @@ it('should work with pages that have loaded before being connected to', async({p
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window["_popup"] = window.open(document.location.href)),
page.evaluate(() => window['_popup'] = window.open(document.location.href)),
]);
// The url is about:blank in FF.
// expect(popup.url()).toBe(server.EMPTY_PAGE);
@ -149,7 +149,7 @@ it('should resolve after popup load', async({browser, server}) => {
const [popup] = await Promise.all([
page.waitForEvent('popup'),
server.waitForRequest('/one-style.css'),
page.evaluate(url => window["popup"] = window.open(url), server.PREFIX + '/one-style.html'),
page.evaluate(url => window['popup'] = window.open(url), server.PREFIX + '/one-style.html'),
]);
let resolved = false;
const loadSatePromise = popup.waitForLoadState().then(() => resolved = true);

View File

@ -15,7 +15,7 @@
* limitations under the License.
*/
import { options } from './playwright.fixtures';
import './playwright.fixtures';
import utils from './utils';
import type { Frame } from '..';

View File

@ -16,8 +16,8 @@
import { options } from './playwright.fixtures';
import fs from 'fs'
import path from 'path'
import fs from 'fs';
import path from 'path';
// Printing to pdf is currently only supported in headless chromium.

View File

@ -33,7 +33,7 @@ export const options = {
HEADLESS: !!valueFromEnv('HEADLESS', true),
WIRE: !!process.env.PWWIRE,
SLOW_MO: valueFromEnv('SLOW_MO', 0),
}
};
declare global {
interface WorkerState {
@ -89,17 +89,17 @@ registerWorkerFixture('httpService', async ({}, test) => {
]);
});
const getExecutablePath = (browserName) => {
const getExecutablePath = browserName => {
if (browserName === 'chromium' && process.env.CRPATH)
return process.env.CRPATH;
if (browserName === 'firefox' && process.env.FFPATH)
return process.env.FFPATH;
if (browserName === 'webkit' && process.env.WKPATH)
return process.env.WKPATH;
}
};
registerWorkerFixture('defaultBrowserOptions', async ({browserName}, test) => {
let executablePath = getExecutablePath(browserName);
const executablePath = getExecutablePath(browserName);
if (executablePath)
console.error(`Using executable at ${executablePath}`);
@ -135,7 +135,7 @@ registerWorkerFixture('playwright', async({browserName}, test) => {
spawnedProcess.stderr.destroy();
await teardownCoverage();
} else {
await test(require('../index'))
await test(require('../index'));
await teardownCoverage();
}

View File

@ -28,7 +28,7 @@ it('should inherit user agent from browser context', async function({browser, se
page.click('a'),
]);
await popup.waitForLoadState('domcontentloaded');
const userAgent = await popup.evaluate(() => window["initialUserAgent"]);
const userAgent = await popup.evaluate(() => window['initialUserAgent']);
const request = await requestPromise;
await context.close();
expect(userAgent).toBe('hey');
@ -60,7 +60,7 @@ it('should inherit extra headers from browser context', async function({browser,
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
const requestPromise = server.waitForRequest('/dummy.html');
await page.evaluate(url => window["_popup"] = window.open(url), server.PREFIX + '/dummy.html');
await page.evaluate(url => window['_popup'] = window.open(url), server.PREFIX + '/dummy.html');
const request = await requestPromise;
await context.close();
expect(request.headers['foo']).toBe('bar');
@ -88,7 +88,7 @@ it('should inherit http credentials from browser context', async function({brows
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window["_popup"] = window.open(url), server.PREFIX + '/title.html'),
page.evaluate(url => window['_popup'] = window.open(url), server.PREFIX + '/title.html'),
]);
await popup.waitForLoadState('domcontentloaded');
expect(await popup.title()).toBe('Woof-Woof');
@ -156,7 +156,7 @@ it('should respect routes from browser context', async function({browser, server
});
await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window["__popup"] = window.open(url), server.EMPTY_PAGE),
page.evaluate(url => window['__popup'] = window.open(url), server.EMPTY_PAGE),
]);
expect(intercepted).toBe(true);
await context.close();

View File

@ -107,7 +107,7 @@ it.fail(options.CHROMIUM && !options.HEADLESS)('should exclude patterns', async
it('should use socks proxy', async ({ browserType, defaultBrowserOptions }) => {
const server = socks.createServer((info, accept, deny) => {
let socket;
if (socket = accept(true)) {
if ((socket = accept(true))) {
// Catch and ignore ECONNRESET errors.
socket.on('error', () => {});
const body = '<html><title>Served by the SOCKS proxy</title></html>';

View File

@ -33,7 +33,7 @@ class RemoteServer {
_output: Map<any, any>;
_outputCallback: Map<any, any>;
_browserType: BrowserType<Browser>;
_child: import("child_process").ChildProcess;
_child: import('child_process').ChildProcess;
_exitPromise: Promise<unknown>;
_exitAndDisconnectPromise: Promise<any>;
_browser: Browser;
@ -60,7 +60,7 @@ class RemoteServer {
...extraOptions,
};
this._child = spawn('node', [path.join(__dirname, 'fixtures', 'closeme.js'), JSON.stringify(options)]);
this._child.on('error', (...args) => console.log("ERROR", ...args));
this._child.on('error', (...args) => console.log('ERROR', ...args));
this._exitPromise = new Promise(resolve => this._child.on('exit', (exitCode, signal) => {
this._didExit = true;
resolve(exitCode);
@ -72,7 +72,7 @@ class RemoteServer {
// Uncomment to debug.
// console.log(data.toString());
let match;
while (match = outputString.match(/\(([^()]+)=>([^()]+)\)/)) {
while ((match = outputString.match(/\(([^()]+)=>([^()]+)\)/))) {
const key = match[1];
const value = match[2];
this._addOutput(key, value);

View File

@ -135,9 +135,7 @@ it('should not modify the headers sent to the server', async({page, server}) =>
}, server.CROSS_PROCESS_PREFIX + '/something');
expect(text).toBe('done');
let playwrightRequest;
await page.route(server.CROSS_PROCESS_PREFIX + '/something', (route, request) => {
playwrightRequest = request;
route.continue({
headers: {
...request.headers()

View File

@ -21,7 +21,6 @@ import type { Page } from '..';
import fs from 'fs';
import path from 'path';
import url from 'url';
import { tmpdir } from 'os';
declare global {
@ -72,15 +71,15 @@ function almostGrey(r, g, b, alpha) {
}
function expectAll(pixels, rgbaPredicate) {
const checkPixel = (i) => {
const checkPixel = i => {
const r = pixels[i];
const g = pixels[i + 1];
const b = pixels[i + 2];
const alpha = pixels[i + 3];
rgbaPredicate(r, g, b, alpha);
}
};
try {
for (var i = 0, n = pixels.length; i < n; i += 4)
for (let i = 0, n = pixels.length; i < n; i += 4)
checkPixel(i);
} catch (e) {
// Log pixel values on failure.
@ -159,9 +158,9 @@ class VideoPlayer {
async pixels(point = {x: 0, y: 0}) {
const pixels = await this._page.$eval('video', (video: HTMLVideoElement, point) => {
let canvas = document.createElement("canvas");
const canvas = document.createElement('canvas');
if (!video.videoWidth || !video.videoHeight)
throw new Error("Video element is empty");
throw new Error('Video element is empty');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const context = canvas.getContext('2d');

View File

@ -25,8 +25,8 @@ async function checkSlowMo(toImpl, page, task) {
throw new Error('already did slowmo');
await new Promise(x => setTimeout(x, 100));
didSlowMo = true;
return orig.call(this, ...args)
}
return orig.call(this, ...args);
};
await task();
expect(!!didSlowMo).toBe(true);
}
@ -41,7 +41,7 @@ async function checkPageSlowMo(toImpl, page, task) {
<option>foo</option>
</select>
<input type="file" class="file">
`)
`);
await checkSlowMo(toImpl, page, task);
}
@ -120,7 +120,7 @@ async function checkFrameSlowMo(toImpl, page, server, task) {
<option>foo</option>
</select>
<input type="file" class="file">
`)
`);
await checkSlowMo(toImpl, page, task.bind(null, frame));
}
@ -189,7 +189,7 @@ async function checkElementSlowMo(toImpl, page, selector, task) {
<option>foo</option>
</select>
<input type="file" class="file">
`)
`);
const element = await page.$(selector);
await checkSlowMo(toImpl, page, task.bind(null, element));
}

View File

@ -169,10 +169,10 @@ it('should respect default timeout', async({page, playwright}) => {
it('should disable timeout when its set to 0', async ({page}) => {
const watchdog = page.waitForFunction(() => {
window['__counter'] = (window['__counter'] || 0) + 1;
return window["__injected"];
return window['__injected'];
}, {}, {timeout: 0, polling: 10});
await page.waitForFunction(() => window['__counter'] > 10);
await page.evaluate(() => window["__injected"] = true);
await page.evaluate(() => window['__injected'] = true);
await watchdog;
});

View File

@ -18,11 +18,6 @@
import './playwright.fixtures';
import utils from './utils';
async function giveItTimeToLog(frame) {
await frame.evaluate(() => new Promise(f => requestAnimationFrame(() => requestAnimationFrame(f))));
await frame.evaluate(() => new Promise(f => requestAnimationFrame(() => requestAnimationFrame(f))));
}
const addElement = tag => document.body.appendChild(document.createElement(tag));
it('should survive cross-process navigation', async ({page, server}) => {