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 /electron-types.d.ts
utils/generate_types/overrides.d.ts utils/generate_types/overrides.d.ts
utils/generate_types/test/test.ts utils/generate_types/test/test.ts
/test/
node_modules/ node_modules/
browser_patches/*/checkout/ browser_patches/*/checkout/
packages/**/*.d.ts 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}) => { it('calling window.stop async', async ({page, server}) => {
server.setRoute('/empty.html', async (req, res) => {}); server.setRoute('/empty.html', async (req, res) => {});
await page.evaluate((url) => { await page.evaluate(url => {
window.location.href = url; window.location.href = url;
setTimeout(() => window.stop(), 100); setTimeout(() => window.stop(), 100);
}, server.EMPTY_PAGE); }, server.EMPTY_PAGE);
}); });
it('calling window.stop sync', async ({page, server}) => { it('calling window.stop sync', async ({page, server}) => {
await page.evaluate((url) => { await page.evaluate(url => {
window.location.href = url; window.location.href = url;
window.stop(); window.stop();
}, server.EMPTY_PAGE); }, server.EMPTY_PAGE);

View file

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

View file

@ -126,7 +126,7 @@ it('close() should abort waitForEvent', async({ browser }) => {
const context = await browser.newContext(); const context = await browser.newContext();
const promise = context.waitForEvent('page').catch(e => e); const promise = context.waitForEvent('page').catch(e => e);
await context.close(); await context.close();
let error = await promise; const error = await promise;
expect(error.message).toContain('Context closed'); 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 page = await context.newPage();
const response = await page.goto(server.PREFIX + '/playground.html'); const response = await page.goto(server.PREFIX + '/playground.html');
expect(response.status()).toBe(200); expect(response.status()).toBe(200);
expect(await page.title()).toBe("Playground"); expect(await page.title()).toBe('Playground');
expect((await response.body()).toString()).toContain("Playground"); expect((await response.body()).toString()).toContain('Playground');
await context.close(); await context.close();
}); });

View file

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

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
import { options } from './playwright.fixtures'; import './playwright.fixtures';
it('should work', async ({ browser }) => { it('should work', async ({ browser }) => {
const func = () => new Date(1479579154987).toString(); 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']) { for (const timezoneId of ['Foo/Bar', 'Baz/Qux']) {
let error = null; let error = null;
const context = await browser.newContext({ timezoneId }); 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}`); expect(error.message).toContain(`Invalid timezone ID: ${timezoneId}`);
await context.close(); 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}) => { 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); const error = await browserType.connect({ wsEndpoint: remoteServer.wsEndpoint(), __testHookBeforeCreateBrowser } as any).catch(e => e);
expect(error.message).toContain('Dummy'); 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}) => { it('WebSocket should work', async ({page, server}) => {
const value = await page.evaluate((port) => { const value = await page.evaluate(port => {
let cb; let cb;
const result = new Promise(f => cb = f); const result = new Promise(f => cb = f);
const ws = new WebSocket('ws://localhost:' + port + '/ws'); 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( expect(coverage).toEqual(
[ [
{ {
"ranges": [ 'ranges': [
{ {
"start": 149, 'start': 149,
"end": 297 'end': 297
}, },
{ {
"start": 327, 'start': 327,
"end": 433 '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 context = await browserType.launchPersistentContext(userDataDir, extensionOptions) as ChromiumBrowserContext;
const backgroundPages = context.backgroundPages(); const backgroundPages = context.backgroundPages();
let backgroundPage = backgroundPages.length const backgroundPage = backgroundPages.length
? backgroundPages[0] ? backgroundPages[0]
: await context.waitForEvent('backgroundpage'); : await context.waitForEvent('backgroundpage');
expect(backgroundPage).toBeTruthy(); 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}) => { 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 context = await browser.newContext({ ...iPhone, timezoneId: 'America/Jamaica', locale: 'fr-CH', userAgent: 'UA' });
const page = await context.newPage(); const page = await context.newPage();

View file

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { options } from '../playwright.fixtures'; 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}) { it.skip(!options.CHROMIUM)('should work', async function({page}) {
const client = await (page.context() as ChromiumBrowserContext).newCDPSession(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; let clicked = false;
const handle = await page.$('button'); const handle = await page.$('button');
const __testHookBeforeHitTarget = () => page.evaluate(() => { 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'; document.querySelector('button').style.marginLeft = margin + 'px';
}); });
const promise = handle.click({ timeout: 5000, __testHookBeforeHitTarget } as any).then(() => clicked = true).catch(e => e); 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'; import utils from './utils';
it('context.cookies() should work', async ({server, launchPersistent}) => { it('context.cookies() should work', async ({server, launchPersistent}) => {
const {page, context} = await launchPersistent(); const {page} = await launchPersistent();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const documentCookie = await page.evaluate(() => { const documentCookie = await page.evaluate(() => {
document.cookie = 'username=John Doe'; 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}) => { 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.goto(server.EMPTY_PAGE);
await page.context().addCookies([{ await page.context().addCookies([{
url: server.EMPTY_PAGE, url: server.EMPTY_PAGE,
@ -61,7 +61,7 @@ it('context.addCookies() should work', async ({server, launchPersistent}) => {
}); });
it('context.clearCookies() 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.goto(server.EMPTY_PAGE);
await page.context().addCookies([{ await page.context().addCookies([{
url: server.EMPTY_PAGE, url: server.EMPTY_PAGE,
@ -102,14 +102,14 @@ it('should(not) block third party cookies', async ({server, launchPersistent}) =
if (allowsThirdParty) { if (allowsThirdParty) {
expect(cookies).toEqual([ expect(cookies).toEqual([
{ {
"domain": "127.0.0.1", 'domain': '127.0.0.1',
"expires": -1, 'expires': -1,
"httpOnly": false, 'httpOnly': false,
"name": "username", 'name': 'username',
"path": "/", 'path': '/',
"sameSite": "None", 'sameSite': 'None',
"secure": false, 'secure': false,
"value": "John Doe" 'value': 'John Doe'
} }
]); ]);
} else { } else {
@ -125,12 +125,12 @@ it('should support viewport option', async ({launchPersistent}) => {
}); });
it('should support deviceScaleFactor 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); expect(await page.evaluate('window.devicePixelRatio')).toBe(3);
}); });
it('should support userAgent option', async ({server, launchPersistent}) => { 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'); expect(await page.evaluate(() => navigator.userAgent)).toBe('foobar');
const [request] = await Promise.all([ const [request] = await Promise.all([
server.waitForRequest('/empty.html'), server.waitForRequest('/empty.html'),
@ -140,14 +140,14 @@ it('should support userAgent option', async ({server, launchPersistent}) => {
}); });
it('should support bypassCSP 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.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window["__injected"] = 42;'}); await page.addScriptTag({content: 'window["__injected"] = 42;'});
expect(await page.evaluate('__injected')).toBe(42); expect(await page.evaluate('__injected')).toBe(42);
}); });
it('should support javascriptEnabled option', async ({launchPersistent}) => { 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>'); await page.goto('data:text/html, <script>var something = "forbidden"</script>');
let error = null; let error = null;
await page.evaluate('something').catch(e => error = e); 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}) => { 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'); server.setAuth('/playground.html', 'user', 'pass');
const response = await page.goto(server.PREFIX + '/playground.html'); const response = await page.goto(server.PREFIX + '/playground.html');
expect(response.status()).toBe(200); expect(response.status()).toBe(200);
}); });
it('should support offline option', async ({server, launchPersistent}) => { 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); const error = await page.goto(server.EMPTY_PAGE).catch(e => e);
expect(error).toBeTruthy(); expect(error).toBeTruthy();
}); });
it.skip(true)('should support acceptDownloads option', async ({server, launchPersistent}) => { it.skip(true)('should support acceptDownloads option', async ({server, launchPersistent}) => {
// TODO: unskip once we support downloads in persistent context. // 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) => { server.setRoute('/download', (req, res) => {
res.setHeader('Content-Type', 'application/octet-stream'); res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', 'attachment'); res.setHeader('Content-Disposition', 'attachment');

View file

@ -21,36 +21,36 @@ import utils from './utils';
const { removeUserDataDir, makeUserDataDir } = utils; const { removeUserDataDir, makeUserDataDir } = utils;
it('should support hasTouch option', async ({server, launchPersistent}) => { 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'); await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => 'ontouchstart' in window)).toBe(true); expect(await page.evaluate(() => 'ontouchstart' in window)).toBe(true);
}); });
it.skip(options.FIREFOX)('should work in persistent context', async ({server, launchPersistent}) => { it.skip(options.FIREFOX)('should work in persistent context', async ({server, launchPersistent}) => {
// Firefox does not support mobile. // 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'); await page.goto(server.PREFIX + '/empty.html');
expect(await page.evaluate(() => window.innerWidth)).toBe(980); expect(await page.evaluate(() => window.innerWidth)).toBe(980);
}); });
it('should support colorScheme option', async ({launchPersistent}) => { 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: light)').matches)).toBe(false);
expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches)).toBe(true); expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches)).toBe(true);
}); });
it('should support timezoneId option', async ({launchPersistent}) => { 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)'); 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}) => { 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'); expect(await page.evaluate(() => navigator.language)).toBe('fr-CH');
}); });
it('should support geolocation and permissions options', async ({server, launchPersistent}) => { 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); await page.goto(server.EMPTY_PAGE);
const geolocation = await page.evaluate(() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => { const geolocation = await page.evaluate(() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
resolve({latitude: position.coords.latitude, longitude: position.coords.longitude}); 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}) => { it('should support ignoreHTTPSErrors option', async ({httpsServer, launchPersistent}) => {
const {page, context} = await launchPersistent({ignoreHTTPSErrors: true}); const {page} = await launchPersistent({ignoreHTTPSErrors: true});
let error = null; let error = null;
const response = await page.goto(httpsServer.EMPTY_PAGE).catch(e => error = e); const response = await page.goto(httpsServer.EMPTY_PAGE).catch(e => error = e);
expect(error).toBe(null); expect(error).toBe(null);
@ -67,7 +67,7 @@ it('should support ignoreHTTPSErrors option', async ({httpsServer, launchPersist
}); });
it('should support extraHTTPHeaders option', async ({server, launchPersistent}) => { 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([ const [request] = await Promise.all([
server.waitForRequest('/empty.html'), server.waitForRequest('/empty.html'),
page.goto(server.EMPTY_PAGE), 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}) => { 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. // Note: we need an open page to make sure its functional.
expect(fs.readdirSync(tmpDir).length).toBeGreaterThan(0); expect(fs.readdirSync(tmpDir).length).toBeGreaterThan(0);
await context.close(); 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}) => { 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()); const urls = context.pages().map(page => page.url());
expect(urls).toEqual(['about:blank']); 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}) => { it('should fire close event for a persistent context', async ({launchPersistent}) => {
const {page, context} = await launchPersistent(); const {context} = await launchPersistent();
let closed = false; let closed = false;
context.on('close', () => closed = true); context.on('close', () => closed = true);
await context.close(); 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}) => { 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.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/simple.html', { waitUntil: 'load' }); await page.goto(server.PREFIX + '/jscoverage/simple.html', { waitUntil: 'load' });
const coverage = await page.coverage.stopJSCoverage(); 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}) => { it.skip(options.CHROMIUM)('coverage should be missing', async ({launchPersistent}) => {
const {page, context} = await launchPersistent(); const {page} = await launchPersistent();
expect(page.coverage).toBe(null); expect(page.coverage).toBe(null);
}); });

View file

@ -110,7 +110,7 @@ it('should be atomic', async({playwright, page}) => {
query(root, selector) { query(root, selector) {
const result = root.querySelector(selector); const result = root.querySelector(selector);
if (result) if (result)
Promise.resolve().then(() => result.onclick = ""); Promise.resolve().then(() => result.onclick = '');
return result; return result;
}, },
queryAll(root: HTMLElement, selector: string) { 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.waitForEvent('download'),
page.click('a') page.click('a')
]); ]);
const userPath = path.join(tmpDir, "download.txt"); const userPath = path.join(tmpDir, 'download.txt');
await download.saveAs(userPath); await download.saveAs(userPath);
expect(fs.existsSync(userPath)).toBeTruthy(); expect(fs.existsSync(userPath)).toBeTruthy();
expect(fs.readFileSync(userPath).toString()).toBe('Hello world'); 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.waitForEvent('download'),
page.click('a') page.click('a')
]); ]);
const userPath = path.join(tmpDir, "download.txt"); const userPath = path.join(tmpDir, 'download.txt');
await download.saveAs(userPath); await download.saveAs(userPath);
expect(fs.existsSync(userPath)).toBeTruthy(); expect(fs.existsSync(userPath)).toBeTruthy();
expect(fs.readFileSync(userPath).toString()).toBe('Hello world'); 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.waitForEvent('download'),
page.click('a') page.click('a')
]); ]);
const userPath = path.join(tmpDir, "download.txt"); const userPath = path.join(tmpDir, 'download.txt');
await download.saveAs(userPath); await download.saveAs(userPath);
expect(fs.existsSync(userPath)).toBeTruthy(); expect(fs.existsSync(userPath)).toBeTruthy();
expect(fs.readFileSync(userPath).toString()).toBe('Hello world'); 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); await download.saveAs(anotherUserPath);
expect(fs.existsSync(anotherUserPath)).toBeTruthy(); expect(fs.existsSync(anotherUserPath)).toBeTruthy();
expect(fs.readFileSync(anotherUserPath).toString()).toBe('Hello world'); 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.waitForEvent('download'),
page.click('a') page.click('a')
]); ]);
const userPath = path.join(tmpDir, "download.txt"); const userPath = path.join(tmpDir, 'download.txt');
await download.saveAs(userPath); await download.saveAs(userPath);
expect((await util.promisify(fs.readdir)(tmpDir)).length).toBe(1); expect((await util.promisify(fs.readdir)(tmpDir)).length).toBe(1);
await download.saveAs(userPath); await download.saveAs(userPath);
@ -137,8 +137,8 @@ it('should create subdirectories when saving to non-existent user-specified path
page.waitForEvent('download'), page.waitForEvent('download'),
page.click('a') 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) await download.saveAs(nestedPath);
expect(fs.existsSync(nestedPath)).toBeTruthy(); expect(fs.existsSync(nestedPath)).toBeTruthy();
expect(fs.readFileSync(nestedPath).toString()).toBe('Hello world'); expect(fs.readFileSync(nestedPath).toString()).toBe('Hello world');
await page.close(); await page.close();
@ -152,7 +152,7 @@ it.skip(options.WIRE)('should save when connected remotely', async({tmpDir, serv
page.waitForEvent('download'), page.waitForEvent('download'),
page.click('a') 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); await download.saveAs(nestedPath);
expect(fs.existsSync(nestedPath)).toBeTruthy(); expect(fs.existsSync(nestedPath)).toBeTruthy();
expect(fs.readFileSync(nestedPath).toString()).toBe('Hello world'); 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.waitForEvent('download'),
page.click('a') 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); const { message } = await download.saveAs(userPath).catch(e => e);
expect(message).toContain('Pass { acceptDownloads: true } when you are creating your browser context'); expect(message).toContain('Pass { acceptDownloads: true } when you are creating your browser context');
await page.close(); await page.close();
@ -181,7 +181,7 @@ it('should error when saving after deletion', async({tmpDir, browser, server}) =
page.waitForEvent('download'), page.waitForEvent('download'),
page.click('a') page.click('a')
]); ]);
const userPath = path.join(tmpDir, "download.txt"); const userPath = path.join(tmpDir, 'download.txt');
await download.delete(); await download.delete();
const { message } = await download.saveAs(userPath).catch(e => e); const { message } = await download.saveAs(userPath).catch(e => e);
expect(message).toContain('Download already deleted. Save before deleting.'); 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.waitForEvent('download'),
page.click('a') page.click('a')
]); ]);
const userPath = path.join(tmpDir, "download.txt"); const userPath = path.join(tmpDir, 'download.txt');
await download.delete(); await download.delete();
const { message } = await download.saveAs(userPath).catch(e => e); const { message } = await download.saveAs(userPath).catch(e => e);
expect(message).toContain('Download already deleted. Save before deleting.'); 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}) => { it(`should report download path within page.on('download', …) handler for Files`, async ({browser, server}) => {
const page = await browser.newPage({ acceptDownloads: true }); const page = await browser.newPage({ acceptDownloads: true });
const onDownloadPath = new Promise<string>((res) => { const onDownloadPath = new Promise<string>(res => {
page.on('download', dl => { page.on('download', dl => {
dl.path().then(res); dl.path().then(res);
}); });
@ -236,10 +236,10 @@ it(`should report download path within page.on('download', …) handler for File
const path = await onDownloadPath; const path = await onDownloadPath;
expect(fs.readFileSync(path).toString()).toBe('Hello world'); expect(fs.readFileSync(path).toString()).toBe('Hello world');
await page.close(); await page.close();
}) });
it(`should report download path within page.on('download', …) handler for Blobs`, async ({browser, server}) => { it(`should report download path within page.on('download', …) handler for Blobs`, async ({browser, server}) => {
const page = await browser.newPage({ acceptDownloads: true }); const page = await browser.newPage({ acceptDownloads: true });
const onDownloadPath = new Promise<string>((res) => { const onDownloadPath = new Promise<string>(res => {
page.on('download', dl => { page.on('download', dl => {
dl.path().then(res); dl.path().then(res);
}); });
@ -249,7 +249,7 @@ it(`should report download path within page.on('download', …) handler for Blob
const path = await onDownloadPath; const path = await onDownloadPath;
expect(fs.readFileSync(path).toString()).toBe('Hello world'); expect(fs.readFileSync(path).toString()).toBe('Hello world');
await page.close(); await page.close();
}) });
it.fixme(options.FIREFOX || options.WEBKIT)('should report alt-click downloads', async ({browser, server}) => { it.fixme(options.FIREFOX || options.WEBKIT)('should report alt-click downloads', async ({browser, server}) => {
// Firefox does not download on alt-click by default. // Firefox does not download on alt-click by default.
// Our WebKit embedder does not download on alt-click, although Safari does. // 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 page1 = await createPage(1);
const page2 = await createPage(2); await createPage(2);
const page3 = await createPage(3); await createPage(3);
await page1.close(); await page1.close();
const page4 = await createPage(4); await createPage(4);
const titles = []; const titles = [];
for (const window of application.windows()) for (const window of application.windows())
titles.push(await window.title()); titles.push(await window.title());
@ -86,7 +86,7 @@ it.skip(!options.CHROMIUM)('should route network', async ({ application }) => {
status: 200, status: 200,
contentType: 'text/html', contentType: 'text/html',
body: '<title>Hello World</title>', body: '<title>Hello World</title>',
}) });
}); });
const page = await application.newBrowserWindow({ width: 800, height: 600 }); const page = await application.newBrowserWindow({ width: 800, height: 600 });
await page.goto('https://localhost:1000/empty.html'); 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 }) => { 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 }); const page = await application.newBrowserWindow({ width: 800, height: 600 });
await page.goto('data:text/html,<script>window.copy = magic</script>'); await page.goto('data:text/html,<script>window.copy = magic</script>');
expect(await page.evaluate(() => window['copy'])).toBe(42); expect(await page.evaluate(() => window['copy'])).toBe(42);
}); });
it.skip(!options.CHROMIUM)('should expose function', async ({ application }) => { it.skip(!options.CHROMIUM)('should expose function', async ({ application }) => {
const t = Date.now();
await application.context().exposeFunction('add', (a, b) => a + b); await application.context().exposeFunction('add', (a, b) => a + b);
const page = await application.newBrowserWindow({ width: 800, height: 600 }); const page = await application.newBrowserWindow({ width: 800, height: 600 });
await page.goto('data:text/html,<script>window["result"] = add(20, 22);</script>'); await page.goto('data:text/html,<script>window["result"] = add(20, 22);</script>');

View file

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { options } from '../playwright.fixtures'; import '../playwright.fixtures';
import { registerFixture } from '../../test-runner'; import { registerFixture } from '../../test-runner';
import type {ElectronApplication, ElectronLauncher, ElectronPage} from '../../electron-types'; import type {ElectronApplication, ElectronLauncher, ElectronPage} from '../../electron-types';
import path from 'path'; import path from 'path';
@ -29,7 +29,7 @@ declare global {
} }
declare module '../../index' { declare module '../../index' {
const electron: ElectronLauncher const electron: ElectronLauncher;
} }
registerFixture('application', async ({playwright}, test) => { 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); await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([ const [popup] = await Promise.all([
page.waitForEvent('popup'), 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 divHandle = await page.evaluateHandle(() => {
const div = document.createElement('div'); const div = document.createElement('div');
@ -89,7 +89,7 @@ it('should work for adopted elements', async ({ page, server }) => {
await popup.waitForLoadState('domcontentloaded'); await popup.waitForLoadState('domcontentloaded');
await page.evaluate(() => { await page.evaluate(() => {
const div = document.querySelector('div'); const div = document.querySelector('div');
window["__popup"].document.body.appendChild(div); window['__popup'].document.body.appendChild(div);
}); });
expect(await divHandle.ownerFrame()).toBe(popup.mainFrame()); 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); await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([ const [popup] = await Promise.all([
page.waitForEvent('popup'), 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 divHandle = await page.evaluateHandle(() => {
const div = document.createElement('div'); const div = document.createElement('div');
@ -54,7 +54,7 @@ it('should work for adopted elements', async({page,server}) => {
await popup.waitForLoadState('domcontentloaded'); await popup.waitForLoadState('domcontentloaded');
await page.evaluate(() => { await page.evaluate(() => {
const div = document.querySelector('div'); 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.$('span')).toBeTruthy();
expect(await divHandle.$eval('span', e => e.textContent)).toBe('hello'); 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 context = await browser.newContext({ viewport: { width: 350, height: 360 } });
const page = await context.newPage(); const page = await context.newPage();
await page.goto(server.PREFIX + '/grid.html'); 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); const error = await page.screenshot({ fullPage: true, __testHookBeforeScreenshot } as any).catch(e => e);
expect(error.message).toContain('oh my'); expect(error.message).toContain('oh my');
await utils.verifyViewport(page, 350, 360); 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(); const page = await context.newPage();
await page.setContent(`<div style="width:600px;height:600px;"></div>`); await page.setContent(`<div style="width:600px;height:600px;"></div>`);
const elementHandle = await page.$('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); const error = await elementHandle.screenshot({ __testHookBeforeScreenshot } as any).catch(e => e);
expect(error.message).toContain('oh my'); expect(error.message).toContain('oh my');
await utils.verifyViewport(page, 350, 360); await utils.verifyViewport(page, 350, 360);

View file

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

View file

@ -131,7 +131,7 @@ it('should change focused iframe', async({page, server}) => {
function logger() { function logger() {
self['_events'] = []; self['_events'] = [];
const element = document.querySelector('input'); 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([ await Promise.all([
frame1.evaluate(logger), 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.$eval('#i2', i2 => (i2 as HTMLInputElement).addEventListener('focus', window['focusEvent']));
await page.focus('#i1'); await page.focus('#i1');
await page.keyboard.type("First"); await page.keyboard.type('First');
await page.keyboard.press("Tab"); await page.keyboard.press('Tab');
await page.keyboard.type("Last"); await page.keyboard.type('Last');
expect(focused).toBe(true); expect(focused).toBe(true);
expect(await page.$eval('#i1', e => (e as HTMLInputElement).value)).toBe('First'); 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 page.goto(server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE); await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
expect(page.frames().length).toBe(2); expect(page.frames().length).toBe(2);
await page.frames()[0].evaluate(() => window["FOO"] = 'foo'); await page.frames()[0].evaluate(() => window['FOO'] = 'foo');
await page.frames()[1].evaluate(() => window["FOO"] = 'bar'); await page.frames()[1].evaluate(() => window['FOO'] = 'bar');
expect(await page.frames()[0].evaluate(() => window["FOO"])).toBe('foo'); expect(await page.frames()[0].evaluate(() => window['FOO'])).toBe('foo');
expect(await page.frames()[1].evaluate(() => window["FOO"])).toBe('bar'); expect(await page.frames()[1].evaluate(() => window['FOO'])).toBe('bar');
}); });
it('should have correct execution contexts', async ({ page, server }) => { 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(); expect(frame1 !== frame2).toBeTruthy();
await Promise.all([ await Promise.all([
frame1.evaluate(() => window["a"] = 1), frame1.evaluate(() => window['a'] = 1),
frame2.evaluate(() => window["a"] = 2) frame2.evaluate(() => window['a'] = 2)
]); ]);
const [a1, a2] = await Promise.all([ const [a1, a2] = await Promise.all([
frame1.evaluate(() => window['a']), frame1.evaluate(() => window['a']),

View file

@ -22,7 +22,7 @@ import utils from './utils';
it('should work', async ({page, server}) => { it('should work', async ({page, server}) => {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const frame1 = await utils.attachFrame(page, 'frame1', 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 frame3 = await utils.attachFrame(page, 'frame3', server.EMPTY_PAGE);
const frame1handle1 = await page.$('#frame1'); const frame1handle1 = await page.$('#frame1');
const frame1handle2 = await frame1.frameElement(); 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>`); 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}) => { 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 }); await context.setGeolocation({ longitude: 10, latitude: 10 });
const [popup] = await Promise.all([ const [popup] = await Promise.all([
page.waitForEvent('popup'), 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(); await popup.waitForLoadState();
const geolocation = await popup.evaluate(() => window['geolocationPromise']); 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 browser = await browserType.launch({...defaultBrowserOptions, headless: false });
{ {
const browserContext = await browser.newContext(); const browserContext = await browser.newContext();
const page = await browserContext.newPage(); await browserContext.newPage();
await browserContext.close(); await browserContext.close();
} }
{ {
const browserContext = await browser.newContext(); const browserContext = await browser.newContext();
const page = await browserContext.newPage(); await browserContext.newPage();
await browserContext.close(); await browserContext.close();
} }
await browser.close(); await browser.close();
@ -112,14 +112,14 @@ it('should(not) block third party cookies', async({browserType, defaultBrowserOp
if (allowsThirdParty) { if (allowsThirdParty) {
expect(cookies).toEqual([ expect(cookies).toEqual([
{ {
"domain": "127.0.0.1", 'domain': '127.0.0.1',
"expires": -1, 'expires': -1,
"httpOnly": false, 'httpOnly': false,
"name": "username", 'name': 'username',
"path": "/", 'path': '/',
"sameSite": "None", 'sameSite': 'None',
"secure": false, 'secure': false,
"value": "John Doe" 'value': 'John Doe'
} }
]); ]);
} else { } 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}) => { it('Page.bringToFront should work', async ({browserType, defaultBrowserOptions}) => {
const browser = await browserType.launch({...defaultBrowserOptions, headless: false }); const browser = await browserType.launch({...defaultBrowserOptions, headless: false });
const page1 = await browser.newPage(); const page1 = await browser.newPage();
await page1.setContent('Page1') await page1.setContent('Page1');
const page2 = await browser.newPage(); const page2 = await browser.newPage();
await page2.setContent('Page2') await page2.setContent('Page2');
await page1.bringToFront(); await page1.bringToFront();
expect(await page1.evaluate('document.visibilityState')).toBe('visible'); 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}) => { it('should intercept after a service worker', async ({browser, page, server, context}) => {
await page.goto(server.PREFIX + '/serviceworkers/fetchdummy/sw.html'); await page.goto(server.PREFIX + '/serviceworkers/fetchdummy/sw.html');
await page.evaluate(() => window["activationPromise"]); await page.evaluate(() => window['activationPromise']);
// Sanity check. // Sanity check.
const swResponse = await page.evaluate(() => window["fetchDummy"]('foo')); const swResponse = await page.evaluate(() => window['fetchDummy']('foo'));
expect(swResponse).toBe('responseFromServiceWorker:foo'); expect(swResponse).toBe('responseFromServiceWorker:foo');
await page.route('**/foo', route => { 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. // 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'); expect(swResponse2).toBe('responseFromServiceWorker:foo');
// Page route is not applied to service worker initiated fetch. // 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'); 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}) => { 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 // Occasionally times out on options.FIREFOX on Windows: https://github.com/microsoft/playwright/pull/1911/checks?check_run_id=607149016
await page.evaluate(() => { await page.evaluate(() => {
window["clickPromise"] = new Promise(resolve => { window['clickPromise'] = new Promise(resolve => {
document.addEventListener('click', event => { document.addEventListener('click', event => {
resolve({ resolve({
type: event.type, 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); 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.type).toBe('click');
expect(event.detail).toBe(1); expect(event.detail).toBe(1);
expect(event.clientX).toBe(50); 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}) => { it('should dblclick the div', async ({page, server}) => {
await page.setContent(`<div style='width: 100px; height: 100px;'>Click me</div>`); await page.setContent(`<div style='width: 100px; height: 100px;'>Click me</div>`);
await page.evaluate(() => { await page.evaluate(() => {
window["dblclickPromise"] = new Promise(resolve => { window['dblclickPromise'] = new Promise(resolve => {
document.querySelector('div').addEventListener('dblclick', event => { document.querySelector('div').addEventListener('dblclick', event => {
resolve({ resolve({
type: event.type, type: event.type,
@ -70,7 +70,7 @@ it('should dblclick the div', async({page, server}) => {
}); });
}); });
await page.mouse.dblclick(50, 60); 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.type).toBe('dblclick');
expect(event.detail).toBe(2); expect(event.detail).toBe(2);
expect(event.clientX).toBe(50); 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}) => { it('should set modifier keys on click', async ({page, server}) => {
await page.goto(server.PREFIX + '/input/scrollable.html'); 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'}; const modifiers = {'Shift': 'shiftKey', 'Control': 'ctrlKey', 'Alt': 'altKey', 'Meta': 'metaKey'};
// In Firefox, the Meta modifier only exists on Mac // In Firefox, the Meta modifier only exists on Mac
if (options.FIREFOX && !MAC) if (options.FIREFOX && !MAC)
@ -132,13 +132,13 @@ it('should set modifier keys on click', async({page, server}) => {
for (const modifier in modifiers) { for (const modifier in modifiers) {
await page.keyboard.down(modifier); await page.keyboard.down(modifier);
await page.click('#button-3'); 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'); throw new Error(modifiers[modifier] + ' should be true');
await page.keyboard.up(modifier); await page.keyboard.up(modifier);
} }
await page.click('#button-3'); await page.click('#button-3');
for (const modifier in modifiers) { 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'); 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.evaluate(() => new Promise(requestAnimationFrame));
await page.mouse.move(100, 100); await page.mouse.move(100, 100);
await page.evaluate(() => { await page.evaluate(() => {
window["result"] = []; window['result'] = [];
document.addEventListener('mousemove', event => { 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}); 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.goto(server.CROSS_PROCESS_PREFIX + '/mobile.html');
await page.evaluate(() => { await page.evaluate(() => {
document.addEventListener('click', event => { 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.hover('#target');
await page.mouse.up(); await page.mouse.up();
expect(await page.$eval('#target', target => target.contains(document.querySelector('#source')))).toBe(true); // could not find source in target 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; let request = null;
page.on('request', r => request = r); page.on('request', r => request = r);
await page.evaluate(async () => { 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(); expect(request).toBeTruthy();
const buffer = request.postDataBuffer(); 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()); await page.route('/post', route => route.continue());
page.on('request', r => request = r); page.on('request', r => request = r);
await page.evaluate(async () => { 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(); expect(request).toBeTruthy();
const buffer = request.postDataBuffer(); const buffer = request.postDataBuffer();
@ -126,7 +126,7 @@ it('should parse the json post data', async ({ page, server }) => {
page.on('request', r => request = r); page.on('request', r => request = r);
await page.evaluate(() => fetch('./post', { method: 'POST', body: JSON.stringify({ foo: 'bar' }) })); await page.evaluate(() => fetch('./post', { method: 'POST', body: JSON.stringify({ foo: 'bar' }) }));
expect(request).toBeTruthy(); 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}) => { 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]'); await page.click('input[type=submit]');
expect(request).toBeTruthy(); expect(request).toBeTruthy();
expect(request.postDataJSON()).toEqual({'foo': 'bar','baz': '123'}); expect(request.postDataJSON()).toEqual({'foo': 'bar','baz': '123'});
}) });
it('should be |undefined| when there is no post data', async ({ page, server }) => { it('should be |undefined| when there is no post data', async ({ page, server }) => {
const response = await page.goto(server.EMPTY_PAGE); 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 }) => { it('should evaluate before anything else on the page', async ({ page, server }) => {
await page.addInitScript(function() { await page.addInitScript(function() {
window["injected"] = 123; window['injected'] = 123;
}); });
await page.goto(server.PREFIX + '/tamperable.html'); 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 }) => { it('should work with a path', async ({ page, server }) => {
await page.addInitScript({ path: path.join(__dirname, 'assets/injectedfile.js') }); await page.addInitScript({ path: path.join(__dirname, 'assets/injectedfile.js') });
await page.goto(server.PREFIX + '/tamperable.html'); 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 }) => { it('should work with content', async ({ page, server }) => {
await page.addInitScript({ content: 'window["injected"] = 123' }); await page.addInitScript({ content: 'window["injected"] = 123' });
await page.goto(server.PREFIX + '/tamperable.html'); 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 }) => { 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 }) => { it('should work with browser context scripts', async ({ browser, server }) => {
const context = await browser.newContext(); const context = await browser.newContext();
await context.addInitScript(() => window["temp"] = 123); await context.addInitScript(() => window['temp'] = 123);
const page = await context.newPage(); 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'); 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(); 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') }); await context.addInitScript({ path: path.join(__dirname, 'assets/injectedfile.js') });
const page = await context.newPage(); const page = await context.newPage();
await page.goto(server.PREFIX + '/tamperable.html'); 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(); await context.close();
}); });
it('should work with browser context scripts for already created pages', async ({ browser, server }) => { it('should work with browser context scripts for already created pages', async ({ browser, server }) => {
const context = await browser.newContext(); const context = await browser.newContext();
const page = await context.newPage(); const page = await context.newPage();
await context.addInitScript(() => window["temp"] = 123); await context.addInitScript(() => window['temp'] = 123);
await page.addInitScript(() => window["injected"] = window["temp"]); await page.addInitScript(() => window['injected'] = window['temp']);
await page.goto(server.PREFIX + '/tamperable.html'); 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(); await context.close();
}); });
it('should support multiple scripts', async ({ page, server }) => { it('should support multiple scripts', async ({ page, server }) => {
await page.addInitScript(function() { await page.addInitScript(function() {
window["script1"] = 1; window['script1'] = 1;
}); });
await page.addInitScript(function() { await page.addInitScript(function() {
window["script2"] = 2; window['script2'] = 2;
}); });
await page.goto(server.PREFIX + '/tamperable.html'); await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window["script1"])).toBe(1); expect(await page.evaluate(() => window['script1'])).toBe(1);
expect(await page.evaluate(() => window["script2"])).toBe(2); expect(await page.evaluate(() => window['script2'])).toBe(2);
}); });
it('should work with CSP', async ({ page, server }) => { it('should work with CSP', async ({ page, server }) => {
server.setCSP('/empty.html', 'script-src ' + server.PREFIX); server.setCSP('/empty.html', 'script-src ' + server.PREFIX);
await page.addInitScript(function() { await page.addInitScript(function() {
window["injected"] = 123; window['injected'] = 123;
}); });
await page.goto(server.PREFIX + '/empty.html'); 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. // Make sure CSP works.
await page.addScriptTag({ content: 'window.e = 10;' }).catch(e => void e); 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 }) => { it('should work after a cross origin navigation', async ({ page, server }) => {
await page.goto(server.CROSS_PROCESS_PREFIX); await page.goto(server.CROSS_PROCESS_PREFIX);
await page.addInitScript(function() { await page.addInitScript(function() {
window["injected"] = 123; window['injected'] = 123;
}); });
await page.goto(server.PREFIX + '/tamperable.html'); 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'); await page.goto(server.EMPTY_PAGE + '#hash');
expect(page.url()).toBe(server.EMPTY_PAGE + '#hash'); expect(page.url()).toBe(server.EMPTY_PAGE + '#hash');
await page.evaluate(() => { await page.evaluate(() => {
window.location.hash = "dynamic"; window.location.hash = 'dynamic';
}); });
expect(page.url()).toBe(server.EMPTY_PAGE + '#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 userAgent = await page.evaluate(() => navigator.userAgent);
const [ const [
part1, part1,
part2, /* part2 */,
part3, part3,
part4, part4,
part5, 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 }) => { it.fail(options.FIREFOX)('frame.focus should work multiple times', async ({ context, server }) => {
const page1 = await context.newPage() const page1 = await context.newPage();
const page2 = await context.newPage() const page2 = await context.newPage();
for (const page of [page1, page2]) { for (const page of [page1, page2]) {
await page.setContent(`<button id="foo" onfocus="window.gotFocus=true"></button>`) await page.setContent(`<button id="foo" onfocus="window.gotFocus=true"></button>`);
await page.focus("#foo") await page.focus('#foo');
expect(await page.evaluate(() => !!window['gotFocus'])).toBe(true) expect(await page.evaluate(() => !!window['gotFocus'])).toBe(true);
} }
}); });

View file

@ -15,7 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { options } from './playwright.fixtures'; import './playwright.fixtures';
import utils from './utils'; import utils from './utils';
it('should emulate type', async ({page, server}) => { 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); 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)'); 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)'); 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)'); 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) { finally(f) {
return wrap(this._promise.finally(f)); return wrap(this._promise.finally(f));
} }
}; }
const wrap = p => { const wrap = p => {
const result = new Promise2(() => { }); const result = new Promise2(() => { });
result._promise = p; result._promise = p;
@ -261,13 +261,13 @@ it('should work with overwritten Promise', async ({ page, server }) => {
}; };
// @ts-ignore; // @ts-ignore;
window.Promise = Promise2; window.Promise = Promise2;
window["__Promise2"] = Promise2; window['__Promise2'] = Promise2;
}); });
// Sanity check. // Sanity check.
expect(await page.evaluate(() => { expect(await page.evaluate(() => {
const p = Promise.all([Promise.race([]), new Promise(() => { }).then(() => { })]); const p = Promise.all([Promise.race([]), new Promise(() => { }).then(() => { })]);
return p instanceof window["__Promise2"]; return p instanceof window['__Promise2'];
})).toBe(true); })).toBe(true);
// Now, the new promise should be awaitable. // 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; let error;
await f().catch(e => error = e); await f().catch(e => error = e);
expect('' + error).toContain('Too many arguments'); expect('' + error).toContain('Too many arguments');
} };
// @ts-ignore // @ts-ignore
await expectThrow(() => page.evaluate((a, b) => false, 1, 2)); await expectThrow(() => page.evaluate((a, b) => false, 1, 2));
// @ts-ignore // @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 }) => { it('should respect use strict expression', async ({ page, server }) => {
const error = await page.evaluate(() => { const error = await page.evaluate(() => {
"use strict"; 'use strict';
// @ts-ignore // @ts-ignore
variableY = 3.14; variableY = 3.14;
// @ts-ignore // @ts-ignore

View file

@ -43,7 +43,7 @@ it('should use text() for inspection', async({page}) => {
let text; let text;
const inspect = value => { const inspect = value => {
text = util.inspect(value); text = util.inspect(value);
} };
page.on('console', inspect); page.on('console', inspect);
await page.evaluate(() => console.log('Hello world')); await page.evaluate(() => console.log('Hello world'));
expect(text).toEqual('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 () => { page.evaluate(async () => {
// 1. Create a popup that Playwright is not connected to. // 1. Create a popup that Playwright is not connected to.
const win = window.open(''); const win = window.open('');
window["_popup"] = win; window['_popup'] = win;
if (window.document.readyState !== 'complete') if (window.document.readyState !== 'complete')
await new Promise(f => window.addEventListener('load', f)); await new Promise(f => window.addEventListener('load', f));
// 2. In this popup, create an iframe that console.logs a message. // 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')); page.on('response', response => events.push('response'));
const response = await page.goto(server.EMPTY_PAGE); const response = await page.goto(server.EMPTY_PAGE);
expect(await response.finished()).toBe(null); expect(await response.finished()).toBe(null);
events.push('requestfinished') events.push('requestfinished');
expect(events).toEqual(['request', 'response', 'requestfinished']); expect(events).toEqual(['request', 'response', 'requestfinished']);
}); });

View file

@ -21,7 +21,7 @@ it('should work', async({browser}) => {
const page = await context.newPage(); const page = await context.newPage();
const [popup] = await Promise.all([ const [popup] = await Promise.all([
page.waitForEvent('popup'), 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 page.evaluate(() => !!window.opener)).toBe(false);
expect(await popup.evaluate(() => !!window.opener)).toBe(true); 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); await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([ const [popup] = await Promise.all([
page.waitForEvent('popup'), 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 page.evaluate(() => !!window.opener)).toBe(false);
expect(await popup.evaluate(() => !!window.opener)).toBe(true); 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 page = await context.newPage();
const [popup] = await Promise.all([ const [popup] = await Promise.all([
page.waitForEvent('popup'), 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 page.evaluate(() => !!window.opener)).toBe(false);
expect(await popup.evaluate(() => !!window.opener)).toBe(true); 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 page = await context.newPage();
const [popup] = await Promise.all([ const [popup] = await Promise.all([
page.waitForEvent('popup'), 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. // Chromium reports `about:blank#blocked` here.
expect(popup.url().split('#')[0]).toBe('about:blank'); 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 page = await context.newPage();
const [popup] = await Promise.all([ const [popup] = await Promise.all([
page.waitForEvent('popup'), 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 page.evaluate(() => !!window.opener)).toBe(false);
expect(await popup.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); await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([ const [popup] = await Promise.all([
page.waitForEvent('popup'), 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 page.evaluate(() => !!window.opener)).toBe(false);
expect(await popup.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}) => { it('should report requests and responses handled by service worker', async ({page, server}) => {
await page.goto(server.PREFIX + '/serviceworkers/fetchdummy/sw.html'); 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([ const [swResponse, request] = await Promise.all([
page.evaluate(() => window["fetchDummy"]('foo')), page.evaluate(() => window['fetchDummy']('foo')),
page.waitForEvent('request'), page.waitForEvent('request'),
]); ]);
expect(swResponse).toBe('responseFromServiceWorker:foo'); 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 () => { const {message, stack} = await page.evaluate(async () => {
try { try {
await window["woof"](); await window['woof']();
} catch (e) { } catch (e) {
return {message: e.message, stack: e.stack}; 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 () => { const thrown = await page.evaluate(async () => {
try { try {
await window["woof"](); await window['woof']();
} catch (e) { } catch (e) {
return e; return e;
} }
@ -95,7 +95,7 @@ it('should be callable from-inside addInitScript', async({page, server}) => {
await page.exposeFunction('woof', function() { await page.exposeFunction('woof', function() {
called = true; called = true;
}); });
await page.addInitScript(() => window["woof"]()); await page.addInitScript(() => window['woof']());
await page.reload(); await page.reload();
expect(called).toBe(true); 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}) => { 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}); 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}) => { 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.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'); 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}) => { it('page.reload should work', async ({page, server}) => {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => window["_foo"] = 10); await page.evaluate(() => window['_foo'] = 10);
await page.reload(); 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}) => { 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), server.waitForRequest(suffix),
(frame['_page'] as Page).waitForRequest(server.PREFIX + suffix), (frame['_page'] as Page).waitForRequest(server.PREFIX + suffix),
]); ]);
} };
let responses = {}; const responses = {};
// Hold on to a bunch of requests without answering. // Hold on to a bunch of requests without answering.
server.setRoute('/fetch-request-a.js', (req, res) => responses['a'] = res); server.setRoute('/fetch-request-a.js', (req, res) => responses['a'] = res);
const firstFetchResourceRequested = waitForRequest('/fetch-request-a.js'); 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(actionFinished).toBe(false);
expect(responses['a']).toBeTruthy(); expect(responses['a']).toBeTruthy();
let timer;
let timerTriggered = false;
// Finishing response should trigger the second round. // Finishing response should trigger the second round.
finishResponse(responses['a']); finishResponse(responses['a']);
@ -70,7 +68,8 @@ async function networkIdleTest(frame: Frame, server: TestServer, action: () => P
await secondFetchResourceRequested; await secondFetchResourceRequested;
expect(actionFinished).toBe(false); expect(actionFinished).toBe(false);
// Finishing the last response should trigger networkidle. // Finishing the last response should trigger networkidle.
timer = setTimeout(() => timerTriggered = true, 500); let timerTriggered = false;
const timer = setTimeout(() => timerTriggered = true, 500);
finishResponse(responses['d']); finishResponse(responses['d']);
const response = await actionPromise; 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}) => { it('should support cors with POST', async ({page, server}) => {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.route('**/cars', async (route) => { await page.route('**/cars', async route => {
await route.fulfill({ await route.fulfill({
contentType: 'application/json', contentType: 'application/json',
headers: { 'Access-Control-Allow-Origin': '*' }, 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}) => { it('should support cors with credentials', async ({page, server}) => {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.route('**/cars', async (route) => { await page.route('**/cars', async route => {
await route.fulfill({ await route.fulfill({
contentType: 'application/json', contentType: 'application/json',
headers: { headers: {
@ -494,7 +494,7 @@ it('should support cors with credentials', async({page, server}) => {
it('should reject cors with disallowed credentials', async ({page, server}) => { it('should reject cors with disallowed credentials', async ({page, server}) => {
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.route('**/cars', async (route) => { await page.route('**/cars', async route => {
await route.fulfill({ await route.fulfill({
contentType: 'application/json', contentType: 'application/json',
headers: { headers: {
@ -508,7 +508,7 @@ it('should reject cors with disallowed credentials', async({page, server}) => {
}); });
let error = ''; let error = '';
try { try {
const resp = await page.evaluate(async () => { await page.evaluate(async () => {
const response = await fetch('https://example.com/cars', { const response = await fetch('https://example.com/cars', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, 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']); 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 page.$eval('select', select => select.addEventListener('input', () => window.location.href = '/empty.html'));
await Promise.all([ await Promise.all([
page.selectOption('select', 'blue'), 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}) => { it('should not allow null items',async ({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html'); await page.goto(server.PREFIX + '/input/select.html');
await page.evaluate(() => window['makeMultiple']()); await page.evaluate(() => window['makeMultiple']());
let error = null let error = null;
await page.selectOption('select', ['blue', null, 'black','magenta']).catch(e => error = e); await page.selectOption('select', ['blue', null, 'black','magenta']).catch(e => error = e);
expect(error.message).toContain('options[1]: expected object, got null'); 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 => { const listener = chooser => {
page.off('filechooser', listener); page.off('filechooser', listener);
f(chooser); f(chooser);
} };
page.on('filechooser', listener); page.on('filechooser', listener);
}), }),
page.click('input'), page.click('input'),
@ -86,7 +86,7 @@ it('should emit event addListener/removeListener', async({page, server}) => {
const listener = chooser => { const listener = chooser => {
page.removeListener('filechooser', listener); page.removeListener('filechooser', listener);
f(chooser); f(chooser);
} };
page.addListener('filechooser', listener); page.addListener('filechooser', listener);
}), }),
page.click('input'), page.click('input'),
@ -185,7 +185,7 @@ it('should detect mime type', async({page, server}) => {
<input type="file" name="file1"> <input type="file" name="file1">
<input type="file" name="file2"> <input type="file" name="file2">
<input type="submit" value="Submit"> <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=file1]')).setInputFiles(path.join(__dirname, '/assets/file-to-upload.txt'));
await (await page.$('input[name=file2]')).setInputFiles(path.join(__dirname, '/assets/pptr.png')); await (await page.$('input[name=file2]')).setInputFiles(path.join(__dirname, '/assets/pptr.png'));
await Promise.all([ 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); await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([ const [popup] = await Promise.all([
page.waitForEvent('popup'), 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. // The url is about:blank in FF.
// expect(popup.url()).toBe(server.EMPTY_PAGE); // 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([ const [popup] = await Promise.all([
page.waitForEvent('popup'), page.waitForEvent('popup'),
server.waitForRequest('/one-style.css'), 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; let resolved = false;
const loadSatePromise = popup.waitForLoadState().then(() => resolved = true); const loadSatePromise = popup.waitForLoadState().then(() => resolved = true);

View file

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

View file

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

View file

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

View file

@ -28,7 +28,7 @@ it('should inherit user agent from browser context', async function({browser, se
page.click('a'), page.click('a'),
]); ]);
await popup.waitForLoadState('domcontentloaded'); await popup.waitForLoadState('domcontentloaded');
const userAgent = await popup.evaluate(() => window["initialUserAgent"]); const userAgent = await popup.evaluate(() => window['initialUserAgent']);
const request = await requestPromise; const request = await requestPromise;
await context.close(); await context.close();
expect(userAgent).toBe('hey'); expect(userAgent).toBe('hey');
@ -60,7 +60,7 @@ it('should inherit extra headers from browser context', async function({browser,
const page = await context.newPage(); const page = await context.newPage();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
const requestPromise = server.waitForRequest('/dummy.html'); 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; const request = await requestPromise;
await context.close(); await context.close();
expect(request.headers['foo']).toBe('bar'); 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); await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([ const [popup] = await Promise.all([
page.waitForEvent('popup'), 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'); await popup.waitForLoadState('domcontentloaded');
expect(await popup.title()).toBe('Woof-Woof'); 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([ await Promise.all([
page.waitForEvent('popup'), 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); expect(intercepted).toBe(true);
await context.close(); 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 }) => { it('should use socks proxy', async ({ browserType, defaultBrowserOptions }) => {
const server = socks.createServer((info, accept, deny) => { const server = socks.createServer((info, accept, deny) => {
let socket; let socket;
if (socket = accept(true)) { if ((socket = accept(true))) {
// Catch and ignore ECONNRESET errors. // Catch and ignore ECONNRESET errors.
socket.on('error', () => {}); socket.on('error', () => {});
const body = '<html><title>Served by the SOCKS proxy</title></html>'; const body = '<html><title>Served by the SOCKS proxy</title></html>';

View file

@ -33,7 +33,7 @@ class RemoteServer {
_output: Map<any, any>; _output: Map<any, any>;
_outputCallback: Map<any, any>; _outputCallback: Map<any, any>;
_browserType: BrowserType<Browser>; _browserType: BrowserType<Browser>;
_child: import("child_process").ChildProcess; _child: import('child_process').ChildProcess;
_exitPromise: Promise<unknown>; _exitPromise: Promise<unknown>;
_exitAndDisconnectPromise: Promise<any>; _exitAndDisconnectPromise: Promise<any>;
_browser: Browser; _browser: Browser;
@ -60,7 +60,7 @@ class RemoteServer {
...extraOptions, ...extraOptions,
}; };
this._child = spawn('node', [path.join(__dirname, 'fixtures', 'closeme.js'), JSON.stringify(options)]); 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._exitPromise = new Promise(resolve => this._child.on('exit', (exitCode, signal) => {
this._didExit = true; this._didExit = true;
resolve(exitCode); resolve(exitCode);
@ -72,7 +72,7 @@ class RemoteServer {
// Uncomment to debug. // Uncomment to debug.
// console.log(data.toString()); // console.log(data.toString());
let match; let match;
while (match = outputString.match(/\(([^()]+)=>([^()]+)\)/)) { while ((match = outputString.match(/\(([^()]+)=>([^()]+)\)/))) {
const key = match[1]; const key = match[1];
const value = match[2]; const value = match[2];
this._addOutput(key, value); 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'); }, server.CROSS_PROCESS_PREFIX + '/something');
expect(text).toBe('done'); expect(text).toBe('done');
let playwrightRequest;
await page.route(server.CROSS_PROCESS_PREFIX + '/something', (route, request) => { await page.route(server.CROSS_PROCESS_PREFIX + '/something', (route, request) => {
playwrightRequest = request;
route.continue({ route.continue({
headers: { headers: {
...request.headers() ...request.headers()

View file

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

View file

@ -25,8 +25,8 @@ async function checkSlowMo(toImpl, page, task) {
throw new Error('already did slowmo'); throw new Error('already did slowmo');
await new Promise(x => setTimeout(x, 100)); await new Promise(x => setTimeout(x, 100));
didSlowMo = true; didSlowMo = true;
return orig.call(this, ...args) return orig.call(this, ...args);
} };
await task(); await task();
expect(!!didSlowMo).toBe(true); expect(!!didSlowMo).toBe(true);
} }
@ -41,7 +41,7 @@ async function checkPageSlowMo(toImpl, page, task) {
<option>foo</option> <option>foo</option>
</select> </select>
<input type="file" class="file"> <input type="file" class="file">
`) `);
await checkSlowMo(toImpl, page, task); await checkSlowMo(toImpl, page, task);
} }
@ -120,7 +120,7 @@ async function checkFrameSlowMo(toImpl, page, server, task) {
<option>foo</option> <option>foo</option>
</select> </select>
<input type="file" class="file"> <input type="file" class="file">
`) `);
await checkSlowMo(toImpl, page, task.bind(null, frame)); await checkSlowMo(toImpl, page, task.bind(null, frame));
} }
@ -189,7 +189,7 @@ async function checkElementSlowMo(toImpl, page, selector, task) {
<option>foo</option> <option>foo</option>
</select> </select>
<input type="file" class="file"> <input type="file" class="file">
`) `);
const element = await page.$(selector); const element = await page.$(selector);
await checkSlowMo(toImpl, page, task.bind(null, element)); 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}) => { it('should disable timeout when its set to 0', async ({page}) => {
const watchdog = page.waitForFunction(() => { const watchdog = page.waitForFunction(() => {
window['__counter'] = (window['__counter'] || 0) + 1; window['__counter'] = (window['__counter'] || 0) + 1;
return window["__injected"]; return window['__injected'];
}, {}, {timeout: 0, polling: 10}); }, {}, {timeout: 0, polling: 10});
await page.waitForFunction(() => window['__counter'] > 10); await page.waitForFunction(() => window['__counter'] > 10);
await page.evaluate(() => window["__injected"] = true); await page.evaluate(() => window['__injected'] = true);
await watchdog; await watchdog;
}); });

View file

@ -18,11 +18,6 @@
import './playwright.fixtures'; import './playwright.fixtures';
import utils from './utils'; 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)); const addElement = tag => document.body.appendChild(document.createElement(tag));
it('should survive cross-process navigation', async ({page, server}) => { it('should survive cross-process navigation', async ({page, server}) => {