chore(tests): convert all tests to typescript (#3384)

This commit is contained in:
Joel Einbinder 2020-08-11 15:50:53 -07:00 committed by GitHub
parent 9375cc62b8
commit 6054f14794
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
97 changed files with 662 additions and 628 deletions

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, WEBKIT} = testOptions;

View file

@ -1,7 +1,7 @@
<script>
let h1 = null;
let button = null;
window.button = null;
let clicked = false;
window.addEventListener('DOMContentLoaded', () => {

View file

@ -24,8 +24,8 @@ it('should bypass CSP meta tag', async({browser, server}) => {
const context = await browser.newContext();
const page = await context.newPage();
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await page.evaluate('window.__injected')).toBe(undefined);
await page.addScriptTag({content: 'window["__injected"] = 42;'}).catch(e => void e);
expect(await page.evaluate('window["__injected"]')).toBe(undefined);
await context.close();
}
@ -34,8 +34,8 @@ it('should bypass CSP meta tag', async({browser, server}) => {
const context = await browser.newContext({ bypassCSP: true });
const page = await context.newPage();
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate('window.__injected')).toBe(42);
await page.addScriptTag({content: 'window["__injected"] = 42;'});
expect(await page.evaluate('window["__injected"]')).toBe(42);
await context.close();
}
});
@ -48,8 +48,8 @@ it('should bypass CSP header', async({browser, server}) => {
const context = await browser.newContext();
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await page.evaluate('window.__injected')).toBe(undefined);
await page.addScriptTag({content: 'window["__injected"] = 42;'}).catch(e => void e);
expect(await page.evaluate('window["__injected"]')).toBe(undefined);
await context.close();
}
@ -58,8 +58,8 @@ it('should bypass CSP header', async({browser, server}) => {
const context = await browser.newContext({ bypassCSP: true });
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate('window.__injected')).toBe(42);
await page.addScriptTag({content: 'window["__injected"] = 42;'});
expect(await page.evaluate('window["__injected"]')).toBe(42);
await context.close();
}
});
@ -68,12 +68,12 @@ it('should bypass after cross-process navigation', async({browser, server}) => {
const context = await browser.newContext({ bypassCSP: true });
const page = await context.newPage();
await page.goto(server.PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate('window.__injected')).toBe(42);
await page.addScriptTag({content: 'window["__injected"] = 42;'});
expect(await page.evaluate('window["__injected"]')).toBe(42);
await page.goto(server.CROSS_PROCESS_PREFIX + '/csp.html');
await page.addScriptTag({content: 'window.__injected = 42;'});
expect(await page.evaluate('window.__injected')).toBe(42);
await page.addScriptTag({content: 'window["__injected"] = 42;'});
expect(await page.evaluate('window["__injected"]')).toBe(42);
await context.close();
});
@ -84,8 +84,8 @@ it('should bypass CSP in iframes as well', async({browser, server}) => {
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
const frame = await utils.attachFrame(page, 'frame1', server.PREFIX + '/csp.html');
await frame.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await frame.evaluate('window.__injected')).toBe(undefined);
await frame.addScriptTag({content: 'window["__injected"] = 42;'}).catch(e => void e);
expect(await frame.evaluate('window["__injected"]')).toBe(undefined);
await context.close();
}
@ -95,8 +95,8 @@ it('should bypass CSP in iframes as well', async({browser, server}) => {
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
const frame = await utils.attachFrame(page, 'frame1', server.PREFIX + '/csp.html');
await frame.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);
expect(await frame.evaluate('window.__injected')).toBe(42);
await frame.addScriptTag({content: 'window["__injected"] = 42;'}).catch(e => void e);
expect(await frame.evaluate('window["__injected"]')).toBe(42);
await context.close();
}
});

View file

@ -72,9 +72,9 @@ it('should be callable from-inside addInitScript', async({browser, server}) => {
await context.exposeFunction('woof', function(arg) {
args.push(arg);
});
await context.addInitScript('woof("context")');
await context.addInitScript('window["woof"]("context")');
const page = await context.newPage();
await page.addInitScript('woof("page")');
await page.addInitScript('window["woof"]("page")');
args = [];
await page.reload();
expect(args).toEqual(['context', 'page']);

View file

@ -83,7 +83,7 @@ it('should format number in popups', async({browser, server}) => {
page.evaluate(url => window.open(url), server.PREFIX + '/formatted-number.html'),
]);
await popup.waitForLoadState('domcontentloaded');
const result = await popup.evaluate('window.result');
const result = await popup.evaluate('window["result"]');
expect(result).toBe('1 000 000,5');
await context.close();
});

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const fs = require('fs');
const utils = require('./utils');
import path from 'path';
import fs from 'fs';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS, CHANNEL} = testOptions;
it('should work', async({browserType, defaultBrowserOptions, toImpl}) => {
@ -71,11 +71,11 @@ it('should return child_process instance', async ({browserType, defaultBrowserOp
it('should fire close event', async ({browserType, defaultBrowserOptions}) => {
const browserServer = await browserType.launchServer(defaultBrowserOptions);
const [result] = await Promise.all([
new Promise(f => browserServer.on('close', (exitCode, signal) => f({ exitCode, signal }))),
new Promise(f => (browserServer as any).on('close', (exitCode, signal) => f({ exitCode, signal }))),
browserServer.close(),
]);
expect(result.exitCode).toBe(0);
expect(result.signal).toBe(null);
expect(result['exitCode']).toBe(0);
expect(result['signal']).toBe(null);
});
it('should reject navigation when browser closes', async({browserType, defaultBrowserOptions, server, toImpl}) => {
@ -117,7 +117,7 @@ it('should throw if used after disconnect', async({browserType, defaultBrowserOp
const page = await remote.newPage();
await remote.close();
const error = await page.evaluate('1 + 1').catch(e => e);
expect(error.message).toContain('has been closed');
expect((error as Error).message).toContain('has been closed');
if (toImpl)
await toImpl(browserServer)._checkLeaks();
await browserServer.close();
@ -129,7 +129,7 @@ it('should emit close events on pages and contexts', async({browserType, default
const context = await remote.newContext();
const page = await context.newPage();
let pageClosed = false;
page.on('close', e => pageClosed = true);
page.on('close', () => pageClosed = true);
await Promise.all([
new Promise(f => context.on('close', f)),
browserServer.close()

View file

@ -17,7 +17,7 @@
import './base.fixture';
import utils from './utils';
import { ChromiumBrowser } from '../types/types';
import { ChromiumBrowser } from '..';
const { FFOX, CHROMIUM, WEBKIT, WIN, CHANNEL } = testOptions;
it.skip(!CHANNEL)('should work', async({browser}) => {

View file

@ -13,13 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('../base.fixture');
import '../base.fixture';
import { ChromiumBrowserContext } from '../..';
const {FFOX, CHROMIUM, WEBKIT, CHANNEL} = testOptions;
it.skip(!CHROMIUM)('should create a worker from a service worker', async({page, server, context}) => {
const [worker] = await Promise.all([
context.waitForEvent('serviceworker'),
(context as ChromiumBrowserContext).waitForEvent('serviceworker'),
page.goto(server.PREFIX + '/serviceworkers/empty/sw.html')
]);
expect(await worker.evaluate(() => self.toString())).toBe('[object ServiceWorkerGlobalScope]');
@ -27,17 +28,17 @@ it.skip(!CHROMIUM)('should create a worker from a service worker', async({page,
it.skip(!CHROMIUM)('serviceWorkers() should return current workers', async({page, server, context}) => {
const [worker1] = await Promise.all([
context.waitForEvent('serviceworker'),
(context as ChromiumBrowserContext).waitForEvent('serviceworker'),
page.goto(server.PREFIX + '/serviceworkers/empty/sw.html')
]);
let workers = context.serviceWorkers();
let workers = (context as ChromiumBrowserContext).serviceWorkers();
expect(workers.length).toBe(1);
const [worker2] = await Promise.all([
context.waitForEvent('serviceworker'),
(context as ChromiumBrowserContext).waitForEvent('serviceworker'),
page.goto(server.CROSS_PROCESS_PREFIX + '/serviceworkers/empty/sw.html')
]);
workers = context.serviceWorkers();
workers = (context as ChromiumBrowserContext).serviceWorkers();
expect(workers.length).toBe(2);
expect(workers).toContain(worker1);
expect(workers).toContain(worker2);
@ -46,7 +47,7 @@ it.skip(!CHROMIUM)('serviceWorkers() should return current workers', async({page
it.skip(!CHROMIUM)('should not create a worker from a shared worker', async({page, server, context}) => {
await page.goto(server.EMPTY_PAGE);
let serviceWorkerCreated;
context.once('serviceworker', () => serviceWorkerCreated = true);
(context as ChromiumBrowserContext).once('serviceworker', () => serviceWorkerCreated = true);
await page.evaluate(() => {
new SharedWorker('data:text/javascript,console.log("hi")');
});
@ -54,7 +55,7 @@ it.skip(!CHROMIUM)('should not create a worker from a shared worker', async({pag
});
it.skip(!CHROMIUM)('should close service worker together with the context', async({browser, server}) => {
const context = await browser.newContext();
const context = await browser.newContext() as ChromiumBrowserContext;
const page = await context.newPage();
const [worker] = await Promise.all([
context.waitForEvent('serviceworker'),

View file

@ -13,10 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('../base.fixture');
import '../base.fixture';
const path = require('path');
const utils = require('../utils');
import path from 'path';
import utils from '../utils';
import { ChromiumBrowser, ChromiumBrowserContext } from '../..';
const {makeUserDataDir, removeUserDataDir} = utils;
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS} = testOptions;
@ -41,7 +42,7 @@ it.skip(!CHROMIUM || USES_HOOKS || WIN)('should open devtools when "devtools: tr
if (parsed.method === 'getPreferences')
devtoolsCallback();
};
const browser = await browserType.launch({...defaultBrowserOptions, headless: false, devtools: true, __testHookForDevTools});
const browser = await browserType.launch({...defaultBrowserOptions, headless: false, devtools: true, __testHookForDevTools} as any);
const context = await browser.newContext();
await Promise.all([
devtoolsPromise,
@ -60,7 +61,7 @@ it.skip(!CHROMIUM)('should return background pages', async({browserType, default
`--load-extension=${extensionPath}`,
],
};
const context = await browserType.launchPersistentContext(userDataDir, extensionOptions);
const context = await browserType.launchPersistentContext(userDataDir, extensionOptions) as ChromiumBrowserContext;
const backgroundPages = context.backgroundPages();
let backgroundPage = backgroundPages.length
? backgroundPages[0]
@ -74,7 +75,7 @@ it.skip(!CHROMIUM)('should return background pages', async({browserType, default
it.skip(!CHROMIUM)('should not create pages automatically', async ({browserType, defaultBrowserOptions}) => {
const browser = await browserType.launch(defaultBrowserOptions);
const browserSession = await browser.newBrowserCDPSession();
const browserSession = await (browser as ChromiumBrowser).newBrowserCDPSession();
const targets = [];
browserSession.on('Target.targetCreated', async ({targetInfo}) => {
if (targetInfo.type !== 'browser')

View file

@ -14,7 +14,7 @@
* limitations under the License.
*/
import '../base.fixture';
import { Page, Browser, BrowserContext } from '../../types/types';
import { Page, Browser, BrowserContext } from '../..';
const {FFOX, CHROMIUM, WEBKIT, CHANNEL} = testOptions;

View file

@ -13,23 +13,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('../base.fixture');
import '../base.fixture';
import { ChromiumBrowserContext, ChromiumBrowser } from "../../types/types";
const {FFOX, CHROMIUM, WEBKIT, CHANNEL, USES_HOOKS} = testOptions;
it.skip(!CHROMIUM)('should work', async function({page}) {
const client = await page.context().newCDPSession(page);
const client = await (page.context() as ChromiumBrowserContext).newCDPSession(page);
await Promise.all([
client.send('Runtime.enable'),
client.send('Runtime.evaluate', { expression: 'window.foo = "bar"' })
]);
const foo = await page.evaluate(() => window.foo);
const foo = await page.evaluate(() => window['foo']);
expect(foo).toBe('bar');
});
it.skip(!CHROMIUM)('should send events', async function({page, server}) {
const client = await page.context().newCDPSession(page);
const client = await (page.context() as ChromiumBrowserContext).newCDPSession(page);
await client.send('Network.enable');
const events = [];
client.on('Network.requestWillBeSent', event => events.push(event));
@ -38,12 +39,12 @@ it.skip(!CHROMIUM)('should send events', async function({page, server}) {
});
it.skip(!CHROMIUM)('should only accept a page', async function({page}) {
const error = await page.context().newCDPSession(page.context()).catch(e => e);
const error = await (page.context() as ChromiumBrowserContext).newCDPSession(page.context() as any).catch(e => e);
expect(error.message).toContain('page: expected Page');
});
it.skip(!CHROMIUM)('should enable and disable domains independently', async function({page}) {
const client = await page.context().newCDPSession(page);
const client = await (page.context() as ChromiumBrowserContext).newCDPSession(page);
await client.send('Runtime.enable');
await client.send('Debugger.enable');
// JS coverage enables and then disables Debugger domain.
@ -61,7 +62,7 @@ it.skip(!CHROMIUM)('should enable and disable domains independently', async func
});
it.skip(!CHROMIUM)('should be able to detach session', async function({page}) {
const client = await page.context().newCDPSession(page);
const client = await (page.context() as ChromiumBrowserContext).newCDPSession(page);
await client.send('Runtime.enable');
const evalResponse = await client.send('Runtime.evaluate', {expression: '1 + 2', returnByValue: true});
expect(evalResponse.result.value).toBe(3);
@ -76,27 +77,27 @@ it.skip(!CHROMIUM)('should be able to detach session', async function({page}) {
});
it.skip(!CHROMIUM)('should throw nice errors', async function({page}) {
const client = await page.context().newCDPSession(page);
const client = await (page.context() as ChromiumBrowserContext).newCDPSession(page);
const error = await theSourceOfTheProblems().catch(error => error);
expect(error.stack).toContain('theSourceOfTheProblems');
expect(error.message).toContain('ThisCommand.DoesNotExist');
async function theSourceOfTheProblems() {
await client.send('ThisCommand.DoesNotExist');
await client.send('ThisCommand.DoesNotExist' as any);
}
});
it.skip(!CHROMIUM)('should not break page.close()', async function({browser}) {
const context = await browser.newContext();
const page = await context.newPage();
const session = await page.context().newCDPSession(page);
const session = await (page.context() as ChromiumBrowserContext).newCDPSession(page);
await session.detach();
await page.close();
await context.close();
});
it.skip(!CHROMIUM)('should detach when page closes', async function({browser}) {
const context = await browser.newContext();
const context = await browser.newContext() as ChromiumBrowserContext;
const page = await context.newPage();
const session = await context.newCDPSession(page);
await page.close();
@ -107,7 +108,7 @@ it.skip(!CHROMIUM)('should detach when page closes', async function({browser}) {
});
it.skip(!CHROMIUM)('should work', async function({browser}) {
const session = await browser.newBrowserCDPSession();
const session = await (browser as ChromiumBrowser).newBrowserCDPSession();
const version = await session.send('Browser.getVersion');
expect(version.userAgent).toBeTruthy();

View file

@ -179,7 +179,7 @@ it('should support userAgent option', async ({server, launchPersistent}) => {
it('should support bypassCSP option', async ({server, launchPersistent}) => {
const {page, context} = await launchPersistent({bypassCSP: true});
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);
});

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, WEBKIT, CHANNEL} = testOptions;

View file

@ -13,23 +13,23 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS} = testOptions;
it('should dispatch click event', async({page, server}) => {
await page.goto(server.PREFIX + '/input/button.html');
await page.dispatchEvent('button', 'click');
expect(await page.evaluate(() => result)).toBe('Clicked');
expect(await page.evaluate(() => window['result'])).toBe('Clicked');
});
it('should dispatch click event properties', async({page, server}) => {
await page.goto(server.PREFIX + '/input/button.html');
await page.dispatchEvent('button', 'click');
expect(await page.evaluate(() => bubbles)).toBeTruthy();
expect(await page.evaluate(() => cancelable)).toBeTruthy();
expect(await page.evaluate(() => composed)).toBeTruthy();
expect(await page.evaluate('bubbles')).toBeTruthy();
expect(await page.evaluate('cancelable')).toBeTruthy();
expect(await page.evaluate('composed')).toBeTruthy();
});
it('should dispatch click svg', async({page, server}) => {
@ -39,7 +39,7 @@ it('should dispatch click svg', async({page, server}) => {
</svg>
`);
await page.dispatchEvent('circle', 'click');
expect(await page.evaluate(() => window.__CLICKED)).toBe(42);
expect(await page.evaluate(() => window['__CLICKED'])).toBe(42);
});
it('should dispatch click on a span with an inline element inside', async({page, server}) => {
@ -52,7 +52,7 @@ it('should dispatch click on a span with an inline element inside', async({page,
<span onclick='javascript:window.CLICKED=42'></span>
`);
await page.dispatchEvent('span', 'click');
expect(await page.evaluate(() => window.CLICKED)).toBe(42);
expect(await page.evaluate(() => window['CLICKED'])).toBe(42);
});
it('should dispatch click after navigation ', async({page, server}) => {
@ -60,7 +60,7 @@ it('should dispatch click after navigation ', async({page, server}) => {
await page.dispatchEvent('button', 'click');
await page.goto(server.PREFIX + '/input/button.html');
await page.dispatchEvent('button', 'click');
expect(await page.evaluate(() => result)).toBe('Clicked');
expect(await page.evaluate(() => window['result'])).toBe('Clicked');
});
it('should dispatch click after a cross origin navigation ', async({page, server}) => {
@ -68,7 +68,7 @@ it('should dispatch click after a cross origin navigation ', async({page, server
await page.dispatchEvent('button', 'click');
await page.goto(server.CROSS_PROCESS_PREFIX + '/input/button.html');
await page.dispatchEvent('button', 'click');
expect(await page.evaluate(() => result)).toBe('Clicked');
expect(await page.evaluate(() => window['result'])).toBe('Clicked');
});
it('should not fail when element is blocked on hover', async({page, server}) => {
@ -83,7 +83,7 @@ it('should not fail when element is blocked on hover', async({page, server}) =>
<div></div>
</container>`);
await page.dispatchEvent('button', 'click');
expect(await page.evaluate(() => window.clicked)).toBeTruthy();
expect(await page.evaluate(() => window['clicked'])).toBeTruthy();
});
it('should dispatch click when node is added in shadow dom', async({page, server}) => {
@ -98,11 +98,11 @@ it('should dispatch click when node is added in shadow dom', async({page, server
await page.evaluate(() => {
const span = document.createElement('span');
span.textContent = 'Hello from shadow';
span.addEventListener('click', () => window.clicked = true);
span.addEventListener('click', () => window['clicked'] = true);
document.querySelector('div').shadowRoot.appendChild(span);
});
await watchdog;
expect(await page.evaluate(() => window.clicked)).toBe(true);
expect(await page.evaluate(() => window['clicked'])).toBe(true);
});
it('should be atomic', async({playwright, page}) => {
@ -114,17 +114,17 @@ it('should be atomic', async({playwright, page}) => {
Promise.resolve().then(() => result.onclick = "");
return result;
},
queryAll(root, selector) {
queryAll(root: HTMLElement, selector: string) {
const result = Array.from(root.querySelectorAll(selector));
for (const e of result)
Promise.resolve().then(() => result.onclick = "");
Promise.resolve().then(() => (e as HTMLElement).onclick = null);
return result;
}
});
await utils.registerEngine(playwright, 'dispatchEvent', createDummySelector);
await page.setContent(`<div onclick="window._clicked=true">Hello</div>`);
await page.dispatchEvent('dispatchEvent=div', 'click');
expect(await page.evaluate(() => window._clicked)).toBe(true);
expect(await page.evaluate(() => window['_clicked'])).toBe(true);
});
it.fail(WEBKIT)('should dispatch drag drop events', async({page, server}) => {
@ -132,9 +132,11 @@ it.fail(WEBKIT)('should dispatch drag drop events', async({page, server}) => {
const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
await page.dispatchEvent('#source', 'dragstart', { dataTransfer });
await page.dispatchEvent('#target', 'drop', { dataTransfer });
expect(await page.evaluate(() => {
const source = await page.$('#source');
const target = await page.$('#target');
expect(await page.evaluate(({source, target}) => {
return source.parentElement === target;
})).toBeTruthy();
}, {source, target})).toBeTruthy();
});
it.fail(WEBKIT)('should dispatch drag drop events', async({page, server}) => {
@ -144,14 +146,14 @@ it.fail(WEBKIT)('should dispatch drag drop events', async({page, server}) => {
await source.dispatchEvent('dragstart', { dataTransfer });
const target = await page.$('#target');
await target.dispatchEvent('drop', { dataTransfer });
expect(await page.evaluate(() => {
expect(await page.evaluate(({source, target}) => {
return source.parentElement === target;
})).toBeTruthy();
}, {source, target})).toBeTruthy();
});
it('should dispatch click event', async({page, server}) => {
await page.goto(server.PREFIX + '/input/button.html');
const button = await page.$('button');
await button.dispatchEvent('click');
expect(await page.evaluate(() => result)).toBe('Clicked');
expect(await page.evaluate(() => window['result'])).toBe('Clicked');
});

View file

@ -104,7 +104,7 @@ it.skip(!CHROMIUM)('should expose function', async ({ application }) => {
const t = Date.now();
await application.context().exposeFunction('add', (a, b) => a + b);
const page = await application.newBrowserWindow({ width: 800, height: 600 });
await page.goto('data:text/html,<script>window.result = add(20, 22);</script>');
await page.goto('data:text/html,<script>window["result"] = add(20, 22);</script>');
expect(await page.evaluate(() => window['result'])).toBe(42);
});

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const { FFOX, HEADLESS } = testOptions;
it.fail(FFOX && !HEADLESS)('should work', async ({ page, server }) => {
@ -67,7 +67,7 @@ it('should work with SVG nodes', async ({ page, server }) => {
});
it.skip(FFOX)('should work with page scale', async ({ browser, server }) => {
const context = await browser.newContext({ viewport: { width: 400, height: 400, isMobile: true } });
const context = await browser.newContext({ viewport: { width: 400, height: 400 }, isMobile: true });
const page = await context.newPage();
await page.goto(server.PREFIX + '/input/button.html');
const button = await page.$('button');

View file

@ -14,16 +14,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const { FFOX, HEADLESS } = testOptions;
it('should work', async ({ page, server }) => {
await page.goto(server.PREFIX + '/input/button.html');
const button = await page.$('button');
await button.click();
expect(await page.evaluate(() => result)).toBe('Clicked');
expect(await page.evaluate(() => window['result'])).toBe('Clicked');
});
it('should work with Node removed', async ({ page, server }) => {
@ -31,21 +31,21 @@ it('should work with Node removed', async ({ page, server }) => {
await page.evaluate(() => delete window['Node']);
const button = await page.$('button');
await button.click();
expect(await page.evaluate(() => result)).toBe('Clicked');
expect(await page.evaluate(() => window['result'])).toBe('Clicked');
});
it('should work for Shadow DOM v1', async ({ page, server }) => {
await page.goto(server.PREFIX + '/shadow.html');
const buttonHandle = await page.evaluateHandle(() => button);
const buttonHandle = await page.evaluateHandle(() => window['button'] as HTMLButtonElement);
await buttonHandle.click();
expect(await page.evaluate(() => clicked)).toBe(true);
expect(await page.evaluate('clicked')).toBe(true);
});
it('should work for TextNodes', async ({ page, server }) => {
await page.goto(server.PREFIX + '/input/button.html');
const buttonTextNode = await page.evaluateHandle(() => document.querySelector('button').firstChild);
await buttonTextNode.click();
expect(await page.evaluate(() => result)).toBe('Clicked');
expect(await page.evaluate(() => window['result'])).toBe('Clicked');
});
it('should throw for detached nodes', async ({ page, server }) => {
@ -83,10 +83,10 @@ it('should throw for <br> elements with force', async ({ page, server }) => {
it('should double click the button', async ({ page, server }) => {
await page.goto(server.PREFIX + '/input/button.html');
await page.evaluate(() => {
window.double = false;
window['double'] = false;
const button = document.querySelector('button');
button.addEventListener('dblclick', event => {
window.double = true;
window['double'] = true;
});
});
const button = await page.$('button');

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const { FFOX, HEADLESS } = testOptions;
it('should work', async ({ page, server }) => {

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const { FFOX, HEADLESS } = testOptions;
it('should have a nice preview', async ({ page, server }) => {
@ -80,10 +80,10 @@ it('textContent should be atomic', async ({ playwright, page }) => {
Promise.resolve().then(() => result.textContent = 'modified');
return result;
},
queryAll(root, selector) {
queryAll(root: HTMLElement, selector: string) {
const result = Array.from(root.querySelectorAll(selector));
for (const e of result)
Promise.resolve().then(() => result.textContent = 'modified');
Promise.resolve().then(() => e.textContent = 'modified');
return result;
}
});
@ -97,16 +97,16 @@ it('textContent should be atomic', async ({ playwright, page }) => {
it('innerText should be atomic', async ({ playwright, page }) => {
const createDummySelector = () => ({
create(root, target) { },
query(root, selector) {
query(root: HTMLElement, selector: string) {
const result = root.querySelector(selector);
if (result)
Promise.resolve().then(() => result.textContent = 'modified');
return result;
},
queryAll(root, selector) {
queryAll(root: HTMLElement, selector: string) {
const result = Array.from(root.querySelectorAll(selector));
for (const e of result)
Promise.resolve().then(() => result.textContent = 'modified');
Promise.resolve().then(() => e.textContent = 'modified');
return result;
}
});
@ -126,10 +126,10 @@ it('innerHTML should be atomic', async ({ playwright, page }) => {
Promise.resolve().then(() => result.textContent = 'modified');
return result;
},
queryAll(root, selector) {
queryAll(root: HTMLElement, selector: string) {
const result = Array.from(root.querySelectorAll(selector));
for (const e of result)
Promise.resolve().then(() => result.textContent = 'modified');
Promise.resolve().then(() => e.textContent = 'modified');
return result;
}
});
@ -143,16 +143,16 @@ it('innerHTML should be atomic', async ({ playwright, page }) => {
it('getAttribute should be atomic', async ({ playwright, page }) => {
const createDummySelector = () => ({
create(root, target) { },
query(root, selector) {
query(root: HTMLElement, selector: string) {
const result = root.querySelector(selector);
if (result)
Promise.resolve().then(() => result.setAttribute('foo', 'modified'));
return result;
},
queryAll(root, selector) {
queryAll(root: HTMLElement, selector: string) {
const result = Array.from(root.querySelectorAll(selector));
for (const e of result)
Promise.resolve().then(() => result.setAttribute('foo', 'modified'));
Promise.resolve().then(() => (e as HTMLElement).setAttribute('foo', 'modified'));
return result;
}
});

View file

@ -14,16 +14,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const utils = require('./utils');
import path from 'path';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, CHANNEL, USES_HOOKS} = testOptions;
it('should work', async({page, server}) => {
await page.setContent('<html><body><div class="tweet"><div class="like">100</div><div class="retweets">10</div></div></body></html>');
const tweet = await page.$('.tweet');
const content = await tweet.$eval('.like', node => node.innerText);
const content = await tweet.$eval('.like', node => (node as HTMLElement).innerText);
expect(content).toBe('100');
});
@ -31,7 +31,7 @@ it('should retrieve content from subtree', async({page, server}) => {
const htmlContent = '<div class="a">not-a-child-div</div><div id="myId"><div class="a">a-child-div</div></div>';
await page.setContent(htmlContent);
const elementHandle = await page.$('#myId');
const content = await elementHandle.$eval('.a', node => node.innerText);
const content = await elementHandle.$eval('.a', node => (node as HTMLElement).innerText);
expect(content).toBe('a-child-div');
});
@ -39,14 +39,14 @@ it('should throw in case of missing selector', async({page, server}) => {
const htmlContent = '<div class="a">not-a-child-div</div><div id="myId"></div>';
await page.setContent(htmlContent);
const elementHandle = await page.$('#myId');
const errorMessage = await elementHandle.$eval('.a', node => node.innerText).catch(error => error.message);
const errorMessage = await elementHandle.$eval('.a', node => (node as HTMLElement).innerText).catch(error => error.message);
expect(errorMessage).toContain(`Error: failed to find element matching selector ".a"`);
});
it('should work for all', async({page, server}) => {
await page.setContent('<html><body><div class="tweet"><div class="like">100</div><div class="like">10</div></div></body></html>');
const tweet = await page.$('.tweet');
const content = await tweet.$$eval('.like', nodes => nodes.map(n => n.innerText));
const content = await tweet.$$eval('.like', nodes => nodes.map(n => (n as HTMLElement).innerText));
expect(content).toEqual(['100', '10']);
});
@ -54,7 +54,7 @@ it('should retrieve content from subtree for all', async({page, server}) => {
const htmlContent = '<div class="a">not-a-child-div</div><div id="myId"><div class="a">a1-child-div</div><div class="a">a2-child-div</div></div>';
await page.setContent(htmlContent);
const elementHandle = await page.$('#myId');
const content = await elementHandle.$$eval('.a', nodes => nodes.map(n => n.innerText));
const content = await elementHandle.$$eval('.a', nodes => nodes.map(n => (n as HTMLElement).innerText));
expect(content).toEqual(['a1-child-div', 'a2-child-div']);
});

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const { FFOX, HEADLESS } = testOptions;
it('should hover', async ({ page, server }) => {
@ -38,7 +38,7 @@ it('should fill input', async ({ page, server }) => {
await page.goto(server.PREFIX + '/input/textarea.html');
const handle = await page.$('input');
await handle.fill('some value');
expect(await page.evaluate(() => result)).toBe('some value');
expect(await page.evaluate(() => window['result'])).toBe('some value');
});
it('should fill input when Node is removed', async ({ page, server }) => {
@ -46,29 +46,29 @@ it('should fill input when Node is removed', async ({ page, server }) => {
await page.evaluate(() => delete window['Node']);
const handle = await page.$('input');
await handle.fill('some value');
expect(await page.evaluate(() => result)).toBe('some value');
expect(await page.evaluate(() => window['result'])).toBe('some value');
});
it('should check the box', async ({ page }) => {
await page.setContent(`<input id='checkbox' type='checkbox'></input>`);
const input = await page.$('input');
await input.check();
expect(await page.evaluate(() => checkbox.checked)).toBe(true);
expect(await page.evaluate('checkbox.checked')).toBe(true);
});
it('should uncheck the box', async ({ page }) => {
await page.setContent(`<input id='checkbox' type='checkbox' checked></input>`);
const input = await page.$('input');
await input.uncheck();
expect(await page.evaluate(() => checkbox.checked)).toBe(false);
expect(await page.evaluate('checkbox.checked')).toBe(false);
});
it('should select single option', async ({ page, server }) => {
await page.goto(server.PREFIX + '/input/select.html');
const select = await page.$('select');
await select.selectOption('blue');
expect(await page.evaluate(() => result.onInput)).toEqual(['blue']);
expect(await page.evaluate(() => result.onChange)).toEqual(['blue']);
expect(await page.evaluate(() => window['result'].onInput)).toEqual(['blue']);
expect(await page.evaluate(() => window['result'].onChange)).toEqual(['blue']);
});
it('should focus a button', async ({ page, server }) => {

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const { FFOX, HEADLESS } = testOptions;
it('should work', async ({ page, server }) => {
@ -55,7 +55,7 @@ it('should work for cross-frame evaluations', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = page.mainFrame();
const elementHandle = await frame.evaluateHandle(() => document.querySelector('#frame1').contentWindow.document.body);
const elementHandle = await frame.evaluateHandle(() => document.querySelector('iframe').contentWindow.document.body);
expect(await elementHandle.ownerFrame()).toBe(frame.childFrames()[0]);
});
@ -78,7 +78,7 @@ it('should work for adopted elements', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window.__popup = window.open(url), server.EMPTY_PAGE),
page.evaluate(url => window["__popup"] = window.open(url), server.EMPTY_PAGE),
]);
const divHandle = await page.evaluateHandle(() => {
const div = document.createElement('div');
@ -89,7 +89,7 @@ it('should work for adopted elements', async ({ page, server }) => {
await popup.waitForLoadState('domcontentloaded');
await page.evaluate(() => {
const div = document.querySelector('div');
window.__popup.document.body.appendChild(div);
window["__popup"].document.body.appendChild(div);
});
expect(await divHandle.ownerFrame()).toBe(popup.mainFrame());
});

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const { FFOX, HEADLESS } = testOptions;
it('should work', async ({ page }) => {

View file

@ -14,10 +14,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const utils = require('./utils');
import path from 'path';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, CHANNEL, USES_HOOKS} = testOptions;
it('should query existing element', async({page, server}) => {
@ -41,7 +41,7 @@ it('should work for adopted elements', async({page,server}) => {
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window.__popup = window.open(url), server.EMPTY_PAGE),
page.evaluate(url => window["__popup"] = window.open(url), server.EMPTY_PAGE),
]);
const divHandle = await page.evaluateHandle(() => {
const div = document.createElement('div');
@ -57,7 +57,7 @@ it('should work for adopted elements', async({page,server}) => {
await popup.waitForLoadState('domcontentloaded');
await page.evaluate(() => {
const div = document.querySelector('div');
window.__popup.document.body.appendChild(div);
window["__popup"].document.body.appendChild(div);
});
expect(await divHandle.$('span')).toBeTruthy();
expect(await divHandle.$eval('span', e => e.textContent)).toBe('hello');

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, USES_HOOKS, HEADLESS} = testOptions;
const {PNG} = require('pngjs');
import {PNG} from 'pngjs';
// Firefox headful produces a different image.
const ffheadful = FFOX && !HEADLESS;
@ -210,7 +210,7 @@ it.skip(ffheadful)('should work for an element with fractional dimensions', asyn
});
it.skip(FFOX)('should work with a mobile viewport', async({browser, server}) => {
const context = await browser.newContext({viewport: { width: 320, height: 480, isMobile: true }});
const context = await browser.newContext({viewport: { width: 320, height: 480 }, isMobile: true});
const page = await context.newPage();
await page.goto(server.PREFIX + '/grid.html');
await page.evaluate(() => window.scrollBy(50, 100));
@ -288,7 +288,7 @@ it.skip(ffheadful || USES_HOOKS)('should restore viewport after page screenshot
const page = await context.newPage();
await page.goto(server.PREFIX + '/grid.html');
const __testHookBeforeScreenshot = () => { throw new Error('oh my') };
const error = await page.screenshot({ fullPage: true, __testHookBeforeScreenshot }).catch(e => e);
const error = await page.screenshot({ fullPage: true, __testHookBeforeScreenshot } as any).catch(e => e);
expect(error.message).toContain('oh my');
await utils.verifyViewport(page, 350, 360);
await context.close();
@ -299,7 +299,7 @@ it.skip(ffheadful || USES_HOOKS)('should restore viewport after page screenshot
const page = await context.newPage();
await page.goto(server.PREFIX + '/grid.html');
const __testHookAfterScreenshot = () => new Promise(f => setTimeout(f, 5000));
const error = await page.screenshot({ fullPage: true, __testHookAfterScreenshot, timeout: 3000 }).catch(e => e);
const error = await page.screenshot({ fullPage: true, __testHookAfterScreenshot, timeout: 3000 } as any).catch(e => e);
expect(error.message).toContain('page.screenshot: Timeout 3000ms exceeded');
await utils.verifyViewport(page, 350, 360);
await page.setViewportSize({ width: 400, height: 400 });
@ -310,7 +310,7 @@ it.skip(ffheadful || USES_HOOKS)('should restore viewport after page screenshot
it.skip(ffheadful)('should take element screenshot when default viewport is null and restore back', async({server, browser}) => {
const context = await browser.newContext({viewport: null});
const page = await context.newPage({ viewport: null });
const page = await context.newPage();
await page.setContent(`
<div style="height: 14px">oooo</div>
<style>
@ -344,7 +344,7 @@ it.skip(ffheadful || USES_HOOKS)('should restore viewport after element screensh
await page.setContent(`<div style="width:600px;height:600px;"></div>`);
const elementHandle = await page.$('div');
const __testHookBeforeScreenshot = () => { throw new Error('oh my') };
const error = await elementHandle.screenshot({ __testHookBeforeScreenshot }).catch(e => e);
const error = await elementHandle.screenshot({ __testHookBeforeScreenshot } as any).catch(e => e);
expect(error.message).toContain('oh my');
await utils.verifyViewport(page, 350, 360);
await context.close();

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const { FFOX, HEADLESS } = testOptions;
it('should work', async ({ page, server }) => {

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const { FFOX, HEADLESS } = testOptions;
it('should select textarea', async ({ page, server }) => {

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const { FFOX, HEADLESS } = testOptions;
it('should work', async ({ page }) => {

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const {CHROMIUM, FFOX, MAC, HEADLESS} = testOptions;
it('should think that it is focused by default', async({page}) => {
@ -66,7 +66,7 @@ it('should provide target for keyboard events', async({page, server}) => {
it('should not affect mouse event target page', async({page, server}) => {
const page2 = await page.context().newPage();
function clickCounter() {
document.onclick = () => window.clickCount = (window.clickCount || 0) + 1;
document.onclick = () => window['clickCount'] = (window['clickCount'] || 0) + 1;
}
await Promise.all([
page.evaluate(clickCounter),
@ -130,9 +130,9 @@ it('should change focused iframe', async({page, server}) => {
utils.attachFrame(page, 'frame2', server.PREFIX + '/input/textarea.html'),
]);
function logger() {
self._events = [];
self['_events'] = [];
const element = document.querySelector('input');
element.onfocus = element.onblur = (e) => self._events.push(e.type);
element.onfocus = element.onblur = (e) => self['_events'].push(e.type);
}
await Promise.all([
frame1.evaluate(logger),

View file

@ -14,10 +14,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const utils = require('./utils');
import path from 'path';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, CHANNEL, USES_HOOKS} = testOptions;
it('should work with css selector', async({page, server}) => {

View file

@ -14,10 +14,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const utils = require('./utils');
import path from 'path';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, CHANNEL, USES_HOOKS} = testOptions;
it('should work with css selector', async({page, server}) => {

View file

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('../base.fixture');
import '../base.fixture';
const { FFOX } = testOptions;

View file

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, LINUX, WEBKIT, MAC} = testOptions;
@ -28,7 +28,7 @@ it('should emit focus event', async function({page, server}) {
await page.setContent(`<div id=d1 tabIndex=0></div>`);
let focused = false;
await page.exposeFunction('focusEvent', () => focused = true);
await page.evaluate(() => d1.addEventListener('focus', focusEvent));
await page.$eval('#d1', d1 => d1.addEventListener('focus', window['focusEvent']));
await page.focus('#d1');
expect(focused).toBe(true);
});
@ -40,8 +40,8 @@ it('should emit blur event', async function({page, server}) {
let blurred = false;
await page.exposeFunction('focusEvent', () => focused = true);
await page.exposeFunction('blurEvent', () => blurred = true);
await page.evaluate(() => d1.addEventListener('blur', blurEvent));
await page.evaluate(() => d2.addEventListener('focus', focusEvent));
await page.$eval('#d1', d1 => d1.addEventListener('blur', window['blurEvent']));
await page.$eval('#d2', d2 => d2.addEventListener('focus', window['focusEvent']));
await page.focus('#d2');
expect(focused).toBe(true);
expect(blurred).toBe(true);
@ -51,7 +51,7 @@ it('should traverse focus', async function({page}) {
await page.setContent(`<input id="i1"><input id="i2">`);
let focused = false;
await page.exposeFunction('focusEvent', () => focused = true);
await page.evaluate(() => i2.addEventListener('focus', focusEvent));
await page.$eval('#i2', i2 => (i2 as HTMLInputElement).addEventListener('focus', window['focusEvent']));
await page.focus('#i1');
await page.keyboard.type("First");
@ -59,22 +59,22 @@ it('should traverse focus', async function({page}) {
await page.keyboard.type("Last");
expect(focused).toBe(true);
expect(await page.$eval('#i1', e => e.value)).toBe('First');
expect(await page.$eval('#i2', e => e.value)).toBe('Last');
expect(await page.$eval('#i1', e => (e as HTMLInputElement).value)).toBe('First');
expect(await page.$eval('#i2', e => (e as HTMLInputElement).value)).toBe('Last');
});
it('should traverse focus in all directions', async function({page}) {
await page.setContent(`<input value="1"><input value="2"><input value="3">`);
await page.keyboard.press('Tab');
expect(await page.evaluate(() => document.activeElement.value)).toBe('1');
expect(await page.evaluate(() => (document.activeElement as HTMLInputElement).value)).toBe('1');
await page.keyboard.press('Tab');
expect(await page.evaluate(() => document.activeElement.value)).toBe('2');
expect(await page.evaluate(() => (document.activeElement as HTMLInputElement).value)).toBe('2');
await page.keyboard.press('Tab');
expect(await page.evaluate(() => document.activeElement.value)).toBe('3');
expect(await page.evaluate(() => (document.activeElement as HTMLInputElement).value)).toBe('3');
await page.keyboard.press('Shift+Tab');
expect(await page.evaluate(() => document.activeElement.value)).toBe('2');
expect(await page.evaluate(() => (document.activeElement as HTMLInputElement).value)).toBe('2');
await page.keyboard.press('Shift+Tab');
expect(await page.evaluate(() => document.activeElement.value)).toBe('1');
expect(await page.evaluate(() => (document.activeElement as HTMLInputElement).value)).toBe('1');
});
// Chromium and WebKit both have settings for tab traversing all links, but
// it is only on by default in WebKit.

View file

@ -14,20 +14,20 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
const path = require('path');
import utils from './utils';
import path from 'path';
const { FFOX, CHROMIUM, WEBKIT, USES_HOOKS } = testOptions;
it('should have different execution contexts', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
expect(page.frames().length).toBe(2);
await page.frames()[0].evaluate(() => window.FOO = 'foo');
await page.frames()[1].evaluate(() => window.FOO = 'bar');
expect(await page.frames()[0].evaluate(() => window.FOO)).toBe('foo');
expect(await page.frames()[1].evaluate(() => window.FOO)).toBe('bar');
await page.frames()[0].evaluate(() => window["FOO"] = 'foo');
await page.frames()[1].evaluate(() => window["FOO"] = 'bar');
expect(await page.frames()[0].evaluate(() => window["FOO"])).toBe('foo');
expect(await page.frames()[1].evaluate(() => window["FOO"])).toBe('bar');
});
it('should have correct execution contexts', async ({ page, server }) => {
@ -76,11 +76,11 @@ it('should not allow cross-frame js handles', async ({ page, server }) => {
const handle = await page.evaluateHandle(() => {
const iframe = document.querySelector('iframe');
const foo = { bar: 'baz' };
iframe.contentWindow.__foo = foo;
iframe.contentWindow['__foo'] = foo;
return foo;
});
const childFrame = page.mainFrame().childFrames()[0];
const childResult = await childFrame.evaluate(() => window.__foo);
const childResult = await childFrame.evaluate(() => window['__foo']);
expect(childResult).toEqual({ bar: 'baz' });
const error = await childFrame.evaluate(foo => foo.bar, handle).catch(e => e);
expect(error.message).toContain('JSHandles can be evaluated only in the context they were created!');
@ -117,12 +117,12 @@ it('should be isolated between frames', async({page, server}) => {
expect(frame1 !== frame2).toBeTruthy();
await Promise.all([
frame1.evaluate(() => window.a = 1),
frame2.evaluate(() => window.a = 2)
frame1.evaluate(() => window["a"] = 1),
frame2.evaluate(() => window["a"] = 2)
]);
const [a1, a2] = await Promise.all([
frame1.evaluate(() => window.a),
frame2.evaluate(() => window.a)
frame1.evaluate(() => window['a']),
frame2.evaluate(() => window['a'])
]);
expect(a1).toBe(1);
expect(a2).toBe(2);

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT} = testOptions;
it('should work', async({page, server}) => {

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
const path = require('path');
const url = require('url');
import utils from './utils';
import path from 'path';
import url from 'url';
const {FFOX, CHROMIUM, WEBKIT, ASSETS_DIR, MAC, WIN} = testOptions;
it('should navigate subframes', async({page, server}) => {

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT} = testOptions;
it('should handle nested frames', async({page, server}) => {
@ -43,7 +43,7 @@ it('should send events when frames are manipulated dynamically', async({page, se
const navigatedFrames = [];
page.on('framenavigated', frame => navigatedFrames.push(frame));
await page.evaluate(() => {
const frame = document.getElementById('frame1');
const frame = document.getElementById('frame1') as HTMLIFrameElement;
frame.src = './empty.html';
return new Promise(x => frame.onload = x);
});
@ -161,13 +161,13 @@ it('should report frame.parent()', async({page, server}) => {
it('should report different frame instance when frame re-attaches', async({page, server}) => {
const frame1 = await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await page.evaluate(() => {
window.frame = document.querySelector('#frame1');
window.frame.remove();
window['frame'] = document.querySelector('#frame1');
window['frame'].remove();
});
expect(frame1.isDetached()).toBe(true);
const [frame2] = await Promise.all([
page.waitForEvent('frameattached'),
page.evaluate(() => document.body.appendChild(window.frame)),
page.evaluate(() => document.body.appendChild(window['frame'])),
]);
expect(frame2.isDetached()).toBe(false);
expect(frame1).not.toBe(frame2);

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, WEBKIT} = testOptions;
@ -75,7 +75,7 @@ it('should isolate contexts', async({page, server, context, browser}) => {
it('should throw with missing latitude', async({context}) => {
let error = null;
try {
await context.setGeolocation({longitude: 10});
await context.setGeolocation({longitude: 10} as any);
} catch (e) {
error = e;
}
@ -94,7 +94,7 @@ it('should not modify passed default options object', async({browser}) => {
it('should throw with missing longitude in default options', async({browser}) => {
let error = null;
try {
const context = await browser.newContext({ geolocation: {latitude: 10} });
const context = await browser.newContext({ geolocation: {latitude: 10} as any });
await context.close();
} catch (e) {
error = e;
@ -149,9 +149,9 @@ it('should use context options for popup', async({page, context, server}) => {
await context.setGeolocation({ longitude: 10, latitude: 10 });
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window._popup = window.open(url), server.PREFIX + '/geolocation.html'),
page.evaluate(url => window["_popup"] = window.open(url), server.PREFIX + '/geolocation.html'),
]);
await popup.waitForLoadState();
const geolocation = await popup.evaluate(() => window.geolocationPromise);
const geolocation = await popup.evaluate(() => window['geolocationPromise']);
expect(geolocation).toEqual({ longitude: 10, latitude: 10 });
});

View file

@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const { makeUserDataDir, removeUserDataDir } = utils;
const {FFOX, CHROMIUM, WEBKIT, WIN, MAC} = testOptions;

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, WEBKIT, MAC} = testOptions;

View file

@ -14,12 +14,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const fs = require('fs');
const path = require('path');
const { helper } = require('../lib/helper');
const vm = require('vm');
import fs from 'fs';
import path from 'path';
import { helper } from '../lib/helper';
import vm from 'vm';
const {FFOX, CHROMIUM, WEBKIT, HEADLESS} = testOptions;
it('should work with navigation', async({page, server}) => {
@ -48,10 +48,10 @@ it('should work with ignoreHTTPSErrors', async({browser, httpsServer}) => {
it('should intercept after a service worker', async({browser, page, server, context}) => {
await page.goto(server.PREFIX + '/serviceworkers/fetchdummy/sw.html');
await page.evaluate(() => window.activationPromise);
await page.evaluate(() => window["activationPromise"]);
// Sanity check.
const swResponse = await page.evaluate(() => fetchDummy('foo'));
const swResponse = await page.evaluate(() => window["fetchDummy"]('foo'));
expect(swResponse).toBe('responseFromServiceWorker:foo');
await page.route('**/foo', route => {
@ -65,11 +65,11 @@ it('should intercept after a service worker', async({browser, page, server, cont
});
// Page route is applied after service worker fetch event.
const swResponse2 = await page.evaluate(() => fetchDummy('foo'));
const swResponse2 = await page.evaluate(() => window["fetchDummy"]('foo'));
expect(swResponse2).toBe('responseFromServiceWorker:foo');
// Page route is not applied to service worker initiated fetch.
const nonInterceptedResponse = await page.evaluate(() => fetchDummy('passthrough'));
const nonInterceptedResponse = await page.evaluate(() => window["fetchDummy"]('passthrough'));
expect(nonInterceptedResponse).toBe('FAILURE: Not Found');
});

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, WEBKIT} = testOptions;
@ -35,7 +35,7 @@ it('should return ElementHandle for TextNodes', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => document.querySelector('div').firstChild);
const element = aHandle.asElement();
expect(element).toBeTruthy();
expect(await page.evaluate(e => e.nodeType === HTMLElement.TEXT_NODE, element)).toBeTruthy();
expect(await page.evaluate(e => e.nodeType === Node.TEXT_NODE, element)).toBeTruthy();
});
it('should work with nullified Node', async({page, server}) => {

View file

@ -14,21 +14,21 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, WEBKIT} = testOptions;
it('should work with function', async({page, server}) => {
const windowHandle = await page.evaluateHandle(() => {
window.foo = [1, 2];
window['foo'] = [1, 2];
return window;
});
expect(await windowHandle.evaluate(w => w.foo)).toEqual([1, 2]);
expect(await windowHandle.evaluate(w => w['foo'])).toEqual([1, 2]);
});
it('should work with expression', async({page, server}) => {
const windowHandle = await page.evaluateHandle(() => {
window.foo = [1, 2];
window['foo'] = [1, 2];
return window;
});
expect(await windowHandle.evaluate('window.foo')).toEqual([1, 2]);

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, WEBKIT} = testOptions;

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, WEBKIT} = testOptions;
@ -77,11 +77,13 @@ it('getProperties should return empty map for non-objects', async({page, server}
it('getProperties should return even non-own properties', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => {
class A {
a: string;
constructor() {
this.a = '1';
}
}
class B extends A {
b: string;
constructor() {
super();
this.b = '2';

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, WEBKIT} = testOptions;

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const {FFOX, WEBKIT, CHROMIUM, MAC} = testOptions;
@ -278,10 +278,10 @@ it('should press Enter', async ({page, server}) => {
async function testEnterKey(key, expectedKey, expectedCode) {
await page.keyboard.press(key);
const lastEvent = await lastEventHandle.jsonValue();
expect(lastEvent.key).toBe(expectedKey, `${JSON.stringify(key)} had the wrong key: ${lastEvent.key}`);
expect(lastEvent.code).toBe(expectedCode, `${JSON.stringify(key)} had the wrong code: ${lastEvent.code}`);
expect(lastEvent.key).toBe(expectedKey); // had the wrong key
expect(lastEvent.code).toBe(expectedCode); // had the wrong code
const value = await page.$eval('textarea', t => t.value);
expect(value).toBe('\n', `${JSON.stringify(key)} failed to create a newline: ${JSON.stringify(value)}`);
expect(value).toBe('\n'); // failed to create a newline
await page.$eval('textarea', t => t.value = '');
}
});
@ -428,7 +428,7 @@ async function captureLastKeydown(page) {
lastEvent.code = e.code;
lastEvent.metaKey = e.metaKey;
// keyIdentifier only exists in WebKit, and isn't in TypeScript's lib.
lastEvent.keyIdentifier = 'keyIdentifier' in e && e.keyIdentifier;
lastEvent.keyIdentifier = 'keyIdentifier' in e && e['keyIdentifier'];
}, true);
return lastEvent;
});

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const fs = require('fs');
const utils = require('./utils');
import path from 'path';
import fs from 'fs';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS, CHANNEL} = testOptions;
it('should require top-level Errors', async({playwright}) => {

View file

@ -13,10 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const fs = require('fs');
const path = require('path');
import fs from 'fs';
import path from 'path';
const {FFOX, CHROMIUM, WEBKIT, CHANNEL} = testOptions;
it('should log', async({browserType, defaultBrowserOptions}) => {

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, WEBKIT, MAC, WIN} = testOptions;
@ -31,7 +31,7 @@ function dimensions() {
it.fail(FFOX && WIN)('should click the document', async({page, server}) => {
// Occasionally times out on FFOX on Windows: https://github.com/microsoft/playwright/pull/1911/checks?check_run_id=607149016
await page.evaluate(() => {
window.clickPromise = new Promise(resolve => {
window["clickPromise"] = new Promise(resolve => {
document.addEventListener('click', event => {
resolve({
type: event.type,
@ -45,7 +45,7 @@ it.fail(FFOX && WIN)('should click the document', async({page, server}) => {
});
});
await page.mouse.click(50, 60);
const event = await page.evaluate(() => window.clickPromise);
const event = await page.evaluate(() => window["clickPromise"]);
expect(event.type).toBe('click');
expect(event.detail).toBe(1);
expect(event.clientX).toBe(50);
@ -57,7 +57,7 @@ it.fail(FFOX && WIN)('should click the document', 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.evaluate(() => {
window.dblclickPromise = new Promise(resolve => {
window["dblclickPromise"] = new Promise(resolve => {
document.querySelector('div').addEventListener('dblclick', event => {
resolve({
type: event.type,
@ -71,7 +71,7 @@ it('should dblclick the div', async({page, server}) => {
});
});
await page.mouse.dblclick(50, 60);
const event = await page.evaluate(() => window.dblclickPromise);
const event = await page.evaluate(() => window["dblclickPromise"]);
expect(event.type).toBe('dblclick');
expect(event.detail).toBe(2);
expect(event.clientX).toBe(50);
@ -118,7 +118,7 @@ it('should trigger hover state with removed window.Node', async({page, server})
it('should set modifier keys on click', async({page, server}) => {
await page.goto(server.PREFIX + '/input/scrollable.html');
await page.evaluate(() => document.querySelector('#button-3').addEventListener('mousedown', e => window.lastEvent = e, true));
await page.evaluate(() => document.querySelector('#button-3').addEventListener('mousedown', e => window["lastEvent"] = e, true));
const modifiers = {'Shift': 'shiftKey', 'Control': 'ctrlKey', 'Alt': 'altKey', 'Meta': 'metaKey'};
// In Firefox, the Meta modifier only exists on Mac
if (FFOX && !MAC)
@ -126,13 +126,13 @@ it('should set modifier keys on click', async({page, server}) => {
for (const modifier in modifiers) {
await page.keyboard.down(modifier);
await page.click('#button-3');
if (!(await page.evaluate(mod => window.lastEvent[mod], modifiers[modifier])))
if (!(await page.evaluate(mod => window["lastEvent"][mod], modifiers[modifier])))
throw new Error(modifiers[modifier] + ' should be true');
await page.keyboard.up(modifier);
}
await page.click('#button-3');
for (const modifier in modifiers) {
if ((await page.evaluate(mod => window.lastEvent[mod], modifiers[modifier])))
if ((await page.evaluate(mod => window["lastEvent"][mod], modifiers[modifier])))
throw new Error(modifiers[modifier] + ' should be false');
}
});
@ -143,9 +143,9 @@ it('should tween mouse movement', async({page, server}) => {
await page.evaluate(() => new Promise(requestAnimationFrame));
await page.mouse.move(100, 100);
await page.evaluate(() => {
window.result = [];
window["result"] = [];
document.addEventListener('mousemove', event => {
window.result.push([event.clientX, event.clientY]);
window["result"].push([event.clientX, event.clientY]);
});
});
await page.mouse.move(200, 300, {steps: 5});
@ -160,13 +160,13 @@ it('should tween mouse movement', async({page, server}) => {
it.skip(FFOX)('should work with mobile viewports and cross process navigations', async({browser, server}) => {
// @see https://crbug.com/929806
const context = await browser.newContext({ viewport: {width: 360, height: 640, isMobile: true} });
const context = await browser.newContext({ viewport: {width: 360, height: 640}, isMobile: true });
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
await page.goto(server.CROSS_PROCESS_PREFIX + '/mobile.html');
await page.evaluate(() => {
document.addEventListener('click', event => {
window.result = {x: event.clientX, y: event.clientY};
window["result"] = {x: event.clientX, y: event.clientY};
});
});
@ -183,6 +183,6 @@ xdescribe('Drag and Drop', function() {
await page.mouse.down();
await page.hover('#target');
await page.mouse.up();
expect(await page.$eval('#target', target => target.contains(document.querySelector('#source')))).toBe(true, 'could not find source in target');
expect(await page.$eval('#target', target => target.contains(document.querySelector('#source')))).toBe(true); // could not find source in target
})
});

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, WEBKIT} = testOptions;
@ -83,7 +83,7 @@ it('should be able to connect multiple times to the same browser', async({browse
browser1.close();
const page2 = await browser2.newPage();
expect(await page2.evaluate(() => 7 * 6)).toBe(42, 'original browser should still work');
expect(await page2.evaluate(() => 7 * 6)).toBe(42); // original browser should still work
await browser2.close();
if (toImpl)
await toImpl(browserServer)._checkLeaks();

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
it('should work with _blank target', async({page, server}) => {
server.setRoute('/empty.html', (req, res) => {

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const fs = require('fs');
const path = require('path');
const utils = require('./utils');
import fs from 'fs';
import path from 'path';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, MAC, WIN} = testOptions;
it('should work for main frame navigation request', async({page, server}) => {

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const fs = require('fs');
const path = require('path');
const utils = require('./utils');
import fs from 'fs';
import path from 'path';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, MAC, WIN} = testOptions;
it('should work', async({page, server}) => {

View file

@ -14,44 +14,44 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
const path = require('path');
import utils from './utils';
import path from 'path';
const { FFOX, CHROMIUM, WEBKIT, USES_HOOKS } = testOptions;
it('should evaluate before anything else on the page', async ({ page, server }) => {
await page.addInitScript(function () {
window.injected = 123;
window["injected"] = 123;
});
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window.result)).toBe(123);
expect(await page.evaluate(() => window["result"])).toBe(123);
});
it('should work with a path', async ({ page, server }) => {
await page.addInitScript({ path: path.join(__dirname, 'assets/injectedfile.js') });
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window.result)).toBe(123);
expect(await page.evaluate(() => window["result"])).toBe(123);
});
it('should work with content', async ({ page, server }) => {
await page.addInitScript({ content: 'window.injected = 123' });
await page.addInitScript({ content: 'window["injected"] = 123' });
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window.result)).toBe(123);
expect(await page.evaluate(() => window["result"])).toBe(123);
});
it('should throw without path and content', async ({ page, server }) => {
const error = await page.addInitScript({ foo: 'bar' }).catch(e => e);
const error = await page.addInitScript({ foo: 'bar' } as any).catch(e => e);
expect(error.message).toContain('Either path or content property must be present');
});
it('should work with browser context scripts', async ({ browser, server }) => {
const context = await browser.newContext();
await context.addInitScript(() => window.temp = 123);
await context.addInitScript(() => window["temp"] = 123);
const page = await context.newPage();
await page.addInitScript(() => window.injected = window.temp);
await page.addInitScript(() => window["injected"] = window["temp"]);
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window.result)).toBe(123);
expect(await page.evaluate(() => window["result"])).toBe(123);
await context.close();
});
@ -60,50 +60,50 @@ it('should work with browser context scripts with a path', async ({ browser, ser
await context.addInitScript({ path: path.join(__dirname, 'assets/injectedfile.js') });
const page = await context.newPage();
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window.result)).toBe(123);
expect(await page.evaluate(() => window["result"])).toBe(123);
await context.close();
});
it('should work with browser context scripts for already created pages', async ({ browser, server }) => {
const context = await browser.newContext();
const page = await context.newPage();
await context.addInitScript(() => window.temp = 123);
await page.addInitScript(() => window.injected = window.temp);
await context.addInitScript(() => window["temp"] = 123);
await page.addInitScript(() => window["injected"] = window["temp"]);
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window.result)).toBe(123);
expect(await page.evaluate(() => window["result"])).toBe(123);
await context.close();
});
it('should support multiple scripts', async ({ page, server }) => {
await page.addInitScript(function () {
window.script1 = 1;
window["script1"] = 1;
});
await page.addInitScript(function () {
window.script2 = 2;
window["script2"] = 2;
});
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window.script1)).toBe(1);
expect(await page.evaluate(() => window.script2)).toBe(2);
expect(await page.evaluate(() => window["script1"])).toBe(1);
expect(await page.evaluate(() => window["script2"])).toBe(2);
});
it('should work with CSP', async ({ page, server }) => {
server.setCSP('/empty.html', 'script-src ' + server.PREFIX);
await page.addInitScript(function () {
window.injected = 123;
window["injected"] = 123;
});
await page.goto(server.PREFIX + '/empty.html');
expect(await page.evaluate(() => window.injected)).toBe(123);
expect(await page.evaluate(() => window["injected"])).toBe(123);
// Make sure CSP works.
await page.addScriptTag({ content: 'window.e = 10;' }).catch(e => void e);
expect(await page.evaluate(() => window.e)).toBe(undefined);
expect(await page.evaluate(() => window['e'])).toBe(undefined);
});
it('should work after a cross origin navigation', async ({ page, server }) => {
await page.goto(server.CROSS_PROCESS_PREFIX);
await page.addInitScript(function () {
window.injected = 123;
window["injected"] = 123;
});
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window.result)).toBe(123);
expect(await page.evaluate(() => window["result"])).toBe(123);
});

View file

@ -14,16 +14,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const util = require('util');
const vm = require('vm');
import path from 'path';
import util from 'util';
import vm from 'vm';
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS, CHANNEL} = testOptions;
it('should throw an error if no options are provided', async({page, server}) => {
let error = null;
try {
//@ts-ignore
await page.addScriptTag('/injectedfile.js');
} catch (e) {
error = e;
@ -35,27 +36,27 @@ it('should work with a url', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const scriptHandle = await page.addScriptTag({ url: '/injectedfile.js' });
expect(scriptHandle.asElement()).not.toBeNull();
expect(await page.evaluate(() => __injected)).toBe(42);
expect(await page.evaluate(() => window['__injected'])).toBe(42);
});
it('should work with a url and type=module', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({ url: '/es6/es6import.js', type: 'module' });
expect(await page.evaluate(() => __es6injected)).toBe(42);
expect(await page.evaluate(() => window['__es6injected'])).toBe(42);
});
it('should work with a path and type=module', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({ path: path.join(__dirname, 'assets/es6/es6pathimport.js'), type: 'module' });
await page.waitForFunction('window.__es6injected');
expect(await page.evaluate(() => __es6injected)).toBe(42);
expect(await page.evaluate(() => window['__es6injected'])).toBe(42);
});
it('should work with a content and type=module', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({ content: `import num from '/es6/es6module.js';window.__es6injected = num;`, type: 'module' });
await page.waitForFunction('window.__es6injected');
expect(await page.evaluate(() => __es6injected)).toBe(42);
expect(await page.evaluate(() => window['__es6injected'])).toBe(42);
});
it('should throw an error if loading from url fail', async({page, server}) => {
@ -73,28 +74,28 @@ it('should work with a path', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const scriptHandle = await page.addScriptTag({ path: path.join(__dirname, 'assets/injectedfile.js') });
expect(scriptHandle.asElement()).not.toBeNull();
expect(await page.evaluate(() => __injected)).toBe(42);
expect(await page.evaluate(() => window['__injected'])).toBe(42);
});
it.skip(WEBKIT)('should include sourceURL when path is provided', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({ path: path.join(__dirname, 'assets/injectedfile.js') });
const result = await page.evaluate(() => __injectedError.stack);
const result = await page.evaluate(() => window['__injectedError'].stack);
expect(result).toContain(path.join('assets', 'injectedfile.js'));
});
it('should work with content', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const scriptHandle = await page.addScriptTag({ content: 'window.__injected = 35;' });
const scriptHandle = await page.addScriptTag({ content: 'window["__injected"] = 35;' });
expect(scriptHandle.asElement()).not.toBeNull();
expect(await page.evaluate(() => __injected)).toBe(35);
expect(await page.evaluate(() => window['__injected'])).toBe(35);
});
it.fail(FFOX)('should throw when added with content to the CSP page', async({page, server}) => {
// Firefox fires onload for blocked script before it issues the CSP console error.
await page.goto(server.PREFIX + '/csp.html');
let error = null;
await page.addScriptTag({ content: 'window.__injected = 35;' }).catch(e => error = e);
await page.addScriptTag({ content: 'window["__injected"] = 35;' }).catch(e => error = e);
expect(error).toBeTruthy();
});

View file

@ -14,16 +14,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const util = require('util');
const vm = require('vm');
import path from 'path';
import util from 'util';
import vm from 'vm';
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS, CHANNEL} = testOptions;
it('should throw an error if no options are provided', async({page, server}) => {
let error = null;
try {
//@ts-ignore
await page.addStyleTag('/injectedstyle.css');
} catch (e) {
error = e;

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const util = require('util');
const vm = require('vm');
import path from 'path';
import util from 'util';
import vm from 'vm';
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS, CHANNEL} = testOptions;
it('should reject all promises when page is closed', async({context}) => {

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const {CHROMIUM, FFOX, MAC, HEADLESS} = testOptions;
it('should emulate type', async({page, server}) => {
@ -35,7 +35,7 @@ it('should emulate type', async({page, server}) => {
it('should throw in case of bad type argument', async({page, server}) => {
let error = null;
await page.emulateMedia({ media: 'bad' }).catch(e => error = e);
await page.emulateMedia({ media: 'bad' as any}).catch(e => error = e);
expect(error.message).toContain('media: expected one of (screen|print|null)');
});
@ -63,7 +63,7 @@ it('should default to light', async({page, server}) => {
it('should throw in case of bad argument', async({page, server}) => {
let error = null;
await page.emulateMedia({ colorScheme: 'bad' }).catch(e => error = e);
await page.emulateMedia({ colorScheme: 'bad' as any}).catch(e => error = e);
expect(error.message).toContain('colorScheme: expected one of (dark|light|no-preference|null)');
});
@ -72,7 +72,7 @@ it('should work during navigation', async({page, server}) => {
const navigated = page.goto(server.EMPTY_PAGE);
for (let i = 0; i < 9; i++) {
await Promise.all([
page.emulateMedia({ colorScheme: ['dark', 'light'][i & 1] }),
page.emulateMedia({ colorScheme: (['dark', 'light'] as const)[i & 1] }),
new Promise(f => setTimeout(f, 1)),
]);
}

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, WEBKIT} = testOptions;
@ -66,7 +66,7 @@ it('should accept multiple nested handles', async({page, server}) => {
it('should throw for circular objects', async({page, server}) => {
const a = { x: 1 };
a.y = a;
a['y'] = a;
const error = await page.evaluate(x => x, a).catch(e => e);
expect(error.message).toContain('Argument is a circular structure');
});
@ -103,8 +103,8 @@ it('should pass configurable args', async({page, server}) => {
it('should work with primitives', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => {
window.FOO = 123;
window['FOO'] = 123;
return window;
});
expect(await page.evaluate(e => e.FOO, aHandle)).toBe(123);
expect(await page.evaluate(e => e['FOO'], aHandle)).toBe(123);
});

View file

@ -14,11 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
const path = require('path');
const { FFOX, CHROMIUM, WEBKIT, USES_HOOKS } = testOptions;
const {WEBKIT, USES_HOOKS, FFOX} = testOptions;
it('should work', async ({ page, server }) => {
const result = await page.evaluate(() => 7 * 3);
@ -102,7 +100,7 @@ it('should transfer maps as empty objects', async ({ page, server }) => {
});
it('should modify global environment', async ({ page }) => {
await page.evaluate(() => window.globalVar = 123);
await page.evaluate(() => window['globalVar'] = 123);
expect(await page.evaluate('globalVar')).toBe(123);
});
@ -176,13 +174,14 @@ it('should work from-inside an exposed function', async ({ page, server }) => {
return await page.evaluate(({ a, b }) => a * b, { a, b });
});
const result = await page.evaluate(async function () {
return await callController(9, 3);
return await window['callController'](9, 3);
});
expect(result).toBe(27);
});
it('should reject promise with exception', async ({ page, server }) => {
let error = null;
//@ts-ignore
await page.evaluate(() => not_existing_object.property).catch(e => error = e);
expect(error).toBeTruthy();
expect(error.message).toContain('not_existing_object');
@ -233,17 +232,18 @@ it('should work with overwritten Promise', async ({ page, server }) => {
await page.evaluate(() => {
const originalPromise = window.Promise;
class Promise2 {
static all(...arg) {
return wrap(originalPromise.all(...arg));
_promise: Promise<any>;
static all(arg) {
return wrap(originalPromise.all(arg));
}
static race(...arg) {
return wrap(originalPromise.race(...arg));
static race(arg) {
return wrap(originalPromise.race(arg));
}
static resolve(...arg) {
return wrap(originalPromise.resolve(...arg));
static resolve(arg) {
return wrap(originalPromise.resolve(arg));
}
constructor(f, r) {
this._promise = new originalPromise(f, r);
constructor(f) {
this._promise = new originalPromise(f);
}
then(f, r) {
return wrap(this._promise.then(f, r));
@ -256,18 +256,19 @@ it('should work with overwritten Promise', async ({ page, server }) => {
}
};
const wrap = p => {
const result = new Promise2(() => { }, () => { });
const result = new Promise2(() => { });
result._promise = p;
return result;
};
//@ts-ignore;
window.Promise = Promise2;
window.__Promise2 = Promise2;
window["__Promise2"] = Promise2;
});
// Sanity check.
expect(await page.evaluate(() => {
const p = Promise.all([Promise.race([]), new Promise(() => { }).then(() => { })]);
return p instanceof window.__Promise2;
return p instanceof window["__Promise2"];
})).toBe(true);
// Now, the new promise should be awaitable.
@ -280,16 +281,26 @@ it('should throw when passed more than one parameter', async ({ page, server })
await f().catch(e => error = e);
expect('' + error).toContain('Too many arguments');
}
//@ts-ignore
await expectThrow(() => page.evaluate((a, b) => false, 1, 2));
//@ts-ignore
await expectThrow(() => page.evaluateHandle((a, b) => false, 1, 2));
//@ts-ignore
await expectThrow(() => page.$eval('sel', (a, b) => false, 1, 2));
//@ts-ignore
await expectThrow(() => page.$$eval('sel', (a, b) => false, 1, 2));
//@ts-ignore
await expectThrow(() => page.evaluate((a, b) => false, 1, 2));
const frame = page.mainFrame();
//@ts-ignore
await expectThrow(() => frame.evaluate((a, b) => false, 1, 2));
//@ts-ignore
await expectThrow(() => frame.evaluateHandle((a, b) => false, 1, 2));
//@ts-ignore
await expectThrow(() => frame.$eval('sel', (a, b) => false, 1, 2));
//@ts-ignore
await expectThrow(() => frame.$$eval('sel', (a, b) => false, 1, 2));
//@ts-ignore
await expectThrow(() => frame.evaluate((a, b) => false, 1, 2));
});
@ -325,7 +336,7 @@ it('should return undefined for non-serializable objects', async ({ page, server
it('should fail for circular object', async ({ page, server }) => {
const result = await page.evaluate(() => {
const a = {};
const a = {} as any;
const b = { a };
a.b = b;
return a;
@ -384,12 +395,12 @@ it('should simulate a user gesture', async ({ page, server }) => {
});
it('should throw a nice error after a navigation', async ({ page, server }) => {
const errorPromise = page.evaluate(() => new Promise(f => window.__resolve = f)).catch(e => e);
const errorPromise = page.evaluate(() => new Promise(f => window['__resolve'] = f)).catch(e => e) as Promise<Error>;
await Promise.all([
page.waitForNavigation(),
page.evaluate(() => {
window.location.reload();
setTimeout(() => window.__resolve(42), 1000);
setTimeout(() => window['__resolve'](42), 1000);
})
]);
const error = await errorPromise;
@ -399,7 +410,7 @@ it('should throw a nice error after a navigation', async ({ page, server }) => {
it('should not throw an error when evaluation does a navigation', async ({ page, server }) => {
await page.goto(server.PREFIX + '/one-style.html');
const result = await page.evaluate(() => {
window.location = '/empty.html';
window.location.href = '/empty.html';
return [42];
});
expect(result).toEqual([42]);
@ -448,7 +459,7 @@ it.fail(FFOX)('should await promise from popup', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
const result = await page.evaluate(() => {
const win = window.open('about:blank');
return new win.Promise(f => f(42));
return new win['Promise'](f => f(42));
});
expect(result).toBe(42);
});
@ -461,7 +472,9 @@ it('should work with new Function() and CSP', async ({ page, server }) => {
it('should work with non-strict expressions', async ({ page, server }) => {
expect(await page.evaluate(() => {
//@ts-ignore
y = 3.14;
//@ts-ignore
return y;
})).toBe(3.14);
});
@ -469,19 +482,21 @@ it('should work with non-strict expressions', async ({ page, server }) => {
it('should respect use strict expression', async ({ page, server }) => {
const error = await page.evaluate(() => {
"use strict";
//@ts-ignore
variableY = 3.14;
//@ts-ignore
return variableY;
}).catch(e => e);
expect(error.message).toContain('variableY');
});
it('should not leak utility script', async ({ page, server }) => {
it('should not leak utility script', async function ({ page, server }) {
expect(await page.evaluate(() => this === window)).toBe(true);
});
it('should not leak handles', async ({ page, server }) => {
const error = await page.evaluate(() => handles.length).catch(e => e);
expect(error.message).toContain(' handles');
const error = await page.evaluate('handles.length').catch(e => e);
expect((error as Error).message).toContain(' handles');
});
it('should work with CSP', async ({ page, server }) => {

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const util = require('util');
const vm = require('vm');
import path from 'path';
import util from 'util';
import vm from 'vm';
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS, CHANNEL} = testOptions;
it('should work', async({page, server}) => {
@ -123,7 +123,7 @@ it('should not throw when there are console messages in detached iframes', async
page.evaluate(async() => {
// 1. Create a popup that Playwright is not connected to.
const win = window.open('');
window._popup = win;
window["_popup"] = win;
if (window.document.readyState !== 'complete')
await new Promise(f => window.addEventListener('load', f));
// 2. In this popup, create an iframe that console.logs a message.

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const util = require('util');
const vm = require('vm');
import path from 'path';
import util from 'util';
import vm from 'vm';
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS, CHANNEL} = testOptions;
const CRASH_FAIL = (FFOX && WIN) || USES_HOOKS;

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const fs = require('fs');
const path = require('path');
const utils = require('./utils');
import fs from 'fs';
import path from 'path';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, MAC, WIN} = testOptions;
it('Page.Events.Request', async({page, server}) => {
@ -48,7 +48,7 @@ it('Page.Events.Response', async({page, server}) => {
it('Page.Events.RequestFailed', async({page, server}) => {
server.setRoute('/one-style.css', (req, res) => {
res.setHeader('Content-Type', 'text/css');
res.socket.destroy();
res.connection.destroy();
});
const failedRequests = [];
page.on('requestfailed', request => failedRequests.push(request));

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
import path from 'path';
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS, CHANNEL} = testOptions;
it('should fire', async({page, server}) => {
@ -26,7 +26,7 @@ it('should fire', async({page, server}) => {
]);
expect(error.name).toBe('Error');
expect(error.message).toBe('Fancy error!');
let stack = await page.evaluate(() => window.e.stack);
let stack = await page.evaluate(() => window['e'].stack);
// Note that WebKit reports the stack of the 'throw' statement instead of the Error constructor call.
if (WEBKIT)
stack = stack.replace('14:25', '15:19');

View file

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, WEBKIT, MAC} = testOptions;
@ -22,7 +22,7 @@ it('should work', async({browser}) => {
const page = await context.newPage();
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window.__popup = window.open('about:blank')),
page.evaluate(() => window["__popup"] = window.open('about:blank')),
]);
expect(await page.evaluate(() => !!window.opener)).toBe(false);
expect(await popup.evaluate(() => !!window.opener)).toBe(true);
@ -35,7 +35,7 @@ it('should work with window features', async({browser, server}) => {
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window.__popup = window.open(window.location.href, 'Title', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=0,left=0')),
page.evaluate(() => window["__popup"] = window.open(window.location.href, 'Title', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=0,left=0')),
]);
expect(await page.evaluate(() => !!window.opener)).toBe(false);
expect(await popup.evaluate(() => !!window.opener)).toBe(true);
@ -91,7 +91,7 @@ it('should work with empty url', async({browser}) => {
const page = await context.newPage();
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window.__popup = window.open('')),
page.evaluate(() => window["__popup"] = window.open('')),
]);
expect(await page.evaluate(() => !!window.opener)).toBe(false);
expect(await popup.evaluate(() => !!window.opener)).toBe(true);
@ -103,7 +103,7 @@ it('should work with noopener and no url', async({browser}) => {
const page = await context.newPage();
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window.__popup = window.open(undefined, null, 'noopener')),
page.evaluate(() => window["__popup"] = window.open(undefined, null, 'noopener')),
]);
// Chromium reports `about:blank#blocked` here.
expect(popup.url().split('#')[0]).toBe('about:blank');
@ -117,7 +117,7 @@ it('should work with noopener and about:blank', async({browser}) => {
const page = await context.newPage();
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window.__popup = window.open('about:blank', null, 'noopener')),
page.evaluate(() => window["__popup"] = window.open('about:blank', null, 'noopener')),
]);
expect(await page.evaluate(() => !!window.opener)).toBe(false);
expect(await popup.evaluate(() => !!window.opener)).toBe(false);
@ -130,7 +130,7 @@ it('should work with noopener and url', async({browser, server}) => {
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window.__popup = window.open(url, null, 'noopener'), server.EMPTY_PAGE),
page.evaluate(url => window["__popup"] = window.open(url, null, 'noopener'), server.EMPTY_PAGE),
]);
expect(await page.evaluate(() => !!window.opener)).toBe(false);
expect(await popup.evaluate(() => !!window.opener)).toBe(false);

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const fs = require('fs');
const path = require('path');
const utils = require('./utils');
import fs from 'fs';
import path from 'path';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, MAC, WIN} = testOptions;
it('should fire for navigation requests', async({page, server}) => {
@ -46,9 +46,9 @@ it('should fire for fetches', async({page, server}) => {
it('should report requests and responses handled by service worker', async({page, server}) => {
await page.goto(server.PREFIX + '/serviceworkers/fetchdummy/sw.html');
await page.evaluate(() => window.activationPromise);
await page.evaluate(() => window["activationPromise"]);
const [swResponse, request] = await Promise.all([
page.evaluate(() => fetchDummy('foo')),
page.evaluate(() => window["fetchDummy"]('foo')),
page.waitForEvent('request'),
]);
expect(swResponse).toBe('responseFromServiceWorker:foo');

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const util = require('util');
const vm = require('vm');
import path from 'path';
import util from 'util';
import vm from 'vm';
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS, CHANNEL} = testOptions;
it('exposeBinding should work', async({browser}) => {
@ -30,7 +30,7 @@ it('exposeBinding should work', async({browser}) => {
return a + b;
});
const result = await page.evaluate(async function() {
return add(5, 6);
return window['add'](5, 6);
});
expect(bindingSource.context).toBe(context);
expect(bindingSource.page).toBe(page);
@ -44,23 +44,23 @@ it('should work', async({page, server}) => {
return a * b;
});
const result = await page.evaluate(async function() {
return await compute(9, 4);
return await window['compute'](9, 4);
});
expect(result).toBe(36);
});
it('should work with handles and complex objects', async({page, server}) => {
const fooHandle = await page.evaluateHandle(() => {
window.fooValue = { bar: 2 };
return window.fooValue;
window['fooValue'] = { bar: 2 };
return window['fooValue'];
});
await page.exposeFunction('handle', () => {
return [{ foo: fooHandle }];
});
const equals = await page.evaluate(async function() {
const value = await handle();
const value = await window['handle']();
const [{ foo }] = value;
return foo === window.fooValue;
return foo === window['fooValue'];
});
expect(equals).toBe(true);
});
@ -71,7 +71,7 @@ it('should throw exception in page context', async({page, server}) => {
});
const {message, stack} = await page.evaluate(async() => {
try {
await woof();
await window["woof"]();
} catch (e) {
return {message: e.message, stack: e.stack};
}
@ -86,7 +86,7 @@ it('should support throwing "null"', async({page, server}) => {
});
const thrown = await page.evaluate(async() => {
try {
await woof();
await window["woof"]();
} catch (e) {
return e;
}
@ -99,7 +99,7 @@ it('should be callable from-inside addInitScript', async({page, server}) => {
await page.exposeFunction('woof', function() {
called = true;
});
await page.addInitScript(() => woof());
await page.addInitScript(() => window["woof"]());
await page.reload();
expect(called).toBe(true);
});
@ -111,7 +111,7 @@ it('should survive navigation', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const result = await page.evaluate(async function() {
return await compute(9, 4);
return await window['compute'](9, 4);
});
expect(result).toBe(36);
});
@ -122,7 +122,7 @@ it('should await returned promise', async({page, server}) => {
});
const result = await page.evaluate(async function() {
return await compute(3, 5);
return await window['compute'](3, 5);
});
expect(result).toBe(15);
});
@ -135,7 +135,7 @@ it('should work on frames', async({page, server}) => {
await page.goto(server.PREFIX + '/frames/nested-frames.html');
const frame = page.frames()[1];
const result = await frame.evaluate(async function() {
return await compute(3, 5);
return await window['compute'](3, 5);
});
expect(result).toBe(15);
});
@ -148,7 +148,7 @@ it('should work on frames before navigation', async({page, server}) => {
const frame = page.frames()[1];
const result = await frame.evaluate(async function() {
return await compute(3, 5);
return await window['compute'](3, 5);
});
expect(result).toBe(15);
});
@ -161,7 +161,7 @@ it('should work after cross origin navigation', async({page, server}) => {
await page.goto(server.CROSS_PROCESS_PREFIX + '/empty.html');
const result = await page.evaluate(async function() {
return await compute(9, 4);
return await window['compute'](9, 4);
});
expect(result).toBe(36);
});
@ -170,6 +170,6 @@ it('should work with complex objects', async({page, server}) => {
await page.exposeFunction('complexObject', function(a, b) {
return {x: a.x + b.x};
});
const result = await page.evaluate(async() => complexObject({x: 5}, {x: 2}));
const result = await page.evaluate(async() => window['complexObject']({x: 5}, {x: 2}));
expect(result.x).toBe(7);
});

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const util = require('util');
const vm = require('vm');
import path from 'path';
import util from 'util';
import vm from 'vm';
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS, CHANNEL} = testOptions;
async function giveItAChanceToFill(page) {
@ -29,13 +29,13 @@ async function giveItAChanceToFill(page) {
it('should fill textarea', async({page, server}) => {
await page.goto(server.PREFIX + '/input/textarea.html');
await page.fill('textarea', 'some value');
expect(await page.evaluate(() => result)).toBe('some value');
expect(await page.evaluate(() => window['result'])).toBe('some value');
});
it('should fill input', async({page, server}) => {
await page.goto(server.PREFIX + '/input/textarea.html');
await page.fill('input', 'some value');
expect(await page.evaluate(() => result)).toBe('some value');
expect(await page.evaluate(() => window['result'])).toBe('some value');
});
it('should throw on unsupported inputs', async({page, server}) => {
@ -53,7 +53,7 @@ it('should fill different input types', async({page, server}) => {
for (const type of ['password', 'search', 'tel', 'text', 'url']) {
await page.$eval('input', (input, type) => input.setAttribute('type', type), type);
await page.fill('input', 'text ' + type);
expect(await page.evaluate(() => result)).toBe('text ' + type);
expect(await page.evaluate(() => window['result'])).toBe('text ' + type);
}
});
@ -105,14 +105,14 @@ it('should fill elements with existing value and selection', async({page, server
await page.$eval('input', input => input.value = 'value one');
await page.fill('input', 'another value');
expect(await page.evaluate(() => result)).toBe('another value');
expect(await page.evaluate(() => window['result'])).toBe('another value');
await page.$eval('input', input => {
input.selectionStart = 1;
input.selectionEnd = 2;
});
await page.fill('input', 'maybe this one');
expect(await page.evaluate(() => result)).toBe('maybe this one');
expect(await page.evaluate(() => window['result'])).toBe('maybe this one');
await page.$eval('div[contenteditable]', div => {
div.innerHTML = 'some text <span>some more text<span> and even more text';
@ -136,7 +136,7 @@ it('should throw when element is not an <input>, <textarea> or [contenteditable]
it('should throw if passed a non-string value', async({page, server}) => {
let error = null;
await page.goto(server.PREFIX + '/input/textarea.html');
await page.fill('textarea', 123).catch(e => error = e);
await page.fill('textarea', 123 as any).catch(e => error = e);
expect(error.message).toContain('value: expected string, got number');
});
@ -148,11 +148,11 @@ it('should retry on disabled element', async({page, server}) => {
const promise = page.fill('input', 'some value').then(() => done = true);
await giveItAChanceToFill(page);
expect(done).toBe(false);
expect(await page.evaluate(() => result)).toBe('');
expect(await page.evaluate(() => window['result'])).toBe('');
await page.$eval('input', i => i.disabled = false);
await promise;
expect(await page.evaluate(() => result)).toBe('some value');
expect(await page.evaluate(() => window['result'])).toBe('some value');
});
it('should retry on readonly element', async({page, server}) => {
@ -163,11 +163,11 @@ it('should retry on readonly element', async({page, server}) => {
const promise = page.fill('textarea', 'some value').then(() => done = true);
await giveItAChanceToFill(page);
expect(done).toBe(false);
expect(await page.evaluate(() => result)).toBe('');
expect(await page.evaluate(() => window['result'])).toBe('');
await page.$eval('textarea', i => i.readOnly = false);
await promise;
expect(await page.evaluate(() => result)).toBe('some value');
expect(await page.evaluate(() => window['result'])).toBe('some value');
});
it('should retry on invisible element', async({page, server}) => {
@ -178,11 +178,11 @@ it('should retry on invisible element', async({page, server}) => {
const promise = page.fill('input', 'some value').then(() => done = true);
await giveItAChanceToFill(page);
expect(done).toBe(false);
expect(await page.evaluate(() => result)).toBe('');
expect(await page.evaluate(() => window['result'])).toBe('');
await page.$eval('input', i => i.style.display = 'inline');
await promise;
expect(await page.evaluate(() => result)).toBe('some value');
expect(await page.evaluate(() => window['result'])).toBe('some value');
});
it('should be able to fill the body', async({page}) => {
@ -210,19 +210,19 @@ it('should be able to fill when focus is in the wrong frame', async({page}) => {
it('should be able to fill the input[type=number]', async({page}) => {
await page.setContent(`<input id="input" type="number"></input>`);
await page.fill('input', '42');
expect(await page.evaluate(() => input.value)).toBe('42');
expect(await page.evaluate(() => window['input'].value)).toBe('42');
});
it('should be able to fill exponent into the input[type=number]', async({page}) => {
await page.setContent(`<input id="input" type="number"></input>`);
await page.fill('input', '-10e5');
expect(await page.evaluate(() => input.value)).toBe('-10e5');
expect(await page.evaluate(() => window['input'].value)).toBe('-10e5');
});
it('should be able to fill input[type=number] with empty string', async({page}) => {
await page.setContent(`<input id="input" type="number" value="123"></input>`);
await page.fill('input', '');
expect(await page.evaluate(() => input.value)).toBe('');
expect(await page.evaluate(() => window['input'].value)).toBe('');
});
it('should not be able to fill text into the input[type=number]', async({page}) => {
@ -235,7 +235,7 @@ it('should not be able to fill text into the input[type=number]', async({page})
it('should be able to clear', async({page, server}) => {
await page.goto(server.PREFIX + '/input/textarea.html');
await page.fill('input', 'some value');
expect(await page.evaluate(() => result)).toBe('some value');
expect(await page.evaluate(() => window['result'])).toBe('some value');
await page.fill('input', '');
expect(await page.evaluate(() => result)).toBe('');
expect(await page.evaluate(() => window['result'])).toBe('');
});

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
const path = require('path');
const url = require('url');
import utils from './utils';
import path from 'path';
import url from 'url';
const {FFOX, CHROMIUM, WEBKIT, ASSETS_DIR, MAC, WIN} = testOptions;
it('should work', async({page, server}) => {
@ -192,12 +192,12 @@ it('should not crash when navigating to bad SSL after a cross origin navigation'
it('should not throw if networkidle0 is passed as an option', async({page, server}) => {
let error = null;
await page.goto(server.EMPTY_PAGE, {waitUntil: 'networkidle0'});
await page.goto(server.EMPTY_PAGE, {waitUntil: 'networkidle0' as any});
});
it('should throw if networkidle2 is passed as an option', async({page, server}) => {
let error = null;
await page.goto(server.EMPTY_PAGE, {waitUntil: 'networkidle2'}).catch(err => error = err);
await page.goto(server.EMPTY_PAGE, {waitUntil: 'networkidle2' as any}).catch(err => error = err);
expect(error.message).toContain(`waitUntil: expected one of (load|domcontentloaded|networkidle)`);
});
@ -338,7 +338,7 @@ it('should not leak listeners during navigation', async({page, server}) => {
process.on('warning', warningHandler);
for (let i = 0; i < 20; ++i)
await page.goto(server.EMPTY_PAGE);
process.removeListener('warning', warningHandler);
process.off('warning', warningHandler);
expect(warning).toBe(null);
});
@ -348,7 +348,7 @@ it('should not leak listeners during bad navigation', async({page, server}) => {
process.on('warning', warningHandler);
for (let i = 0; i < 20; ++i)
await page.goto('asdf').catch(e => {/* swallow navigation error */});
process.removeListener('warning', warningHandler);
process.off('warning', warningHandler);
expect(warning).toBe(null);
});
@ -359,7 +359,7 @@ it('should not leak listeners during navigation of 20 pages', async({page, conte
const pages = await Promise.all([...Array(20)].map(() => context.newPage()));
await Promise.all(pages.map(page => page.goto(server.EMPTY_PAGE)));
await Promise.all(pages.map(page => page.close()));
process.removeListener('warning', warningHandler);
process.off('warning', warningHandler);
expect(warning).toBe(null);
});
@ -370,7 +370,7 @@ it('should not leak listeners during 20 waitForNavigation', async({page, context
const promises = [...Array(20)].map(() => page.waitForNavigation());
await page.goto(server.EMPTY_PAGE);
await Promise.all(promises);
process.removeListener('warning', warningHandler);
process.off('warning', warningHandler);
expect(warning).toBe(null);
});
@ -412,7 +412,7 @@ it('should fail when navigating and show the url at the error message', async fu
it('should be able to navigate to a page controlled by service worker', async({page, server}) => {
await page.goto(server.PREFIX + '/serviceworkers/fetch/sw.html');
await page.evaluate(() => window.activationPromise);
await page.evaluate(() => window["activationPromise"]);
await page.goto(server.PREFIX + '/serviceworkers/fetch/sw.html');
});

View file

@ -14,10 +14,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const url = require('url');
import path from 'path';
import url from 'url';
const {FFOX, CHROMIUM, WEBKIT, ASSETS_DIR, MAC, WIN} = testOptions;
it('page.goBack should work', async({page, server}) => {
@ -81,9 +81,9 @@ it.fail(WEBKIT && MAC)('page.goBack should work for file urls', async ({page, se
it('page.reload should work', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => window._foo = 10);
await page.evaluate(() => window["_foo"] = 10);
await page.reload();
expect(await page.evaluate(() => window._foo)).toBe(undefined);
expect(await page.evaluate(() => window["_foo"])).toBe(undefined);
});
it('page.reload should work with data url', async({page, server}) => {

View file

@ -14,11 +14,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
const path = require('path');
const url = require('url');
import utils from './utils';
import path from 'path';
import url from 'url';
import { Frame, Page } from '..';
import { TestServer } from '../utils/testserver';
const {FFOX, CHROMIUM, WEBKIT, ASSETS_DIR, MAC, WIN} = testOptions;
it('should navigate to empty page with networkidle', async({page, server}) => {
@ -26,13 +28,7 @@ it('should navigate to empty page with networkidle', async({page, server}) => {
expect(response.status()).toBe(200);
});
/**
* @param {import('../index').Frame} frame
* @param {TestServer} server
* @param {() => Promise<void>} action
* @param {boolean} isSetContent
*/
async function networkIdleTest(frame, server, action, isSetContent) {
async function networkIdleTest(frame: Frame, server: TestServer, action: () => Promise<any>, isSetContent?: boolean) {
const finishResponse = response => {
response.statusCode = 404;
response.end(`File not found`);
@ -40,14 +36,14 @@ async function networkIdleTest(frame, server, action, isSetContent) {
const waitForRequest = suffix => {
return Promise.all([
server.waitForRequest(suffix),
frame._page.waitForRequest(server.PREFIX + suffix),
(frame['_page'] as Page).waitForRequest(server.PREFIX + suffix),
]);
}
let responses = {};
// 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');
server.setRoute('/fetch-request-d.js', (req, res) => responses.d = res);
server.setRoute('/fetch-request-d.js', (req, res) => responses['d'] = res);
const secondFetchResourceRequested = waitForRequest('/fetch-request-d.js');
const waitForLoadPromise = isSetContent ? Promise.resolve() : frame.waitForNavigation({ waitUntil: 'load' });
@ -68,18 +64,18 @@ async function networkIdleTest(frame, server, action, isSetContent) {
await firstFetchResourceRequested;
expect(actionFinished).toBe(false);
expect(responses.a).toBeTruthy();
expect(responses['a']).toBeTruthy();
let timer;
let timerTriggered = false;
// Finishing response should trigger the second round.
finishResponse(responses.a);
finishResponse(responses['a']);
// Wait for the second round to be requested.
await secondFetchResourceRequested;
expect(actionFinished).toBe(false);
// Finishing the last response should trigger networkidle.
timer = setTimeout(() => timerTriggered = true, 500);
finishResponse(responses.d);
finishResponse(responses['d']);
const response = await actionPromise;
clearTimeout(timer);

View file

@ -14,12 +14,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const fs = require('fs');
const path = require('path');
const { helper } = require('../lib/helper');
const vm = require('vm');
import fs from 'fs';
import path from 'path';
import { helper } from '../lib/helper';
import vm from 'vm';
const {FFOX, CHROMIUM, WEBKIT, HEADLESS} = testOptions;
it('should intercept', async({page, server}) => {

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, USES_HOOKS, HEADLESS} = testOptions;
const {PNG} = require('pngjs');
import {PNG} from 'pngjs';
// Firefox headful produces a different image.
const ffheadful = FFOX && !HEADLESS;

View file

@ -14,53 +14,53 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const util = require('util');
const vm = require('vm');
import path from 'path';
import util from 'util';
import vm from 'vm';
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS, CHANNEL} = testOptions;
it('should select single option', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.selectOption('select', 'blue');
expect(await page.evaluate(() => result.onInput)).toEqual(['blue']);
expect(await page.evaluate(() => result.onChange)).toEqual(['blue']);
expect(await page.evaluate(() => window['result'].onInput)).toEqual(['blue']);
expect(await page.evaluate(() => window['result'].onChange)).toEqual(['blue']);
});
it('should select single option by value', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.selectOption('select', { value: 'blue' });
expect(await page.evaluate(() => result.onInput)).toEqual(['blue']);
expect(await page.evaluate(() => result.onChange)).toEqual(['blue']);
expect(await page.evaluate(() => window['result'].onInput)).toEqual(['blue']);
expect(await page.evaluate(() => window['result'].onChange)).toEqual(['blue']);
});
it('should select single option by label', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.selectOption('select', { label: 'Indigo' });
expect(await page.evaluate(() => result.onInput)).toEqual(['indigo']);
expect(await page.evaluate(() => result.onChange)).toEqual(['indigo']);
expect(await page.evaluate(() => window['result'].onInput)).toEqual(['indigo']);
expect(await page.evaluate(() => window['result'].onChange)).toEqual(['indigo']);
});
it('should select single option by handle', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.selectOption('select', await page.$('[id=whiteOption]'));
expect(await page.evaluate(() => result.onInput)).toEqual(['white']);
expect(await page.evaluate(() => result.onChange)).toEqual(['white']);
expect(await page.evaluate(() => window['result'].onInput)).toEqual(['white']);
expect(await page.evaluate(() => window['result'].onChange)).toEqual(['white']);
});
it('should select single option by index', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.selectOption('select', { index: 2 });
expect(await page.evaluate(() => result.onInput)).toEqual(['brown']);
expect(await page.evaluate(() => result.onChange)).toEqual(['brown']);
expect(await page.evaluate(() => window['result'].onInput)).toEqual(['brown']);
expect(await page.evaluate(() => window['result'].onChange)).toEqual(['brown']);
});
it('should select single option by multiple attributes', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.selectOption('select', { value: 'green', label: 'Green' });
expect(await page.evaluate(() => result.onInput)).toEqual(['green']);
expect(await page.evaluate(() => result.onChange)).toEqual(['green']);
expect(await page.evaluate(() => window['result'].onInput)).toEqual(['green']);
expect(await page.evaluate(() => window['result'].onChange)).toEqual(['green']);
});
it('should not select single option when some attributes do not match', async({page, server}) => {
@ -71,13 +71,13 @@ it('should not select single option when some attributes do not match', async({p
it('should select only first option', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.selectOption('select', 'blue', 'green', 'red');
expect(await page.evaluate(() => result.onInput)).toEqual(['blue']);
expect(await page.evaluate(() => result.onChange)).toEqual(['blue']);
await page.selectOption('select', ['blue', 'green', 'red']);
expect(await page.evaluate(() => window['result'].onInput)).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');
await page.$eval('select', select => select.addEventListener('input', () => window.location = '/empty.html'));
await page.$eval('select', select => select.addEventListener('input', () => window.location.href = '/empty.html'));
await Promise.all([
page.selectOption('select', 'blue'),
page.waitForNavigation(),
@ -87,25 +87,25 @@ it('should not throw when select causes navigation', async({page, server}) => {
it('should select multiple options', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.evaluate(() => makeMultiple());
await page.evaluate(() => window['makeMultiple']());
await page.selectOption('select', ['blue', 'green', 'red']);
expect(await page.evaluate(() => result.onInput)).toEqual(['blue', 'green', 'red']);
expect(await page.evaluate(() => result.onChange)).toEqual(['blue', 'green', 'red']);
expect(await page.evaluate(() => window['result'].onInput)).toEqual(['blue', 'green', 'red']);
expect(await page.evaluate(() => window['result'].onChange)).toEqual(['blue', 'green', 'red']);
});
it('should select multiple options with attributes', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.evaluate(() => makeMultiple());
await page.evaluate(() => window['makeMultiple']());
await page.selectOption('select', [{ value: 'blue' }, { label: 'Green' }, { index: 4 }]);
expect(await page.evaluate(() => result.onInput)).toEqual(['blue', 'gray', 'green']);
expect(await page.evaluate(() => result.onChange)).toEqual(['blue', 'gray', 'green']);
expect(await page.evaluate(() => window['result'].onInput)).toEqual(['blue', 'gray', 'green']);
expect(await page.evaluate(() => window['result'].onChange)).toEqual(['blue', 'gray', 'green']);
});
it('should respect event bubbling', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.selectOption('select', 'blue');
expect(await page.evaluate(() => result.onBubblingInput)).toEqual(['blue']);
expect(await page.evaluate(() => result.onBubblingChange)).toEqual(['blue']);
expect(await page.evaluate(() => window['result'].onBubblingInput)).toEqual(['blue']);
expect(await page.evaluate(() => window['result'].onBubblingChange)).toEqual(['blue']);
});
it('should throw when element is not a <select>', async({page, server}) => {
@ -123,7 +123,7 @@ it('should return [] on no matched values', async({page, server}) => {
it('should return an array of matched values', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.evaluate(() => makeMultiple());
await page.evaluate(() => window['makeMultiple']());
const result = await page.selectOption('select', ['blue','black','magenta']);
expect(result.reduce((accumulator,current) => ['blue', 'black', 'magenta'].includes(current) && accumulator, true)).toEqual(true);
});
@ -142,7 +142,7 @@ it('should return [] on no values',async({page, server}) => {
it('should not allow null items',async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.evaluate(() => makeMultiple());
await page.evaluate(() => window['makeMultiple']());
let error = null
await page.selectOption('select', ['blue', null, 'black','magenta']).catch(e => error = e);
expect(error.message).toContain('options[1]: expected object, got null');
@ -150,7 +150,7 @@ it('should not allow null items',async({page, server}) => {
it('should unselect with null',async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.evaluate(() => makeMultiple());
await page.evaluate(() => window['makeMultiple']());
const result = await page.selectOption('select', ['blue', 'black','magenta']);
expect(result.reduce((accumulator,current) => ['blue', 'black', 'magenta'].includes(current) && accumulator, true)).toEqual(true);
await page.selectOption('select', null);
@ -159,7 +159,7 @@ it('should unselect with null',async({page, server}) => {
it('should deselect all options when passed no values for a multiple select',async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.evaluate(() => makeMultiple());
await page.evaluate(() => window['makeMultiple']());
await page.selectOption('select', ['blue','black','magenta']);
await page.selectOption('select', []);
expect(await page.$eval('select', select => Array.from(select.options).every(option => !option.selected))).toEqual(true);
@ -178,7 +178,7 @@ it('should throw if passed wrong types', async({page, server}) => {
error = null;
try {
await page.selectOption('select', 12);
await page.selectOption('select', 12 as any);
} catch (e) {
error = e;
}
@ -186,7 +186,7 @@ it('should throw if passed wrong types', async({page, server}) => {
error = null;
try {
await page.selectOption('select', { value: 12 });
await page.selectOption('select', { value: 12 } as any);
} catch (e) {
error = e;
}
@ -194,7 +194,7 @@ it('should throw if passed wrong types', async({page, server}) => {
error = null;
try {
await page.selectOption('select', { label: 12 });
await page.selectOption('select', { label: 12 } as any);
} catch (e) {
error = e;
}
@ -202,7 +202,7 @@ it('should throw if passed wrong types', async({page, server}) => {
error = null;
try {
await page.selectOption('select', { index: '12' });
await page.selectOption('select', { index: '12' } as any);
} catch (e) {
error = e;
}
@ -213,6 +213,6 @@ it('should work when re-defining top-level Event class', async({page, server}) =
await page.goto(server.PREFIX + '/input/select.html');
await page.evaluate(() => window.Event = null);
await page.selectOption('select', 'blue');
expect(await page.evaluate(() => result.onInput)).toEqual(['blue']);
expect(await page.evaluate(() => result.onChange)).toEqual(['blue']);
expect(await page.evaluate(() => window['result'].onInput)).toEqual(['blue']);
expect(await page.evaluate(() => window['result'].onChange)).toEqual(['blue']);
});

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const util = require('util');
const vm = require('vm');
import path from 'path';
import util from 'util';
import vm from 'vm';
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS, CHANNEL} = testOptions;
const expectedOutput = '<html><head></head><body><div>hello</div></body></html>';

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const fs = require('fs');
const path = require('path');
const utils = require('./utils');
import fs from 'fs';
import path from 'path';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, MAC, WIN} = testOptions;
@ -79,7 +79,7 @@ it('should override extra headers from browser context', async({browser, server}
it('should throw for non-string header values', async({page, server}) => {
let error = null;
try {
await page.setExtraHTTPHeaders({ 'foo': 1 });
await page.setExtraHTTPHeaders({ 'foo': 1 as any });
} catch (e) {
error = e;
}

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const fs = require('fs');
const formidable = require('formidable');
import path from 'path';
import fs from 'fs';
import formidable from 'formidable';
const FILE_TO_UPLOAD = path.join(__dirname, '/assets/file-to-upload.txt');

View file

@ -14,11 +14,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
const path = require('path');
const url = require('url');
import utils from './utils';
import path from 'path';
import url from 'url';
import { Route } from '..';
const {FFOX, CHROMIUM, WEBKIT, ASSETS_DIR, MAC, WIN} = testOptions;
it('should pick up ongoing navigation', async({page, server}) => {
@ -35,7 +36,7 @@ it('should pick up ongoing navigation', async({page, server}) => {
});
it('should respect timeout', async({page, server}) => {
server.setRoute('/one-style.css', (req, res) => response = res);
server.setRoute('/one-style.css', (req, res) => void 0);
await page.goto(server.PREFIX + '/one-style.html', {waitUntil: 'domcontentloaded'});
const error = await page.waitForLoadState('load', { timeout: 1 }).catch(e => e);
expect(error.message).toContain('page.waitForLoadState: Timeout 1ms exceeded.');
@ -48,13 +49,13 @@ it('should resolve immediately if loaded', async({page, server}) => {
it('should throw for bad state', async({page, server}) => {
await page.goto(server.PREFIX + '/one-style.html');
const error = await page.waitForLoadState('bad').catch(e => e);
const error = await page.waitForLoadState('bad' as any).catch(e => e);
expect(error.message).toContain(`state: expected one of (load|domcontentloaded|networkidle)`);
});
it('should resolve immediately if load state matches', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
server.setRoute('/one-style.css', (req, res) => response = res);
server.setRoute('/one-style.css', (req, res) => void 0);
await page.goto(server.PREFIX + '/one-style.html', {waitUntil: 'domcontentloaded'});
await page.waitForLoadState('domcontentloaded');
});
@ -63,7 +64,7 @@ it('should work with pages that have loaded before being connected to', async({p
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window._popup = window.open(document.location.href)),
page.evaluate(() => window["_popup"] = window.open(document.location.href)),
]);
// The url is about:blank in FF.
// expect(popup.url()).toBe(server.EMPTY_PAGE);
@ -152,7 +153,7 @@ it('should resolve after popup load', async({browser, server}) => {
const [popup] = await Promise.all([
page.waitForEvent('popup'),
server.waitForRequest('/one-style.css'),
page.evaluate(url => window.popup = window.open(url), server.PREFIX + '/one-style.html'),
page.evaluate(url => window["popup"] = window.open(url), server.PREFIX + '/one-style.html'),
]);
let resolved = false;
const loadSatePromise = popup.waitForLoadState().then(() => resolved = true);
@ -171,7 +172,7 @@ it('should work for frame', async({page, server}) => {
await page.goto(server.PREFIX + '/frames/one-frame.html');
const frame = page.frames()[1];
const requestPromise = new Promise(resolve => page.route(server.PREFIX + '/one-style.css',resolve));
const requestPromise = new Promise<Route>(resolve => page.route(server.PREFIX + '/one-style.css',resolve));
await frame.goto(server.PREFIX + '/one-style.html', {waitUntil: 'domcontentloaded'});
const request = await requestPromise;
let resolved = false;

View file

@ -14,11 +14,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
import utils from './utils';
import path from 'path';
import url from 'url';
import { Frame } from '..';
const utils = require('./utils');
const path = require('path');
const url = require('url');
const {FFOX, CHROMIUM, WEBKIT, ASSETS_DIR, MAC, WIN} = testOptions;
it('should work', async({page, server}) => {
@ -145,7 +147,7 @@ it('should work with DOM history.back()/history.forward()', async({page, server}
it.fail(FFOX)('should work when subframe issues window.stop()', async({page, server}) => {
server.setRoute('/frames/style.css', (req, res) => {});
const navigationPromise = page.goto(server.PREFIX + '/frames/one-frame.html');
const frame = await new Promise(f => page.once('frameattached', f));
const frame = await new Promise<Frame>(f => page.once('frameattached', f));
await new Promise(fulfill => page.on('framenavigated', f => {
if (f === frame)
fulfill();
@ -243,7 +245,7 @@ it('should fail when frame detaches', async({page, server}) => {
let error = null;
await Promise.all([
frame.waitForNavigation().catch(e => error = e),
frame.evaluate('window.location = "/empty.html"'),
frame.evaluate('window.location.href = "/empty.html"'),
page.evaluate('setTimeout(() => document.querySelector("iframe").remove())'),
]).catch(e => error = e);
expect(error.message).toContain('waiting for navigation until "load"');

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const util = require('util');
const vm = require('vm');
import path from 'path';
import util from 'util';
import vm from 'vm';
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS, CHANNEL} = testOptions;
it('should work', async({page, server}) => {

View file

@ -14,11 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const util = require('util');
const vm = require('vm');
import path from 'path';
import util from 'util';
import vm from 'vm';
const {FFOX, CHROMIUM, WEBKIT, WIN, USES_HOOKS, CHANNEL} = testOptions;
it('should work', async({page, server}) => {
@ -50,7 +50,7 @@ it('should respect default timeout', async({page, playwright}) => {
it('should work with predicate', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const [response] = await Promise.all([
page.waitForEvent('response', response => response.url() === server.PREFIX + '/digits/2.png'),
page.waitForEvent('request', response => response.url() === server.PREFIX + '/digits/2.png'),
page.evaluate(() => {
fetch('/digits/1.png');
fetch('/digits/2.png');

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, WEBKIT, LINUX, HEADLESS} = testOptions;
@ -36,7 +36,7 @@ it.skip(WEBKIT)('should deny permission when not listed', async({page, server, c
it.skip(WEBKIT)('should fail when bad permission is given', async({page, server, context}) => {
await page.goto(server.EMPTY_PAGE);
let error = {};
let error: Error;
await context.grantPermissions(['foo'], { origin: server.EMPTY_PAGE }).catch(e => error = e);
expect(error.message).toContain('Unknown permission: foo');
});

View file

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const {FFOX, CHROMIUM, WEBKIT, MAC} = testOptions;
@ -31,7 +31,7 @@ it('should inherit user agent from browser context', async function({browser, se
page.click('a'),
]);
await popup.waitForLoadState('domcontentloaded');
const userAgent = await popup.evaluate(() => window.initialUserAgent);
const userAgent = await popup.evaluate(() => window["initialUserAgent"]);
const request = await requestPromise;
await context.close();
expect(userAgent).toBe('hey');
@ -63,7 +63,7 @@ it('should inherit extra headers from browser context', async function({browser,
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
const requestPromise = server.waitForRequest('/dummy.html');
await page.evaluate(url => window._popup = window.open(url), server.PREFIX + '/dummy.html');
await page.evaluate(url => window["_popup"] = window.open(url), server.PREFIX + '/dummy.html');
const request = await requestPromise;
await context.close();
expect(request.headers['foo']).toBe('bar');
@ -91,7 +91,7 @@ it('should inherit http credentials from browser context', async function({brows
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window._popup = window.open(url), server.PREFIX + '/title.html'),
page.evaluate(url => window["_popup"] = window.open(url), server.PREFIX + '/title.html'),
]);
await popup.waitForLoadState('domcontentloaded');
expect(await popup.title()).toBe('Woof-Woof');
@ -159,7 +159,7 @@ it('should respect routes from browser context', async function({browser, server
});
await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window.__popup = window.open(url), server.EMPTY_PAGE),
page.evaluate(url => window["__popup"] = window.open(url), server.EMPTY_PAGE),
]);
expect(intercepted).toBe(true);
await context.close();
@ -167,12 +167,12 @@ it('should respect routes from browser context', async function({browser, server
it('BrowserContext.addInitScript should apply to an in-process popup', async function({browser, server}) {
const context = await browser.newContext();
await context.addInitScript(() => window.injected = 123);
await context.addInitScript(() => window['injected'] = 123);
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
const injected = await page.evaluate(() => {
const win = window.open('about:blank');
return win.injected;
return win['injected'];
});
await context.close();
expect(injected).toBe(123);
@ -180,7 +180,7 @@ it('BrowserContext.addInitScript should apply to an in-process popup', async fun
it('BrowserContext.addInitScript should apply to a cross-process popup', async function({browser, server}) {
const context = await browser.newContext();
await context.addInitScript(() => window.injected = 123);
await context.addInitScript(() => window['injected'] = 123);
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
@ -205,7 +205,7 @@ it('should expose function from browser context', async function({browser, serve
await page.goto(server.EMPTY_PAGE);
const added = await page.evaluate(async () => {
const win = window.open('about:blank');
return win.add(9, 4);
return win['add'](9, 4);
});
await context.close();
expect(added).toBe(13);
@ -230,7 +230,7 @@ it('should not dispatch binding on a closed page', async function({browser, serv
}),
page.evaluate(async () => {
const win = window.open('about:blank');
win.add(9, 4);
win['add'](9, 4);
win.close();
}),
]);

View file

@ -13,10 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const socks = require('socksv5');
const utils = require('./utils');
import socks from 'socksv5';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, MAC, HEADLESS} = testOptions;
it('should use proxy', async ({browserType, defaultBrowserOptions, server}) => {

View file

@ -14,10 +14,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const utils = require('./utils');
import path from 'path';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, CHANNEL, USES_HOOKS} = testOptions;
it('should query existing element with css selector', async({page, server}) => {

View file

@ -14,12 +14,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const fs = require('fs');
const path = require('path');
const { helper } = require('../lib/helper');
const vm = require('vm');
import fs from 'fs';
import path from 'path';
import { helper } from '../lib/helper';
import vm from 'vm';
const {FFOX, CHROMIUM, WEBKIT, HEADLESS} = testOptions;
it('should work', async({page, server}) => {

View file

@ -14,12 +14,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const fs = require('fs');
const path = require('path');
const { helper } = require('../lib/helper');
const vm = require('vm');
import fs from 'fs';
import path from 'path';
import { helper } from '../lib/helper';
import vm from 'vm';
const {FFOX, CHROMIUM, WEBKIT, HEADLESS} = testOptions;
it('should work', async({page, server}) => {
@ -106,7 +106,7 @@ it('should stringify intercepted request response headers', async({page, server}
route.fulfill({
status: 200,
headers: {
'foo': true
'foo': 'true'
},
body: 'Yo, page!'
});
@ -123,7 +123,7 @@ it('should not modify the headers sent to the server', async({page, server}) =>
const interceptedRequests = [];
//this is just to enable request interception, which disables caching in chromium
await page.route(server.PREFIX + '/unused');
await page.route(server.PREFIX + '/unused', () => {});
server.setRoute('/something', (request, response) => {
interceptedRequests.push(request);

View file

@ -13,7 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
import { FirefoxBrowser } from '..';
const fs = require('fs');
const os = require('os');
@ -22,6 +23,12 @@ const url = require('url');
const {mkdtempAsync, removeFolderAsync} = require('./utils');
const {FFOX, CHROMIUM, WEBKIT, MAC, LINUX, WIN, HEADLESS, USES_HOOKS} = testOptions;
declare global {
interface FixtureState {
persistentDirectory: string;
firefox: FirefoxBrowser;
}
}
registerFixture('persistentDirectory', async ({}, test) => {
const persistentDirectory = await mkdtempAsync(path.join(os.tmpdir(), 'playwright-test-'));

View file

@ -14,10 +14,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const utils = require('./utils');
import path from 'path';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, CHANNEL, USES_HOOKS} = testOptions;
it('should work for open shadow roots', async({page, server}) => {
@ -102,7 +102,7 @@ it('should work with comma inside text', async({page}) => {
it('should work with attribute selectors', async({page}) => {
await page.setContent(`<div attr="hello world" attr2="hello-''>>foo=bar[]" attr3="] span"><span></span></div>`);
await page.evaluate(() => window.div = document.querySelector('div'));
await page.evaluate(() => window['div'] = document.querySelector('div'));
const selectors = [
`[attr="hello world"]`,
`[attr = "hello world"]`,
@ -118,8 +118,8 @@ it('should work with attribute selectors', async({page}) => {
`[attr2 $="foo=bar[]"]`,
];
for (const selector of selectors)
expect(await page.$eval(selector, e => e === div)).toBe(true);
expect(await page.$eval(`[attr*=hello] span`, e => e.parentNode === div)).toBe(true);
expect(await page.$eval(`[attr*=hello] >> span`, e => e.parentNode === div)).toBe(true);
expect(await page.$eval(`[attr3="] span"] >> span`, e => e.parentNode === div)).toBe(true);
expect(await page.$eval(selector, e => e === window['div'])).toBe(true);
expect(await page.$eval(`[attr*=hello] span`, e => e.parentNode === window['div'])).toBe(true);
expect(await page.$eval(`[attr*=hello] >> span`, e => e.parentNode === window['div'])).toBe(true);
expect(await page.$eval(`[attr3="] span"] >> span`, e => e.parentNode === window['div'])).toBe(true);
});

View file

@ -14,10 +14,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const utils = require('./utils');
import path from 'path';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, CHANNEL, USES_HOOKS} = testOptions;
it('should work for open shadow roots', async({page, server}) => {

View file

@ -14,10 +14,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const utils = require('./utils');
import path from 'path';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, CHANNEL, USES_HOOKS} = testOptions;
it('should work', async ({playwright, page}) => {
@ -34,7 +34,7 @@ it('should work', async ({playwright, page}) => {
});
await utils.registerEngine(playwright, 'tag', `(${createTagSelector.toString()})()`);
await page.setContent('<div><span></span></div><div></div>');
expect(await playwright.selectors._createSelector('tag', await page.$('div'))).toBe('DIV');
expect(await (playwright.selectors as any)._createSelector('tag', await page.$('div'))).toBe('DIV');
expect(await page.$eval('tag=DIV', e => e.nodeName)).toBe('DIV');
expect(await page.$eval('tag=SPAN', e => e.nodeName)).toBe('SPAN');
expect(await page.$$eval('tag=DIV', es => es.length)).toBe(2);
@ -54,26 +54,26 @@ it('should work in main and isolated world', async ({playwright, page}) => {
const createDummySelector = () => ({
create(root, target) { },
query(root, selector) {
return window.__answer;
return window['__answer'];
},
queryAll(root, selector) {
return [document.body, document.documentElement, window.__answer];
return [document.body, document.documentElement, window['__answer']];
}
});
await utils.registerEngine(playwright, 'main', createDummySelector);
await utils.registerEngine(playwright, 'isolated', createDummySelector, { contentScript: true });
await page.setContent('<div><span><section></section></span></div>');
await page.evaluate(() => window.__answer = document.querySelector('span'));
await page.evaluate(() => window['__answer'] = document.querySelector('span'));
// Works in main if asked.
expect(await page.$eval('main=ignored', e => e.nodeName)).toBe('SPAN');
expect(await page.$eval('css=div >> main=ignored', e => e.nodeName)).toBe('SPAN');
expect(await page.$$eval('main=ignored', es => window.__answer !== undefined)).toBe(true);
expect(await page.$$eval('main=ignored', es => window['__answer'] !== undefined)).toBe(true);
expect(await page.$$eval('main=ignored', es => es.filter(e => e).length)).toBe(3);
// Works in isolated by default.
expect(await page.$('isolated=ignored')).toBe(null);
expect(await page.$('css=div >> isolated=ignored')).toBe(null);
// $$eval always works in main, to avoid adopting nodes one by one.
expect(await page.$$eval('isolated=ignored', es => window.__answer !== undefined)).toBe(true);
expect(await page.$$eval('isolated=ignored', es => window['__answer'] !== undefined)).toBe(true);
expect(await page.$$eval('isolated=ignored', es => es.filter(e => e).length)).toBe(3);
// At least one engine in main forces all to be in main.
expect(await page.$eval('main=ignored >> isolated=ignored', e => e.nodeName)).toBe('SPAN');

View file

@ -14,10 +14,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const path = require('path');
const utils = require('./utils');
import path from 'path';
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, CHANNEL, USES_HOOKS} = testOptions;
it('query', async ({page}) => {
@ -101,18 +101,18 @@ it('query', async ({page}) => {
it('create', async ({playwright, page}) => {
await page.setContent(`<div>yo</div><div>"ya</div><div>ye ye</div>`);
expect(await playwright.selectors._createSelector('text', await page.$('div'))).toBe('yo');
expect(await playwright.selectors._createSelector('text', await page.$('div:nth-child(2)'))).toBe('"\\"ya"');
expect(await playwright.selectors._createSelector('text', await page.$('div:nth-child(3)'))).toBe('"ye ye"');
expect(await (playwright.selectors as any)._createSelector('text', await page.$('div'))).toBe('yo');
expect(await (playwright.selectors as any)._createSelector('text', await page.$('div:nth-child(2)'))).toBe('"\\"ya"');
expect(await (playwright.selectors as any)._createSelector('text', await page.$('div:nth-child(3)'))).toBe('"ye ye"');
await page.setContent(`<div>yo</div><div>yo<div>ya</div>hey</div>`);
expect(await playwright.selectors._createSelector('text', await page.$('div:nth-child(2)'))).toBe('hey');
expect(await (playwright.selectors as any)._createSelector('text', await page.$('div:nth-child(2)'))).toBe('hey');
await page.setContent(`<div> yo <div></div>ya</div>`);
expect(await playwright.selectors._createSelector('text', await page.$('div'))).toBe('yo');
expect(await (playwright.selectors as any)._createSelector('text', await page.$('div'))).toBe('yo');
await page.setContent(`<div> "yo <div></div>ya</div>`);
expect(await playwright.selectors._createSelector('text', await page.$('div'))).toBe('" \\"yo "');
expect(await (playwright.selectors as any)._createSelector('text', await page.$('div'))).toBe('" \\"yo "');
});
it('should be case sensitive if quotes are specified', async({page}) => {

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, CHANNEL} = testOptions;
it('should timeout', async({page, server}) => {
@ -28,14 +28,14 @@ it('should timeout', async({page, server}) => {
it('should accept a string', async({page, server}) => {
const watchdog = page.waitForFunction('window.__FOO === 1');
await page.evaluate(() => window.__FOO = 1);
await page.evaluate(() => window['__FOO'] = 1);
await watchdog;
});
it('should work when resolved right before execution context disposal', async({page, server}) => {
await page.addInitScript(() => window.__RELOADED = true);
await page.addInitScript(() => window['__RELOADED'] = true);
await page.waitForFunction(() => {
if (!window.__RELOADED)
if (!window['__RELOADED'])
window.location.reload();
return true;
});
@ -44,11 +44,11 @@ it('should work when resolved right before execution context disposal', async({p
it('should poll on interval', async({page, server}) => {
const polling = 100;
const timeDelta = await page.waitForFunction(() => {
if (!window.__startTime) {
window.__startTime = Date.now();
if (!window['__startTime']) {
window['__startTime'] = Date.now();
return false;
}
return Date.now() - window.__startTime;
return Date.now() - window['__startTime'];
}, {}, {polling});
expect(await timeDelta.jsonValue()).not.toBeLessThan(polling);
});
@ -58,8 +58,8 @@ it('should avoid side effects after timeout', async({page, server}) => {
page.on('console', () => ++counter);
const error = await page.waitForFunction(() => {
window.counter = (window.counter || 0) + 1;
console.log(window.counter);
window['counter'] = (window['counter'] || 0) + 1;
console.log(window['counter']);
}, {}, { polling: 1, timeout: 1000 }).catch(e => e);
const savedCounter = counter;
@ -70,13 +70,13 @@ it('should avoid side effects after timeout', async({page, server}) => {
});
it('should throw on polling:mutation', async({page, server}) => {
const error = await page.waitForFunction(() => true, {}, {polling: 'mutation'}).catch(e => e);
const error = await page.waitForFunction(() => true, {}, {polling: 'mutation' as any}).catch(e => e);
expect(error.message).toContain('Unknown polling option: mutation');
});
it('should poll on raf', async({page, server}) => {
const watchdog = page.waitForFunction(() => window.__FOO === 'hit', {}, {polling: 'raf'});
await page.evaluate(() => window.__FOO = 'hit');
const watchdog = page.waitForFunction(() => window['__FOO'] === 'hit', {}, {polling: 'raf'});
await page.evaluate(() => window['__FOO'] = 'hit');
await watchdog;
});
@ -87,15 +87,16 @@ it('should fail with predicate throwing on first call', async({page, server}) =>
it('should fail with predicate throwing sometimes', async({page, server}) => {
const error = await page.waitForFunction(() => {
window.counter = (window.counter || 0) + 1;
if (window.counter === 3)
window['counter'] = (window['counter'] || 0) + 1;
if (window['counter'] === 3)
throw new Error('Bad counter!');
return window.counter === 5 ? 'result' : false;
return window['counter'] === 5 ? 'result' : false;
}).catch(e => e);
expect(error.message).toContain('Bad counter!');
});
it('should fail with ReferenceError on wrong page', async({page, server}) => {
// @ts-ignore
const error = await page.waitForFunction(() => globalVar === 123).catch(e => e);
expect(error.message).toContain('globalVar');
});
@ -105,8 +106,8 @@ it('should work with strict CSP policy', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
let error = null;
await Promise.all([
page.waitForFunction(() => window.__FOO === 'hit', {}, {polling: 'raf'}).catch(e => error = e),
page.evaluate(() => window.__FOO = 'hit')
page.waitForFunction(() => window['__FOO'] === 'hit', {}, {polling: 'raf'}).catch(e => error = e),
page.evaluate(() => window['__FOO'] = 'hit')
]);
expect(error).toBe(null);
});
@ -114,7 +115,7 @@ it('should work with strict CSP policy', async({page, server}) => {
it('should throw on bad polling value', async({page, server}) => {
let error = null;
try {
await page.waitForFunction(() => !!document.body, {}, {polling: 'unknown'});
await page.waitForFunction(() => !!document.body, {}, {polling: 'unknown' as any});
} catch (e) {
error = e;
}
@ -169,11 +170,11 @@ it('should respect default timeout', async({page, playwright}) => {
it('should disable timeout when its set to 0', async({page}) => {
const watchdog = page.waitForFunction(() => {
window.__counter = (window.__counter || 0) + 1;
return window.__injected;
window['__counter'] = (window['__counter'] || 0) + 1;
return window["__injected"];
}, {}, {timeout: 0, polling: 10});
await page.waitForFunction(() => window.__counter > 10);
await page.evaluate(() => window.__injected = true);
await page.waitForFunction(() => window['__counter'] > 10);
await page.evaluate(() => window["__injected"] = true);
await watchdog;
});
@ -186,16 +187,16 @@ it('should survive cross-process navigation', async({page, server}) => {
expect(fooFound).toBe(false);
await page.goto(server.CROSS_PROCESS_PREFIX + '/grid.html');
expect(fooFound).toBe(false);
await page.evaluate(() => window.__FOO = 1);
await page.evaluate(() => window['__FOO'] = 1);
await waitForFunction;
expect(fooFound).toBe(true);
});
it('should survive navigations', async({page, server}) => {
const watchdog = page.waitForFunction(() => window.__done);
const watchdog = page.waitForFunction(() => window['__done']);
await page.goto(server.EMPTY_PAGE);
await page.goto(server.PREFIX + '/consolelog.html');
await page.evaluate(() => window.__done = true);
await page.evaluate(() => window['__done'] = true);
await watchdog;
});

View file

@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
const utils = require('./utils');
import utils from './utils';
const {FFOX, CHROMIUM, WEBKIT, CHANNEL} = testOptions;
async function giveItTimeToLog(frame) {
@ -28,13 +28,15 @@ const addElement = tag => document.body.appendChild(document.createElement(tag))
it('should throw on waitFor', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
let error;
await page.waitForSelector('*', { waitFor: 'attached' }).catch(e => error = e);
await page.waitForSelector('*', { waitFor: 'attached' } as any).catch(e => error = e);
expect(error.message).toContain('options.waitFor is not supported, did you mean options.state?');
});
it('should tolerate waitFor=visible', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.waitForSelector('*', { waitFor: 'visible' }).catch(e => error = e);
let error = false;
await page.waitForSelector('*', { waitFor: 'visible' } as any).catch(() => error = true);
expect(error).toBe(false);
});
it('should immediately resolve promise if node exists', async({page, server}) => {
@ -316,25 +318,25 @@ it('should have correct stack trace for timeout', async({page, server}) => {
it('should throw for unknown state option', async({page, server}) => {
await page.setContent('<section>test</section>');
const error = await page.waitForSelector('section', { state: 'foo' }).catch(e => e);
const error = await page.waitForSelector('section', { state: 'foo' as any}).catch(e => e);
expect(error.message).toContain('state: expected one of (attached|detached|visible|hidden)');
});
it('should throw for visibility option', async({page, server}) => {
await page.setContent('<section>test</section>');
const error = await page.waitForSelector('section', { visibility: 'hidden' }).catch(e => e);
const error = await page.waitForSelector('section', { visibility: 'hidden' } as any).catch(e => e);
expect(error.message).toContain('options.visibility is not supported, did you mean options.state?');
});
it('should throw for true state option', async({page, server}) => {
await page.setContent('<section>test</section>');
const error = await page.waitForSelector('section', { state: true }).catch(e => e);
const error = await page.waitForSelector('section', { state: true as any }).catch(e => e);
expect(error.message).toContain('state: expected one of (attached|detached|visible|hidden)');
});
it('should throw for false state option', async({page, server}) => {
await page.setContent('<section>test</section>');
const error = await page.waitForSelector('section', { state: false }).catch(e => e);
const error = await page.waitForSelector('section', { state: false as any }).catch(e => e);
expect(error.message).toContain('state: expected one of (attached|detached|visible|hidden)');
});

View file

@ -14,7 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require('./base.fixture');
import './base.fixture';
import { ConsoleMessage } from '..';
const {FFOX, CHROMIUM, WEBKIT} = testOptions;
@ -52,7 +53,7 @@ it('should report console logs', async function({page}) {
});
it('should have JSHandles for console logs', async function({page}) {
const logPromise = new Promise(x => page.on('console', x));
const logPromise = new Promise<ConsoleMessage>(x => page.on('console', x));
await page.evaluate(() => new Worker(URL.createObjectURL(new Blob(['console.log(1,2,3,this)'], {type: 'application/javascript'}))));
const log = await logPromise;
expect(log.text()).toBe('1 2 3 JSHandle@object');
@ -68,7 +69,7 @@ it('should evaluate', async function({page}) {
});
it('should report errors', async function({page}) {
const errorPromise = new Promise(x => page.on('pageerror', x));
const errorPromise = new Promise<Error>(x => page.on('pageerror', x));
await page.evaluate(() => new Worker(URL.createObjectURL(new Blob([`
setTimeout(() => {
// Do a console.log just to check that we do not confuse it with an error.

View file

@ -21,9 +21,9 @@ export class TestServer {
enableGzip(path: string);
setCSP(path: string, csp: string);
stop(): Promise<void>;
setRoute(path: string, handler: (message: IncomingMessage, response: ServerResponse) => void);
setRoute(path: string, handler: (message: IncomingMessage & {postBody: Buffer}, response: ServerResponse) => void);
setRedirect(from: string, to: string);
waitForRequest(path: string): Promise<IncomingMessage>;
waitForRequest(path: string): Promise<IncomingMessage & {postBody: Buffer}>;
reset();
serveFile(request: IncomingMessage, response: ServerResponse, pathName: string);