api(browserType): remove devices, errors (#1368)

This commit is contained in:
Pavel Feldman 2020-03-12 17:58:00 -07:00 committed by GitHub
parent 0d7cb29329
commit 9aa56a6b9e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 122 additions and 203 deletions

View file

@ -3706,9 +3706,7 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
<!-- GEN:toc --> <!-- GEN:toc -->
- [browserType.connect(options)](#browsertypeconnectoptions) - [browserType.connect(options)](#browsertypeconnectoptions)
- [browserType.devices](#browsertypedevices)
- [browserType.downloadBrowserIfNeeded([progress])](#browsertypedownloadbrowserifneededprogress) - [browserType.downloadBrowserIfNeeded([progress])](#browsertypedownloadbrowserifneededprogress)
- [browserType.errors](#browsertypeerrors)
- [browserType.executablePath()](#browsertypeexecutablepath) - [browserType.executablePath()](#browsertypeexecutablepath)
- [browserType.launch([options])](#browsertypelaunchoptions) - [browserType.launch([options])](#browsertypelaunchoptions)
- [browserType.launchPersistentContext(userDataDir, [options])](#browsertypelaunchpersistentcontextuserdatadir-options) - [browserType.launchPersistentContext(userDataDir, [options])](#browsertypelaunchpersistentcontextuserdatadir-options)
@ -3724,56 +3722,12 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
This methods attaches Playwright to an existing browser instance. This methods attaches Playwright to an existing browser instance.
#### browserType.devices
- returns: <[Object]>
Returns a list of devices to be used with [`browser.newContext([options])`](#browsernewcontextoptions) and [`browser.newPage([options])`](#browsernewpageoptions). Actual list of devices can be found in [src/deviceDescriptors.ts](https://github.com/Microsoft/playwright/blob/master/src/deviceDescriptors.ts).
```js
const { webkit } = require('playwright');
const iPhone = webkit.devices['iPhone 6'];
(async () => {
const browser = await webkit.launch();
const context = await browser.newContext({
viewport: iPhone.viewport,
userAgent: iPhone.userAgent
});
const page = await context.newPage();
await page.goto('https://example.com');
// other actions...
await browser.close();
})();
```
#### browserType.downloadBrowserIfNeeded([progress]) #### browserType.downloadBrowserIfNeeded([progress])
- `progress` <[function]> If download is initiated, this function is called with two parameters: `downloadedBytes` and `totalBytes`. - `progress` <[function]> If download is initiated, this function is called with two parameters: `downloadedBytes` and `totalBytes`.
- returns: <[Promise]> promise that resolves when browser is successfully downloaded. - returns: <[Promise]> promise that resolves when browser is successfully downloaded.
Download browser binary if it is missing. Download browser binary if it is missing.
#### browserType.errors
- returns: <[Object]>
- `TimeoutError` <[function]> A class of [TimeoutError].
Playwright methods might throw errors if they are unable to fulfill a request. For example, [page.waitForSelector(selector[, options])](#pagewaitforelementselector-options)
might fail if the selector doesn't match any nodes during the given timeframe.
For certain types of errors Playwright uses specific error classes.
These classes are available via [`browserType.errors`](#browsertypeerrors) or [`playwright.errors`](#playwrighterrors).
An example of handling a timeout error:
```js
const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
try {
await page.waitForSelector('.foo');
} catch (e) {
if (e instanceof webkit.errors.TimeoutError) {
// Do something if this is a timeout.
}
}
```
#### browserType.executablePath() #### browserType.executablePath()
- returns: <[string]> A path where Playwright expects to find a bundled browser. - returns: <[string]> A path where Playwright expects to find a bundled browser.

View file

@ -14,8 +14,6 @@
* limitations under the License. * limitations under the License.
*/ */
import * as types from '../types';
import { TimeoutError } from '../errors';
import { Browser, ConnectOptions } from '../browser'; import { Browser, ConnectOptions } from '../browser';
import { BrowserContext } from '../browserContext'; import { BrowserContext } from '../browserContext';
import { BrowserServer } from './browserServer'; import { BrowserServer } from './browserServer';
@ -50,6 +48,4 @@ export interface BrowserType {
launchPersistentContext(userDataDir: string, options?: LaunchOptions): Promise<BrowserContext>; launchPersistentContext(userDataDir: string, options?: LaunchOptions): Promise<BrowserContext>;
connect(options: ConnectOptions): Promise<Browser>; connect(options: ConnectOptions): Promise<Browser>;
downloadBrowserIfNeeded(progress?: OnProgressCallback): Promise<void>; downloadBrowserIfNeeded(progress?: OnProgressCallback): Promise<void>;
devices: types.Devices;
errors: { TimeoutError: typeof TimeoutError };
} }

View file

@ -20,8 +20,6 @@ import * as os from 'os';
import * as path from 'path'; import * as path from 'path';
import * as util from 'util'; import * as util from 'util';
import { BrowserFetcher, OnProgressCallback, BrowserFetcherOptions } from '../server/browserFetcher'; import { BrowserFetcher, OnProgressCallback, BrowserFetcherOptions } from '../server/browserFetcher';
import { DeviceDescriptors } from '../deviceDescriptors';
import * as types from '../types';
import { assert, helper } from '../helper'; import { assert, helper } from '../helper';
import { CRBrowser } from '../chromium/crBrowser'; import { CRBrowser } from '../chromium/crBrowser';
import * as platform from '../platform'; import * as platform from '../platform';
@ -166,14 +164,6 @@ export class Chromium implements BrowserType {
return this._resolveExecutablePath().executablePath; return this._resolveExecutablePath().executablePath;
} }
get devices(): types.Devices {
return DeviceDescriptors;
}
get errors(): { TimeoutError: typeof TimeoutError } {
return { TimeoutError };
}
private _defaultArgs(options: BrowserArgOptions = {}, launchType: LaunchType, userDataDir: string, port: number): string[] { private _defaultArgs(options: BrowserArgOptions = {}, launchType: LaunchType, userDataDir: string, port: number): string[] {
const { const {
devtools = false, devtools = false,

View file

@ -21,14 +21,12 @@ import * as path from 'path';
import * as util from 'util'; import * as util from 'util';
import { ConnectOptions, LaunchType } from '../browser'; import { ConnectOptions, LaunchType } from '../browser';
import { BrowserContext } from '../browserContext'; import { BrowserContext } from '../browserContext';
import { DeviceDescriptors } from '../deviceDescriptors';
import { TimeoutError } from '../errors'; import { TimeoutError } from '../errors';
import { Events } from '../events'; import { Events } from '../events';
import { FFBrowser } from '../firefox/ffBrowser'; import { FFBrowser } from '../firefox/ffBrowser';
import { kBrowserCloseMessageId } from '../firefox/ffConnection'; import { kBrowserCloseMessageId } from '../firefox/ffConnection';
import { assert, helper } from '../helper'; import { assert, helper } from '../helper';
import * as platform from '../platform'; import * as platform from '../platform';
import * as types from '../types';
import { BrowserFetcher, BrowserFetcherOptions, OnProgressCallback } from './browserFetcher'; import { BrowserFetcher, BrowserFetcherOptions, OnProgressCallback } from './browserFetcher';
import { BrowserServer } from './browserServer'; import { BrowserServer } from './browserServer';
import { BrowserArgOptions, BrowserType, LaunchOptions } from './browserType'; import { BrowserArgOptions, BrowserType, LaunchOptions } from './browserType';
@ -174,14 +172,6 @@ export class Firefox implements BrowserType {
return this._resolveExecutablePath().executablePath; return this._resolveExecutablePath().executablePath;
} }
get devices(): types.Devices {
return DeviceDescriptors;
}
get errors(): { TimeoutError: typeof TimeoutError } {
return { TimeoutError };
}
private _defaultArgs(options: BrowserArgOptions = {}, launchType: LaunchType, userDataDir: string, port: number): string[] { private _defaultArgs(options: BrowserArgOptions = {}, launchType: LaunchType, userDataDir: string, port: number): string[] {
const { const {
devtools = false, devtools = false,

View file

@ -16,9 +16,6 @@
*/ */
import { BrowserFetcher, OnProgressCallback, BrowserFetcherOptions } from './browserFetcher'; import { BrowserFetcher, OnProgressCallback, BrowserFetcherOptions } from './browserFetcher';
import { DeviceDescriptors } from '../deviceDescriptors';
import { TimeoutError } from '../errors';
import * as types from '../types';
import { WKBrowser } from '../webkit/wkBrowser'; import { WKBrowser } from '../webkit/wkBrowser';
import { execSync } from 'child_process'; import { execSync } from 'child_process';
import { PipeTransport } from './pipeTransport'; import { PipeTransport } from './pipeTransport';
@ -163,14 +160,6 @@ export class WebKit implements BrowserType {
return this._resolveExecutablePath().executablePath; return this._resolveExecutablePath().executablePath;
} }
get devices(): types.Devices {
return DeviceDescriptors;
}
get errors(): { TimeoutError: typeof TimeoutError } {
return { TimeoutError };
}
_defaultArgs(options: BrowserArgOptions = {}, launchType: LaunchType, userDataDir: string, port: number): string[] { _defaultArgs(options: BrowserArgOptions = {}, launchType: LaunchType, userDataDir: string, port: number): string[] {
const { const {
devtools = false, devtools = false,

View file

@ -29,7 +29,7 @@ const TMP_FOLDER = path.join(os.tmpdir(), 'pw_tmp_folder-');
/** /**
* @type {TestSuite} * @type {TestSuite}
*/ */
module.exports.describe = function({testRunner, expect, defaultBrowserOptions, playwright, WIN}) { module.exports.describe = function({testRunner, expect, defaultBrowserOptions, browserType, WIN}) {
const {describe, xdescribe, fdescribe} = testRunner; const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner; const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner; const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
@ -50,17 +50,17 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
it('should throw with remote-debugging-pipe argument', async() => { it('should throw with remote-debugging-pipe argument', async() => {
const options = Object.assign({}, defaultBrowserOptions); const options = Object.assign({}, defaultBrowserOptions);
options.args = ['--remote-debugging-pipe'].concat(options.args || []); options.args = ['--remote-debugging-pipe'].concat(options.args || []);
const error = await playwright.launchServer(options).catch(e => e); const error = await browserType.launchServer(options).catch(e => e);
expect(error.message).toContain('Playwright manages remote debugging connection itself'); expect(error.message).toContain('Playwright manages remote debugging connection itself');
}); });
it('should throw with remote-debugging-port argument', async() => { it('should throw with remote-debugging-port argument', async() => {
const options = Object.assign({}, defaultBrowserOptions); const options = Object.assign({}, defaultBrowserOptions);
options.args = ['--remote-debugging-port=9222'].concat(options.args || []); options.args = ['--remote-debugging-port=9222'].concat(options.args || []);
const error = await playwright.launchServer(options).catch(e => e); const error = await browserType.launchServer(options).catch(e => e);
expect(error.message).toContain('Playwright manages remote debugging connection itself'); expect(error.message).toContain('Playwright manages remote debugging connection itself');
}); });
it('should open devtools when "devtools: true" option is given', async({server}) => { it('should open devtools when "devtools: true" option is given', async({server}) => {
const browser = await playwright.launch(Object.assign({devtools: true}, headfulOptions)); const browser = await browserType.launch(Object.assign({devtools: true}, headfulOptions));
const context = await browser.newContext(); const context = await browser.newContext();
const browserSession = await browser.createBrowserSession(); const browserSession = await browser.createBrowserSession();
await browserSession.send('Target.setDiscoverTargets', { discover: true }); await browserSession.send('Target.setDiscoverTargets', { discover: true });
@ -79,7 +79,7 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
describe('extensions', () => { describe('extensions', () => {
it('should return background pages', async() => { it('should return background pages', async() => {
const userDataDir = await makeUserDataDir(); const userDataDir = await makeUserDataDir();
const context = await playwright.launchPersistentContext(userDataDir, extensionOptions); const context = await browserType.launchPersistentContext(userDataDir, extensionOptions);
const backgroundPages = await context.backgroundPages(); const backgroundPages = await context.backgroundPages();
let backgroundPage = backgroundPages.length let backgroundPage = backgroundPages.length
? backgroundPages[0] ? backgroundPages[0]
@ -94,7 +94,7 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
describe('BrowserFetcher', function() { describe('BrowserFetcher', function() {
it('should download and extract linux binary', async({server}) => { it('should download and extract linux binary', async({server}) => {
const downloadsFolder = await mkdtempAsync(TMP_FOLDER); const downloadsFolder = await mkdtempAsync(TMP_FOLDER);
const browserFetcher = playwright._createBrowserFetcher({ const browserFetcher = browserType._createBrowserFetcher({
platform: 'linux', platform: 'linux',
path: downloadsFolder, path: downloadsFolder,
host: server.PREFIX host: server.PREFIX
@ -123,7 +123,7 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
describe('BrowserContext', function() { describe('BrowserContext', function() {
it('should not create pages automatically', async function() { it('should not create pages automatically', async function() {
const browser = await playwright.launch(); const browser = await browserType.launch();
const browserSession = await browser.createBrowserSession(); const browserSession = await browser.createBrowserSession();
const targets = []; const targets = [];
browserSession.on('Target.targetCreated', async ({targetInfo}) => { browserSession.on('Target.targetCreated', async ({targetInfo}) => {

View file

@ -17,7 +17,7 @@
/** /**
* @type {ChromiumTestSuite} * @type {ChromiumTestSuite}
*/ */
module.exports.describe = function({testRunner, expect, defaultBrowserOptions, playwright, FFOX, CHROMIUM, WEBKIT}) { module.exports.describe = function({testRunner, expect, defaultBrowserOptions, browserType, FFOX, CHROMIUM, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner; const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner; const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner; const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
@ -28,7 +28,7 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
describe('OOPIF', function() { describe('OOPIF', function() {
beforeAll(async function(state) { beforeAll(async function(state) {
state.browser = await playwright.launch(Object.assign({}, defaultBrowserOptions, { state.browser = await browserType.launch(Object.assign({}, defaultBrowserOptions, {
args: (defaultBrowserOptions.args || []).concat(['--site-per-process']), args: (defaultBrowserOptions.args || []).concat(['--site-per-process']),
})); }));
}); });
@ -65,7 +65,7 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
it.fail(true)('should report google.com frame with headful', async({server}) => { it.fail(true)('should report google.com frame with headful', async({server}) => {
// TODO: Support OOOPIF. @see https://github.com/GoogleChrome/puppeteer/issues/2548 // TODO: Support OOOPIF. @see https://github.com/GoogleChrome/puppeteer/issues/2548
// https://google.com is isolated by default in Chromium embedder. // https://google.com is isolated by default in Chromium embedder.
const browser = await playwright.launch(headfulOptions); const browser = await browserType.launch(headfulOptions);
const page = await browser.newPage(); const page = await browser.newPage();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.route('**/*', request => { await page.route('**/*', request => {

View file

@ -20,7 +20,7 @@ const path = require('path');
/** /**
* @type {ChromiumTestSuite} * @type {ChromiumTestSuite}
*/ */
module.exports.describe = function({testRunner, expect, defaultBrowserOptions, playwright, ASSETS_DIR}) { module.exports.describe = function({testRunner, expect, defaultBrowserOptions, browserType, ASSETS_DIR}) {
const {describe, xdescribe, fdescribe} = testRunner; const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner; const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner; const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
@ -28,7 +28,7 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
describe('Chromium.startTracing', function() { describe('Chromium.startTracing', function() {
beforeEach(async function(state) { beforeEach(async function(state) {
state.outputFile = path.join(ASSETS_DIR, `trace-${state.parallelIndex}.json`); state.outputFile = path.join(ASSETS_DIR, `trace-${state.parallelIndex}.json`);
state.browser = await playwright.launch(defaultBrowserOptions); state.browser = await browserType.launch(defaultBrowserOptions);
state.page = await state.browser.newPage(); state.page = await state.browser.newPage();
}); });
afterEach(async function(state) { afterEach(async function(state) {

View file

@ -18,7 +18,7 @@
/** /**
* @type {PageTestSuite} * @type {PageTestSuite}
*/ */
module.exports.describe = function({testRunner, expect, playwright, defaultBrowserOptions, MAC, FFOX, CHROMIUM, WEBKIT}) { module.exports.describe = function({testRunner, expect, browserType, defaultBrowserOptions, MAC, FFOX, CHROMIUM, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner; const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner; const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner; const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
@ -276,12 +276,12 @@ module.exports.describe = function({testRunner, expect, playwright, defaultBrows
} }
}); });
it.slow()('should isolate cookies between launches', async({server}) => { it.slow()('should isolate cookies between launches', async({server}) => {
const browser1 = await playwright.launch(defaultBrowserOptions); const browser1 = await browserType.launch(defaultBrowserOptions);
const context1 = await browser1.newContext(); const context1 = await browser1.newContext();
await context1.addCookies([{url: server.EMPTY_PAGE, name: 'cookie-in-context-1', value: 'value', expires: Date.now() / 1000 + 10000}]); await context1.addCookies([{url: server.EMPTY_PAGE, name: 'cookie-in-context-1', value: 'value', expires: Date.now() / 1000 + 10000}]);
await browser1.close(); await browser1.close();
const browser2 = await playwright.launch(defaultBrowserOptions); const browser2 = await browserType.launch(defaultBrowserOptions);
const context2 = await browser2.newContext(); const context2 = await browser2.newContext();
const cookies = await context2.cookies(); const cookies = await context2.cookies();
expect(cookies.length).toBe(0); expect(cookies.length).toBe(0);

View file

@ -20,7 +20,7 @@ const { makeUserDataDir, removeUserDataDir } = require('./utils');
/** /**
* @type {PageTestSuite} * @type {PageTestSuite}
*/ */
module.exports.describe = function ({ testRunner, expect, defaultBrowserOptions, playwright, WEBKIT }) { module.exports.describe = function ({ testRunner, expect, defaultBrowserOptions, browserType, WEBKIT }) {
const {describe, xdescribe, fdescribe} = testRunner; const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner; const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner; const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
@ -28,7 +28,7 @@ module.exports.describe = function ({ testRunner, expect, defaultBrowserOptions,
describe('launchPersistentContext()', function() { describe('launchPersistentContext()', function() {
beforeEach(async state => { beforeEach(async state => {
state.userDataDir = await makeUserDataDir(); state.userDataDir = await makeUserDataDir();
state.browserContext = await playwright.launchPersistentContext(state.userDataDir, defaultBrowserOptions); state.browserContext = await browserType.launchPersistentContext(state.userDataDir, defaultBrowserOptions);
state.page = await state.browserContext.newPage(); state.page = await state.browserContext.newPage();
}); });
afterEach(async state => { afterEach(async state => {

View file

@ -21,7 +21,7 @@ const {spawn, execSync} = require('child_process');
/** /**
* @type {TestSuite} * @type {TestSuite}
*/ */
module.exports.describe = function({testRunner, expect, product, playwright, playwrightPath, defaultBrowserOptions, WIN, FFOX, CHROMIUM, WEBKIT}) { module.exports.describe = function({testRunner, expect, product, browserType, playwrightPath, defaultBrowserOptions, WIN, FFOX, CHROMIUM, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner; const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner; const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner; const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
@ -58,7 +58,7 @@ module.exports.describe = function({testRunner, expect, product, playwright, pla
browserPid = +match[1]; browserPid = +match[1];
}); });
res.on('error', (...args) => console.log("ERROR", ...args)); res.on('error', (...args) => console.log("ERROR", ...args));
const browser = await playwright.connect({ wsEndpoint: await wsEndPointPromise }); const browser = await browserType.connect({ wsEndpoint: await wsEndPointPromise });
const promises = [ const promises = [
new Promise(resolve => browser.once('disconnected', resolve)), new Promise(resolve => browser.once('disconnected', resolve)),
new Promise(resolve => res.on('exit', resolve)), new Promise(resolve => res.on('exit', resolve)),

View file

@ -19,7 +19,7 @@ const { makeUserDataDir, removeUserDataDir } = require('./utils');
/** /**
* @type {TestSuite} * @type {TestSuite}
*/ */
module.exports.describe = function({testRunner, expect, playwright, defaultBrowserOptions, FFOX, CHROMIUM, WEBKIT, WIN}) { module.exports.describe = function({testRunner, expect, browserType, defaultBrowserOptions, FFOX, CHROMIUM, WEBKIT, WIN}) {
const {describe, xdescribe, fdescribe} = testRunner; const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner; const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner; const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
@ -34,7 +34,7 @@ module.exports.describe = function({testRunner, expect, playwright, defaultBrows
describe('Headful', function() { describe('Headful', function() {
it('should have default url when launching browser', async function() { it('should have default url when launching browser', async function() {
const userDataDir = await makeUserDataDir(); const userDataDir = await makeUserDataDir();
const browserContext = await playwright.launchPersistentContext(userDataDir, headfulOptions); const browserContext = await browserType.launchPersistentContext(userDataDir, headfulOptions);
const pages = (await browserContext.pages()).map(page => page.url()); const pages = (await browserContext.pages()).map(page => page.url());
expect(pages).toEqual(['about:blank']); expect(pages).toEqual(['about:blank']);
await browserContext.close(); await browserContext.close();
@ -44,13 +44,13 @@ module.exports.describe = function({testRunner, expect, playwright, defaultBrows
it.fail((WIN && CHROMIUM) || FFOX)('headless should be able to read cookies written by headful', async({server}) => { it.fail((WIN && CHROMIUM) || FFOX)('headless should be able to read cookies written by headful', async({server}) => {
const userDataDir = await makeUserDataDir(); const userDataDir = await makeUserDataDir();
// Write a cookie in headful chrome // Write a cookie in headful chrome
const headfulContext = await playwright.launchPersistentContext(userDataDir, headfulOptions); const headfulContext = await browserType.launchPersistentContext(userDataDir, headfulOptions);
const headfulPage = await headfulContext.newPage(); const headfulPage = await headfulContext.newPage();
await headfulPage.goto(server.EMPTY_PAGE); await headfulPage.goto(server.EMPTY_PAGE);
await headfulPage.evaluate(() => document.cookie = 'foo=true; expires=Fri, 31 Dec 9999 23:59:59 GMT'); await headfulPage.evaluate(() => document.cookie = 'foo=true; expires=Fri, 31 Dec 9999 23:59:59 GMT');
await headfulContext.close(); await headfulContext.close();
// Read the cookie from headless chrome // Read the cookie from headless chrome
const headlessContext = await playwright.launchPersistentContext(userDataDir, headlessOptions); const headlessContext = await browserType.launchPersistentContext(userDataDir, headlessOptions);
const headlessPage = await headlessContext.newPage(); const headlessPage = await headlessContext.newPage();
await headlessPage.goto(server.EMPTY_PAGE); await headlessPage.goto(server.EMPTY_PAGE);
const cookie = await headlessPage.evaluate(() => document.cookie); const cookie = await headlessPage.evaluate(() => document.cookie);
@ -61,7 +61,7 @@ module.exports.describe = function({testRunner, expect, playwright, defaultBrows
}); });
it.fail(FFOX)('should close browser with beforeunload page', async({server}) => { it.fail(FFOX)('should close browser with beforeunload page', async({server}) => {
const userDataDir = await makeUserDataDir(); const userDataDir = await makeUserDataDir();
const browserContext = await playwright.launchPersistentContext(userDataDir, headfulOptions); const browserContext = await browserType.launchPersistentContext(userDataDir, headfulOptions);
const page = await browserContext.newPage(); const page = await browserContext.newPage();
await page.goto(server.PREFIX + '/beforeunload.html'); await page.goto(server.PREFIX + '/beforeunload.html');
// We have to interact with a page so that 'beforeunload' handlers // We have to interact with a page so that 'beforeunload' handlers

View file

@ -23,15 +23,15 @@ const { makeUserDataDir, removeUserDataDir } = require('./utils');
/** /**
* @type {TestSuite} * @type {TestSuite}
*/ */
module.exports.describe = function({testRunner, expect, defaultBrowserOptions, playwright, playwrightPath, product, CHROMIUM, FFOX, WEBKIT, WIN}) { module.exports.describe = function({testRunner, expect, defaultBrowserOptions, playwright, browserType, playwrightPath, product, CHROMIUM, FFOX, WEBKIT, WIN}) {
const {describe, xdescribe, fdescribe} = testRunner; const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner; const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner; const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('Playwright', function() { describe('Playwright', function() {
describe('Playwright.launch', function() { describe('browserType.launch', function() {
it('should reject all promises when browser is closed', async() => { it('should reject all promises when browser is closed', async() => {
const browser = await playwright.launch(defaultBrowserOptions); const browser = await browserType.launch(defaultBrowserOptions);
const page = await (await browser.newContext()).newPage(); const page = await (await browser.newContext()).newPage();
let error = null; let error = null;
const neverResolves = page.evaluate(() => new Promise(r => {})).catch(e => error = e); const neverResolves = page.evaluate(() => new Promise(r => {})).catch(e => error = e);
@ -42,27 +42,27 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
it('should throw if userDataDir option is passed', async() => { it('should throw if userDataDir option is passed', async() => {
let waitError = null; let waitError = null;
const options = Object.assign({}, defaultBrowserOptions, {userDataDir: 'random-path'}); const options = Object.assign({}, defaultBrowserOptions, {userDataDir: 'random-path'});
await playwright.launch(options).catch(e => waitError = e); await browserType.launch(options).catch(e => waitError = e);
expect(waitError.message).toContain('launchPersistentContext'); expect(waitError.message).toContain('launchPersistentContext');
}); });
it('should throw if page argument is passed', async() => { it('should throw if page argument is passed', async() => {
let waitError = null; let waitError = null;
const options = Object.assign({}, defaultBrowserOptions, { args: ['http://example.com'] }); const options = Object.assign({}, defaultBrowserOptions, { args: ['http://example.com'] });
await playwright.launch(options).catch(e => waitError = e); await browserType.launch(options).catch(e => waitError = e);
expect(waitError.message).toContain('can not specify page'); expect(waitError.message).toContain('can not specify page');
}); });
it('should reject if executable path is invalid', async({server}) => { it('should reject if executable path is invalid', async({server}) => {
let waitError = null; let waitError = null;
const options = Object.assign({}, defaultBrowserOptions, {executablePath: 'random-invalid-path'}); const options = Object.assign({}, defaultBrowserOptions, {executablePath: 'random-invalid-path'});
await playwright.launch(options).catch(e => waitError = e); await browserType.launch(options).catch(e => waitError = e);
expect(waitError.message).toContain('Failed to launch'); expect(waitError.message).toContain('Failed to launch');
}); });
}); });
describe('Playwright.launchPersistentContext', function() { describe('browserType.launchPersistentContext', function() {
it('should have default URL when launching browser', async function() { it('should have default URL when launching browser', async function() {
const userDataDir = await makeUserDataDir(); const userDataDir = await makeUserDataDir();
const browserContext = await playwright.launchPersistentContext(userDataDir, defaultBrowserOptions); const browserContext = await browserType.launchPersistentContext(userDataDir, defaultBrowserOptions);
const pages = (await browserContext.pages()).map(page => page.url()); const pages = (await browserContext.pages()).map(page => page.url());
expect(pages).toEqual(['about:blank']); expect(pages).toEqual(['about:blank']);
await browserContext.close(); await browserContext.close();
@ -72,7 +72,7 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
const userDataDir = await makeUserDataDir(); const userDataDir = await makeUserDataDir();
const options = Object.assign({}, defaultBrowserOptions); const options = Object.assign({}, defaultBrowserOptions);
options.args = [server.EMPTY_PAGE].concat(options.args || []); options.args = [server.EMPTY_PAGE].concat(options.args || []);
const browserContext = await playwright.launchPersistentContext(userDataDir, options); const browserContext = await browserType.launchPersistentContext(userDataDir, options);
const pages = await browserContext.pages(); const pages = await browserContext.pages();
expect(pages.length).toBe(1); expect(pages.length).toBe(1);
const page = pages[0]; const page = pages[0];
@ -85,14 +85,14 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
}); });
}); });
describe('Playwright.launchServer', function() { describe('browserType.launchServer', function() {
it('should return child_process instance', async () => { it('should return child_process instance', async () => {
const browserServer = await playwright.launchServer(defaultBrowserOptions); const browserServer = await browserType.launchServer(defaultBrowserOptions);
expect(browserServer.process().pid).toBeGreaterThan(0); expect(browserServer.process().pid).toBeGreaterThan(0);
await browserServer.close(); await browserServer.close();
}); });
it('should fire close event', async () => { it('should fire close event', async () => {
const browserServer = await playwright.launchServer(defaultBrowserOptions); const browserServer = await browserType.launchServer(defaultBrowserOptions);
await Promise.all([ await Promise.all([
utils.waitEvent(browserServer, 'close'), utils.waitEvent(browserServer, 'close'),
browserServer.close(), browserServer.close(),
@ -100,22 +100,22 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
}); });
}); });
describe('Playwright.executablePath', function() { describe('browserType.executablePath', function() {
it('should work', async({server}) => { it('should work', async({server}) => {
const executablePath = playwright.executablePath(); const executablePath = browserType.executablePath();
expect(fs.existsSync(executablePath)).toBe(true); expect(fs.existsSync(executablePath)).toBe(true);
expect(fs.realpathSync(executablePath)).toBe(executablePath); expect(fs.realpathSync(executablePath)).toBe(executablePath);
}); });
}); });
describe('Playwright.name', function() { describe('browserType.name', function() {
it('should work', async({server}) => { it('should work', async({server}) => {
if (WEBKIT) if (WEBKIT)
expect(playwright.name()).toBe('webkit'); expect(browserType.name()).toBe('webkit');
else if (FFOX) else if (FFOX)
expect(playwright.name()).toBe('firefox'); expect(browserType.name()).toBe('firefox');
else if (CHROMIUM) else if (CHROMIUM)
expect(playwright.name()).toBe('chromium'); expect(browserType.name()).toBe('chromium');
else else
throw new Error('Unknown browser'); throw new Error('Unknown browser');
}); });
@ -137,16 +137,16 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
describe('Browser.isConnected', () => { describe('Browser.isConnected', () => {
it('should set the browser connected state', async () => { it('should set the browser connected state', async () => {
const browserServer = await playwright.launchServer({...defaultBrowserOptions }); const browserServer = await browserType.launchServer({...defaultBrowserOptions });
const remote = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const remote = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
expect(remote.isConnected()).toBe(true); expect(remote.isConnected()).toBe(true);
await remote.close(); await remote.close();
expect(remote.isConnected()).toBe(false); expect(remote.isConnected()).toBe(false);
await browserServer.close(); await browserServer.close();
}); });
it('should throw when used after isConnected returns false', async({server}) => { it('should throw when used after isConnected returns false', async({server}) => {
const browserServer = await playwright.launchServer({...defaultBrowserOptions }); const browserServer = await browserType.launchServer({...defaultBrowserOptions });
const remote = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const remote = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
const page = await remote.newPage(); const page = await remote.newPage();
await Promise.all([ await Promise.all([
browserServer.close(), browserServer.close(),
@ -161,8 +161,8 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
describe('Browser.disconnect', function() { describe('Browser.disconnect', function() {
it('should reject navigation when browser closes', async({server}) => { it('should reject navigation when browser closes', async({server}) => {
server.setRoute('/one-style.css', () => {}); server.setRoute('/one-style.css', () => {});
const browserServer = await playwright.launchServer({...defaultBrowserOptions }); const browserServer = await browserType.launchServer({...defaultBrowserOptions });
const remote = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const remote = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
const page = await remote.newPage(); const page = await remote.newPage();
const navigationPromise = page.goto(server.PREFIX + '/one-style.html', {timeout: 60000}).catch(e => e); const navigationPromise = page.goto(server.PREFIX + '/one-style.html', {timeout: 60000}).catch(e => e);
await server.waitForRequest('/one-style.css'); await server.waitForRequest('/one-style.css');
@ -173,8 +173,8 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
}); });
it('should reject waitForSelector when browser closes', async({server}) => { it('should reject waitForSelector when browser closes', async({server}) => {
server.setRoute('/empty.html', () => {}); server.setRoute('/empty.html', () => {});
const browserServer = await playwright.launchServer({...defaultBrowserOptions }); const browserServer = await browserType.launchServer({...defaultBrowserOptions });
const remote = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const remote = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
const page = await remote.newPage(); const page = await remote.newPage();
const watchdog = page.waitForSelector('div', { timeout: 60000 }).catch(e => e); const watchdog = page.waitForSelector('div', { timeout: 60000 }).catch(e => e);
@ -187,8 +187,8 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
await browserServer.close(); await browserServer.close();
}); });
it('should throw if used after disconnect', async({server}) => { it('should throw if used after disconnect', async({server}) => {
const browserServer = await playwright.launchServer({...defaultBrowserOptions }); const browserServer = await browserType.launchServer({...defaultBrowserOptions });
const remote = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const remote = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
const page = await remote.newPage(); const page = await remote.newPage();
await remote.close(); await remote.close();
const error = await page.evaluate('1 + 1').catch(e => e); const error = await page.evaluate('1 + 1').catch(e => e);
@ -196,8 +196,8 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
await browserServer.close(); await browserServer.close();
}); });
it('should emit close events on pages and contexts', async({server}) => { it('should emit close events on pages and contexts', async({server}) => {
const browserServer = await playwright.launchServer({...defaultBrowserOptions }); const browserServer = await browserType.launchServer({...defaultBrowserOptions });
const remote = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const remote = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
const context = await remote.newContext(); const context = await remote.newContext();
const page = await context.newPage(); const page = await context.newPage();
let pageClosed = false; let pageClosed = false;
@ -212,8 +212,8 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
describe('Browser.close', function() { describe('Browser.close', function() {
it('should terminate network waiters', async({server}) => { it('should terminate network waiters', async({server}) => {
const browserServer = await playwright.launchServer({...defaultBrowserOptions }); const browserServer = await browserType.launchServer({...defaultBrowserOptions });
const remote = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const remote = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
const newPage = await remote.newPage(); const newPage = await remote.newPage();
const results = await Promise.all([ const results = await Promise.all([
newPage.waitForRequest(server.EMPTY_PAGE).catch(e => e), newPage.waitForRequest(server.EMPTY_PAGE).catch(e => e),
@ -227,7 +227,7 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
} }
}); });
it('should fire close event for all contexts', async(state, test) => { it('should fire close event for all contexts', async(state, test) => {
const browser = await playwright.launch(defaultBrowserOptions); const browser = await browserType.launch(defaultBrowserOptions);
const context = await browser.newContext(); const context = await browser.newContext();
let closed = false; let closed = false;
context.on('close', () => closed = true); context.on('close', () => closed = true);
@ -236,10 +236,10 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
}); });
}); });
describe('Playwright.launch |webSocket| option', function() { describe('browserType.launch |webSocket| option', function() {
it('should support the webSocket option', async() => { it('should support the webSocket option', async() => {
const browserServer = await playwright.launchServer(defaultBrowserOptions); const browserServer = await browserType.launchServer(defaultBrowserOptions);
const browser = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const browser = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
const browserContext = await browser.newContext(); const browserContext = await browser.newContext();
expect((await browserContext.pages()).length).toBe(0); expect((await browserContext.pages()).length).toBe(0);
expect(browserServer.wsEndpoint()).not.toBe(null); expect(browserServer.wsEndpoint()).not.toBe(null);
@ -249,26 +249,26 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
await browserServer.close(); await browserServer.close();
}); });
it('should fire "disconnected" when closing with webSocket', async() => { it('should fire "disconnected" when closing with webSocket', async() => {
const browserServer = await playwright.launchServer(defaultBrowserOptions); const browserServer = await browserType.launchServer(defaultBrowserOptions);
const browser = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const browser = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
const disconnectedEventPromise = new Promise(resolve => browser.once('disconnected', resolve)); const disconnectedEventPromise = new Promise(resolve => browser.once('disconnected', resolve));
browserServer.kill(); browserServer.kill();
await disconnectedEventPromise; await disconnectedEventPromise;
}); });
}); });
describe('Playwright.connect', function() { describe('browserType.connect', function() {
it('should be able to reconnect to a browser', async({server}) => { it('should be able to reconnect to a browser', async({server}) => {
const browserServer = await playwright.launchServer(defaultBrowserOptions); const browserServer = await browserType.launchServer(defaultBrowserOptions);
{ {
const browser = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const browser = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
const browserContext = await browser.newContext(); const browserContext = await browser.newContext();
const page = await browserContext.newPage(); const page = await browserContext.newPage();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await browser.close(); await browser.close();
} }
{ {
const browser = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const browser = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
const browserContext = await browser.newContext(); const browserContext = await browser.newContext();
const page = await browserContext.newPage(); const page = await browserContext.newPage();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
@ -278,11 +278,11 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
}); });
}); });
describe('Playwright.launchPersistentContext', function() { describe('browserType.launchPersistentContext', function() {
it('userDataDir option', async({server}) => { it('userDataDir option', async({server}) => {
const userDataDir = await makeUserDataDir(); const userDataDir = await makeUserDataDir();
const options = Object.assign(defaultBrowserOptions); const options = Object.assign(defaultBrowserOptions);
const browserContext = await playwright.launchPersistentContext(userDataDir, options); const browserContext = await browserType.launchPersistentContext(userDataDir, options);
// Open a page to make sure its functional. // Open a page to make sure its functional.
await browserContext.newPage(); await browserContext.newPage();
expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0); expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
@ -293,20 +293,20 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
}); });
it.fail(FFOX)('userDataDir option should restore state', async({server}) => { it.fail(FFOX)('userDataDir option should restore state', async({server}) => {
const userDataDir = await makeUserDataDir(); const userDataDir = await makeUserDataDir();
const browserContext = await playwright.launchPersistentContext(userDataDir, defaultBrowserOptions); const browserContext = await browserType.launchPersistentContext(userDataDir, defaultBrowserOptions);
const page = await browserContext.newPage(); const page = await browserContext.newPage();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => localStorage.hey = 'hello'); await page.evaluate(() => localStorage.hey = 'hello');
await browserContext.close(); await browserContext.close();
const browserContext2 = await playwright.launchPersistentContext(userDataDir, defaultBrowserOptions); const browserContext2 = await browserType.launchPersistentContext(userDataDir, defaultBrowserOptions);
const page2 = await browserContext2.newPage(); const page2 = await browserContext2.newPage();
await page2.goto(server.EMPTY_PAGE); await page2.goto(server.EMPTY_PAGE);
expect(await page2.evaluate(() => localStorage.hey)).toBe('hello'); expect(await page2.evaluate(() => localStorage.hey)).toBe('hello');
await browserContext2.close(); await browserContext2.close();
const userDataDir2 = await makeUserDataDir(); const userDataDir2 = await makeUserDataDir();
const browserContext3 = await playwright.launchPersistentContext(userDataDir2, defaultBrowserOptions); const browserContext3 = await browserType.launchPersistentContext(userDataDir2, defaultBrowserOptions);
const page3 = await browserContext3.newPage(); const page3 = await browserContext3.newPage();
await page3.goto(server.EMPTY_PAGE); await page3.goto(server.EMPTY_PAGE);
expect(await page3.evaluate(() => localStorage.hey)).not.toBe('hello'); expect(await page3.evaluate(() => localStorage.hey)).not.toBe('hello');
@ -319,20 +319,20 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
// See https://github.com/microsoft/playwright/issues/717 // See https://github.com/microsoft/playwright/issues/717
it.fail(FFOX || (WIN && CHROMIUM))('userDataDir option should restore cookies', async({server}) => { it.fail(FFOX || (WIN && CHROMIUM))('userDataDir option should restore cookies', async({server}) => {
const userDataDir = await makeUserDataDir(); const userDataDir = await makeUserDataDir();
const browserContext = await playwright.launchPersistentContext(userDataDir, defaultBrowserOptions); const browserContext = await browserType.launchPersistentContext(userDataDir, defaultBrowserOptions);
const page = await browserContext.newPage(); const page = await browserContext.newPage();
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => document.cookie = 'doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT'); await page.evaluate(() => document.cookie = 'doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT');
await browserContext.close(); await browserContext.close();
const browserContext2 = await playwright.launchPersistentContext(userDataDir, defaultBrowserOptions); const browserContext2 = await browserType.launchPersistentContext(userDataDir, defaultBrowserOptions);
const page2 = await browserContext2.newPage(); const page2 = await browserContext2.newPage();
await page2.goto(server.EMPTY_PAGE); await page2.goto(server.EMPTY_PAGE);
expect(await page2.evaluate(() => document.cookie)).toBe('doSomethingOnlyOnce=true'); expect(await page2.evaluate(() => document.cookie)).toBe('doSomethingOnlyOnce=true');
await browserContext2.close(); await browserContext2.close();
const userDataDir2 = await makeUserDataDir(); const userDataDir2 = await makeUserDataDir();
const browserContext3 = await playwright.launchPersistentContext(userDataDir2, defaultBrowserOptions); const browserContext3 = await browserType.launchPersistentContext(userDataDir2, defaultBrowserOptions);
const page3 = await browserContext3.newPage(); const page3 = await browserContext3.newPage();
await page3.goto(server.EMPTY_PAGE); await page3.goto(server.EMPTY_PAGE);
expect(await page3.evaluate(() => localStorage.hey)).not.toBe('doSomethingOnlyOnce=true'); expect(await page3.evaluate(() => localStorage.hey)).not.toBe('doSomethingOnlyOnce=true');

View file

@ -20,20 +20,20 @@ const utils = require('./utils');
/** /**
* @type {TestSuite} * @type {TestSuite}
*/ */
module.exports.describe = function({testRunner, expect, defaultBrowserOptions, playwright, FFOX, CHROMIUM, WEBKIT}) { module.exports.describe = function({testRunner, expect, defaultBrowserOptions, browserType, FFOX, CHROMIUM, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner; const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner; const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner; const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('BrowserContext', function() { describe('BrowserContext', function() {
it('should work across sessions', async () => { it('should work across sessions', async () => {
const browserServer = await playwright.launchServer(defaultBrowserOptions); const browserServer = await browserType.launchServer(defaultBrowserOptions);
const browser1 = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const browser1 = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
expect(browser1.contexts().length).toBe(0); expect(browser1.contexts().length).toBe(0);
await browser1.newContext(); await browser1.newContext();
expect(browser1.contexts().length).toBe(1); expect(browser1.contexts().length).toBe(1);
const browser2 = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const browser2 = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
expect(browser2.contexts().length).toBe(0); expect(browser2.contexts().length).toBe(0);
await browser2.newContext(); await browser2.newContext();
expect(browser2.contexts().length).toBe(1); expect(browser2.contexts().length).toBe(1);
@ -45,11 +45,11 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
describe('Browser.Events.disconnected', function() { describe('Browser.Events.disconnected', function() {
it('should be emitted when: browser gets closed, disconnected or underlying websocket gets closed', async () => { it('should be emitted when: browser gets closed, disconnected or underlying websocket gets closed', async () => {
const browserServer = await playwright.launchServer(defaultBrowserOptions); const browserServer = await browserType.launchServer(defaultBrowserOptions);
const originalBrowser = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const originalBrowser = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
const wsEndpoint = browserServer.wsEndpoint(); const wsEndpoint = browserServer.wsEndpoint();
const remoteBrowser1 = await playwright.connect({ wsEndpoint }); const remoteBrowser1 = await browserType.connect({ wsEndpoint });
const remoteBrowser2 = await playwright.connect({ wsEndpoint }); const remoteBrowser2 = await browserType.connect({ wsEndpoint });
let disconnectedOriginal = 0; let disconnectedOriginal = 0;
let disconnectedRemote1 = 0; let disconnectedRemote1 = 0;
@ -79,11 +79,11 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
}); });
}); });
describe('Playwright.connect', function() { describe('browserType.connect', function() {
it('should be able to connect multiple times to the same browser', async({server}) => { it('should be able to connect multiple times to the same browser', async({server}) => {
const browserServer = await playwright.launchServer(defaultBrowserOptions); const browserServer = await browserType.launchServer(defaultBrowserOptions);
const browser1 = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const browser1 = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
const browser2 = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const browser2 = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
const page1 = await browser1.newPage(); const page1 = await browser1.newPage();
expect(await page1.evaluate(() => 7 * 8)).toBe(56); expect(await page1.evaluate(() => 7 * 8)).toBe(56);
browser1.close(); browser1.close();
@ -93,14 +93,14 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
await browserServer.close(); await browserServer.close();
}); });
it('should not be able to close remote browser', async() => { it('should not be able to close remote browser', async() => {
const browserServer = await playwright.launchServer(defaultBrowserOptions); const browserServer = await browserType.launchServer(defaultBrowserOptions);
{ {
const remote = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const remote = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
await remote.newContext(); await remote.newContext();
await remote.close(); await remote.close();
} }
{ {
const remote = await playwright.connect({ wsEndpoint: browserServer.wsEndpoint() }); const remote = await browserType.connect({ wsEndpoint: browserServer.wsEndpoint() });
await remote.newContext(); await remote.newContext();
await remote.close(); await remote.close();
} }

View file

@ -39,8 +39,8 @@ module.exports.describe = ({testRunner, product, playwrightPath}) => {
const LINUX = os.platform() === 'linux'; const LINUX = os.platform() === 'linux';
const WIN = os.platform() === 'win32'; const WIN = os.platform() === 'win32';
const playwrightModule = require(playwrightPath); const playwright = require(playwrightPath);
const playwright = playwrightModule[product.toLowerCase()]; const browserType = playwright[product.toLowerCase()];
const headless = !!valueFromEnv('HEADLESS', true); const headless = !!valueFromEnv('HEADLESS', true);
const slowMo = valueFromEnv('SLOW_MO', 0); const slowMo = valueFromEnv('SLOW_MO', 0);
@ -68,7 +68,7 @@ module.exports.describe = ({testRunner, product, playwrightPath}) => {
console.warn(`${YELLOW_COLOR}WARN: running ${product} tests with ${defaultBrowserOptions.executablePath}${RESET_COLOR}`); console.warn(`${YELLOW_COLOR}WARN: running ${product} tests with ${defaultBrowserOptions.executablePath}${RESET_COLOR}`);
} else { } else {
// Make sure the `npm install` was run after the chromium roll. // Make sure the `npm install` was run after the chromium roll.
if (!fs.existsSync(playwright.executablePath())) if (!fs.existsSync(browserType.executablePath()))
throw new Error(`Browser is not downloaded. Run 'npm install' and try to re-run tests`); throw new Error(`Browser is not downloaded. Run 'npm install' and try to re-run tests`);
} }
@ -90,8 +90,8 @@ module.exports.describe = ({testRunner, product, playwrightPath}) => {
MAC, MAC,
LINUX, LINUX,
WIN, WIN,
browserType,
playwright, playwright,
selectors: playwrightModule.selectors,
expect, expect,
defaultBrowserOptions, defaultBrowserOptions,
playwrightPath, playwrightPath,
@ -101,7 +101,7 @@ module.exports.describe = ({testRunner, product, playwrightPath}) => {
describe('', function() { describe('', function() {
beforeAll(async state => { beforeAll(async state => {
state.browser = await playwright.launch(defaultBrowserOptions); state.browser = await browserType.launch(defaultBrowserOptions);
state.browserServer = state.browser.__server__; state.browserServer = state.browser.__server__;
}); });

View file

@ -21,7 +21,7 @@ const zsSelectorEngineSource = require('../lib/generated/zsSelectorEngineSource'
/** /**
* @type {PageTestSuite} * @type {PageTestSuite}
*/ */
module.exports.describe = function({testRunner, expect, selectors, FFOX, CHROMIUM, WEBKIT}) { module.exports.describe = function({testRunner, expect, playwright, FFOX, CHROMIUM, WEBKIT}) {
const {describe, xdescribe, fdescribe} = testRunner; const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner; const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner; const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
@ -355,7 +355,7 @@ module.exports.describe = function({testRunner, expect, selectors, FFOX, CHROMIU
describe('zselector', () => { describe('zselector', () => {
beforeAll(async () => { beforeAll(async () => {
try { try {
await selectors.register('z', zsSelectorEngineSource.source); await playwright.selectors.register('z', zsSelectorEngineSource.source);
} catch (e) { } catch (e) {
if (!e.message.includes('has been already registered')) if (!e.message.includes('has been already registered'))
throw e; throw e;
@ -400,28 +400,28 @@ module.exports.describe = function({testRunner, expect, selectors, FFOX, CHROMIU
it('create', async ({page}) => { it('create', async ({page}) => {
await page.setContent(`<div>yo</div><div>ya</div><div>ya</div>`); await page.setContent(`<div>yo</div><div>ya</div><div>ya</div>`);
expect(await selectors._createSelector('z', await page.$('div'))).toBe('"yo"'); expect(await playwright.selectors._createSelector('z', await page.$('div'))).toBe('"yo"');
expect(await selectors._createSelector('z', await page.$('div:nth-child(2)'))).toBe('"ya"'); expect(await playwright.selectors._createSelector('z', await page.$('div:nth-child(2)'))).toBe('"ya"');
expect(await selectors._createSelector('z', await page.$('div:nth-child(3)'))).toBe('"ya"#1'); expect(await playwright.selectors._createSelector('z', await page.$('div:nth-child(3)'))).toBe('"ya"#1');
await page.setContent(`<img alt="foo bar">`); await page.setContent(`<img alt="foo bar">`);
expect(await selectors._createSelector('z', await page.$('img'))).toBe('img[alt="foo bar"]'); expect(await playwright.selectors._createSelector('z', await page.$('img'))).toBe('img[alt="foo bar"]');
await page.setContent(`<div>yo<span></span></div><span></span>`); await page.setContent(`<div>yo<span></span></div><span></span>`);
expect(await selectors._createSelector('z', await page.$('span'))).toBe('"yo"~SPAN'); expect(await playwright.selectors._createSelector('z', await page.$('span'))).toBe('"yo"~SPAN');
expect(await selectors._createSelector('z', await page.$('span:nth-child(2)'))).toBe('SPAN#1'); expect(await playwright.selectors._createSelector('z', await page.$('span:nth-child(2)'))).toBe('SPAN#1');
}); });
it('children of various display parents', async ({page}) => { it('children of various display parents', async ({page}) => {
await page.setContent(`<body><div style='position: fixed;'><span>yo</span></div></body>`); await page.setContent(`<body><div style='position: fixed;'><span>yo</span></div></body>`);
expect(await selectors._createSelector('z', await page.$('span'))).toBe('"yo"'); expect(await playwright.selectors._createSelector('z', await page.$('span'))).toBe('"yo"');
await page.setContent(`<div style='position: relative;'><span>yo</span></div>`); await page.setContent(`<div style='position: relative;'><span>yo</span></div>`);
expect(await selectors._createSelector('z', await page.$('span'))).toBe('"yo"'); expect(await playwright.selectors._createSelector('z', await page.$('span'))).toBe('"yo"');
// "display: none" makes all children text invisible - fallback to tag name. // "display: none" makes all children text invisible - fallback to tag name.
await page.setContent(`<div style='display: none;'><span>yo</span></div>`); await page.setContent(`<div style='display: none;'><span>yo</span></div>`);
expect(await selectors._createSelector('z', await page.$('span'))).toBe('SPAN'); expect(await playwright.selectors._createSelector('z', await page.$('span'))).toBe('SPAN');
}); });
it('boundary', async ({page}) => { it('boundary', async ({page}) => {
@ -472,7 +472,7 @@ module.exports.describe = function({testRunner, expect, selectors, FFOX, CHROMIU
<div id=target2>hello</div> <div id=target2>hello</div>
</div> </div>
</div>`); </div>`);
expect(await selectors._createSelector('z', await page.$('#target'))).toBe('"ya"~"hey"~"hello"'); expect(await playwright.selectors._createSelector('z', await page.$('#target'))).toBe('"ya"~"hey"~"hello"');
expect(await page.$eval(`z="ya"~"hey"~"hello"`, e => e.outerHTML)).toBe('<div id="target">hello</div>'); expect(await page.$eval(`z="ya"~"hey"~"hello"`, e => e.outerHTML)).toBe('<div id="target">hello</div>');
expect(await page.$eval(`z="ya"~"hey"~"unique"`, e => e.outerHTML).catch(e => e.message)).toBe('Error: failed to find element matching selector "z="ya"~"hey"~"unique""'); expect(await page.$eval(`z="ya"~"hey"~"unique"`, e => e.outerHTML).catch(e => e.message)).toBe('Error: failed to find element matching selector "z="ya"~"hey"~"unique""');
expect(await page.$$eval(`z="ya" ~ "hey" ~ "hello"`, es => es.map(e => e.outerHTML).join('\n'))).toBe('<div id="target">hello</div>\n<div id="target2">hello</div>'); expect(await page.$$eval(`z="ya" ~ "hey" ~ "hello"`, es => es.map(e => e.outerHTML).join('\n'))).toBe('<div id="target">hello</div>\n<div id="target2">hello</div>');
@ -515,18 +515,18 @@ module.exports.describe = function({testRunner, expect, selectors, FFOX, CHROMIU
it('create', async ({page}) => { it('create', async ({page}) => {
await page.setContent(`<div>yo</div><div>"ya</div><div>ye ye</div>`); await page.setContent(`<div>yo</div><div>"ya</div><div>ye ye</div>`);
expect(await selectors._createSelector('text', await page.$('div'))).toBe('yo'); expect(await playwright.selectors._createSelector('text', await page.$('div'))).toBe('yo');
expect(await selectors._createSelector('text', await page.$('div:nth-child(2)'))).toBe('"\\"ya"'); expect(await playwright.selectors._createSelector('text', await page.$('div:nth-child(2)'))).toBe('"\\"ya"');
expect(await selectors._createSelector('text', await page.$('div:nth-child(3)'))).toBe('"ye ye"'); expect(await playwright.selectors._createSelector('text', await page.$('div:nth-child(3)'))).toBe('"ye ye"');
await page.setContent(`<div>yo</div><div>yo<div>ya</div>hey</div>`); await page.setContent(`<div>yo</div><div>yo<div>ya</div>hey</div>`);
expect(await selectors._createSelector('text', await page.$('div:nth-child(2)'))).toBe('hey'); expect(await playwright.selectors._createSelector('text', await page.$('div:nth-child(2)'))).toBe('hey');
await page.setContent(`<div> yo <div></div>ya</div>`); await page.setContent(`<div> yo <div></div>ya</div>`);
expect(await selectors._createSelector('text', await page.$('div'))).toBe('yo'); expect(await playwright.selectors._createSelector('text', await page.$('div'))).toBe('yo');
await page.setContent(`<div> "yo <div></div>ya</div>`); await page.setContent(`<div> "yo <div></div>ya</div>`);
expect(await selectors._createSelector('text', await page.$('div'))).toBe('" \\"yo "'); expect(await playwright.selectors._createSelector('text', await page.$('div'))).toBe('" \\"yo "');
}); });
it('should be case sensitive iff quotes are specified', async({page}) => { it('should be case sensitive iff quotes are specified', async({page}) => {
await page.setContent(`<div>yo</div><div>ya</div><div>\nye </div>`); await page.setContent(`<div>yo</div><div>ya</div><div>\nye </div>`);
@ -548,15 +548,15 @@ module.exports.describe = function({testRunner, expect, selectors, FFOX, CHROMIU
return Array.from(root.querySelectorAll(selector)); return Array.from(root.querySelectorAll(selector));
} }
}); });
await selectors.register('tag', `(${createTagSelector.toString()})()`); await playwright.selectors.register('tag', `(${createTagSelector.toString()})()`);
await page.setContent('<div><span></span></div><div></div>'); await page.setContent('<div><span></span></div><div></div>');
expect(await selectors._createSelector('tag', await page.$('div'))).toBe('DIV'); expect(await playwright.selectors._createSelector('tag', await page.$('div'))).toBe('DIV');
expect(await page.$eval('tag=DIV', e => e.nodeName)).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=SPAN', e => e.nodeName)).toBe('SPAN');
expect(await page.$$eval('tag=DIV', es => es.length)).toBe(2); expect(await page.$$eval('tag=DIV', es => es.length)).toBe(2);
}); });
it('should work with path', async ({page}) => { it('should work with path', async ({page}) => {
await selectors.register('foo', { path: path.join(__dirname, 'assets/sectionselectorengine.js') }); await playwright.selectors.register('foo', { path: path.join(__dirname, 'assets/sectionselectorengine.js') });
await page.setContent('<section></section>'); await page.setContent('<section></section>');
expect(await page.$eval('foo=whatever', e => e.nodeName)).toBe('SECTION'); expect(await page.$eval('foo=whatever', e => e.nodeName)).toBe('SECTION');
}); });
@ -579,17 +579,17 @@ module.exports.describe = function({testRunner, expect, selectors, FFOX, CHROMIU
} }
}); });
error = await selectors.register('$', createDummySelector).catch(e => e); error = await playwright.selectors.register('$', createDummySelector).catch(e => e);
expect(error.message).toBe('Selector engine name may only contain [a-zA-Z0-9_] characters'); expect(error.message).toBe('Selector engine name may only contain [a-zA-Z0-9_] characters');
await selectors.register('dummy', createDummySelector); await playwright.selectors.register('dummy', createDummySelector);
expect(await page.$eval('dummy=ignored', e => e.id)).toBe('d1'); expect(await page.$eval('dummy=ignored', e => e.id)).toBe('d1');
expect(await page.$eval('css=span >> dummy=ignored', e => e.id)).toBe('d2'); expect(await page.$eval('css=span >> dummy=ignored', e => e.id)).toBe('d2');
error = await selectors.register('dummy', createDummySelector).catch(e => e); error = await playwright.selectors.register('dummy', createDummySelector).catch(e => e);
expect(error.message).toBe('"dummy" selector engine has been already registered'); expect(error.message).toBe('"dummy" selector engine has been already registered');
error = await selectors.register('css', createDummySelector).catch(e => e); error = await playwright.selectors.register('css', createDummySelector).catch(e => e);
expect(error.message).toBe('"css" is a predefined selector engine'); expect(error.message).toBe('"css" is a predefined selector engine');
}); });
}); });

View file

@ -17,15 +17,15 @@
/** /**
* @type {PageTestSuite} * @type {PageTestSuite}
*/ */
module.exports.describe = function({testRunner, expect, defaultBrowserOptions, playwright, product, CHROMIUM, FFOX}) { module.exports.describe = function({testRunner, expect, defaultBrowserOptions, browserType, product, CHROMIUM, FFOX}) {
const {describe, xdescribe, fdescribe} = testRunner; const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner; const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner; const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('Web SDK', function() { describe('Web SDK', function() {
beforeAll(async state => { beforeAll(async state => {
state.controlledBrowserApp = await playwright.launchServer(defaultBrowserOptions); state.controlledBrowserApp = await browserType.launchServer(defaultBrowserOptions);
state.hostBrowser = await playwright.launch(defaultBrowserOptions); state.hostBrowser = await browserType.launch(defaultBrowserOptions);
}); });
afterAll(async state => { afterAll(async state => {