Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

feat(electron): expose test and fixtures from @playwright/electron (#40320)

Dmitry Gozmanb7700b8f74c2
diff --git a/docs/src/electron-api/class-electron.md b/docs/src/electron-api/class-electron.md
index 4442c87145..bf74771e20 100644
--- a/docs/src/electron-api/class-electron.md
+++ b/docs/src/electron-api/class-electron.md
@@ -2,15 +2,32 @@
* since: v1.9
* langs: js
-Playwright supports Electron automation, shipped as a separate package:
+Playwright supports Electron automation, shipped as a separate package.
```sh
npm i -D @playwright/electron
```
-An example of the Electron automation script would be:
+After installation, you can write a test or an automation script.
-```js
+```js tab=js-test
+import { test, expect } from '@playwright/electron';
+
+test.use({ appOptions: { args: ['main.js'] } });
+
+test('basic test', async ({ app, page }) => {
+ // Evaluate in the main Electron process.
+ const appPath = await app.evaluate(async ({ app }) => app.getAppPath());
+ console.log(appPath);
+
+ // Interact with the first window via the `page` fixture.
+ await expect(page).toHaveTitle(/My App/);
+ await page.click('text=Click me');
+ await expect(page.getByRole('heading')).toHaveText('Hello');
+});
+```
+
+```js tab=js-library
import { electron } from '@playwright/electron';
(async () => {
diff --git a/docs/src/electron-api/class-electronfixtures.md b/docs/src/electron-api/class-electronfixtures.md
new file mode 100644
index 0000000000..8e77102543
--- /dev/null
+++ b/docs/src/electron-api/class-electronfixtures.md
@@ -0,0 +1,180 @@
+# class: ElectronFixtures
+* since: v1.60
+* langs: js
+
+The `@playwright/electron` package exposes a `test` object with a set of fixtures tailored for Electron automation. Fixtures are used to establish the environment for each test, giving the test everything it needs and nothing else.
+
+```js
+import { test, expect } from '@playwright/electron';
+
+test('basic test', async ({ page }) => {
+ // ...
+});
+```
+
+Given the test above, Playwright Test will launch the Electron application, wait for its first window, and expose it as the `page` fixture. Underneath, the [`property: ElectronFixtures.app`] fixture launches the application via [`method: Electron.launch`] using [`property: ElectronFixtures.appOptions`]. The application is closed after the test finishes.
+
+## property: ElectronFixtures.app
+* since: v1.60
+- type: <[ElectronApplication]>
+
+[ElectronApplication] instance, created for each test by launching Electron with [`property: ElectronFixtures.appOptions`]. The application is closed after the test finishes.
+
+**Usage**
+
+```js
+import { test, expect } from '@playwright/electron';
+
+test.use({ appOptions: { args: ['main.js'] } });
+
+test('scripts the main process', async ({ app }) => {
+ const appPath = await app.evaluate(({ app }) => app.getAppPath());
+ expect(appPath).toBeTruthy();
+});
+```
+
+## property: ElectronFixtures.appOptions
+* since: v1.60
+- type: <[Object]>
+
+Options passed to [`method: Electron.launch`] when creating the [`property: ElectronFixtures.app`]. Override via `use` in the config file or `test.use()` to point at your Electron entry point and configure the launch.
+
+**Usage**
+
+```js title="playwright.config.ts"
+import { defineConfig } from '@playwright/electron';
+
+export default defineConfig({
+ use: {
+ appOptions: {
+ args: ['main.js'],
+ env: { NODE_ENV: 'test' },
+ },
+ },
+});
+```
+
+## property: ElectronFixtures.context
+* since: v1.60
+- type: <[BrowserContext]>
+
+[BrowserContext] of the launched Electron app. All windows of the Electron application belong to this context.
+
+**Usage**
+
+```js
+import { test, expect } from '@playwright/electron';
+
+test('routes network', async ({ context, page }) => {
+ await context.route('**/api/**', route => route.fulfill({ status: 200, body: '{}' }));
+ await page.goto('https://example.com/api/data');
+});
+```
+
+## property: ElectronFixtures.page
+* since: v1.60
+- type: <[Page]>
+
+First window of the launched Electron app, as returned by [`method: ElectronApplication.firstWindow`]. This is the most common fixture used in an Electron test.
+
+**Usage**
+
+```js
+import { test, expect } from '@playwright/electron';
+
+test('interacts with the first window', async ({ page }) => {
+ await page.setContent('<h1>Hello</h1>');
+ await expect(page.locator('h1')).toHaveText('Hello');
+});
+```
+
+## property: ElectronFixtures.playwright
+* since: v1.60
+- type: <[Object]>
+
+The Playwright module re-exported as a worker-scoped fixture. Use it when you need programmatic access to the Playwright API without importing it directly.
+
+**Usage**
+
+```js
+import { test, expect } from '@playwright/electron';
+
+test('uses playwright module', async ({ playwright }) => {
+ const request = await playwright.request.newContext();
+ // ...
+});
+```
+
+## property: ElectronFixtures.screenshot
+* since: v1.60
+- type: <[Object]|[ScreenshotMode]<"off"|"on"|"only-on-failure"|"on-first-failure">>
+ - `mode` <[ScreenshotMode]<"off"|"on"|"only-on-failure"|"on-first-failure">> Automatic screenshot mode.
+ - `fullPage` ?<[boolean]> When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Defaults to `false`.
+ - `omitBackground` ?<[boolean]> Hides default white background and allows capturing screenshots with transparency. Not applicable to `jpeg` images. Defaults to `false`.
+
+Whether to automatically capture a screenshot after each test. Defaults to `'off'`.
+* `'off'`: Do not capture screenshots.
+* `'on'`: Capture screenshot after each test.
+* `'only-on-failure'`: Capture screenshot after each test failure.
+* `'on-first-failure'`: Capture screenshot after each test's first failure.
+
+**Usage**
+
+```js title="playwright.config.ts"
+import { defineConfig } from '@playwright/electron';
+
+export default defineConfig({
+ use: {
+ screenshot: 'only-on-failure',
+ },
+});
+```
+
+## property: ElectronFixtures.testIdAttribute
+* since: v1.60
+
+Custom attribute to be used in [`method: Page.getByTestId`]. `data-testid` is used by default.
+
+**Usage**
+
+```js title="playwright.config.ts"
+import { defineConfig } from '@playwright/electron';
+
+export default defineConfig({
+ use: {
+ testIdAttribute: 'pw-test-id',
+ },
+});
+```
+
+## property: ElectronFixtures.trace
+* since: v1.60
+- type: <[Object]|[TraceMode]<"off"|"on"|"retain-on-failure"|"on-first-retry"|"retain-on-first-failure"|"retain-on-failure-and-retries">>
+ - `mode` <[TraceMode]<"off"|"on"|"retain-on-failure"|"on-first-retry"|"on-all-retries"|"retain-on-first-failure"|"retain-on-failure-and-retries">> Trace recording mode.
+ - `attachments` ?<[boolean]> Whether to include test attachments. Defaults to true. Optional.
+ - `screenshots` ?<[boolean]> Whether to capture screenshots during tracing. Screenshots are used to build a timeline preview. Defaults to true. Optional.
+ - `snapshots` ?<[boolean]> Whether to capture DOM snapshot on every action. Defaults to true. Optional.
+ - `sources` ?<[boolean]> Whether to include source files for trace actions. Defaults to true. Optional.
+
+Whether to record trace for each test. Defaults to `'off'`.
+* `'off'`: Do not record trace.
+* `'on'`: Record trace for each test.
+* `'on-first-retry'`: Record trace only when retrying a test for the first time.
+* `'on-all-retries'`: Record trace only when retrying a test.
+* `'retain-on-failure'`: Record trace for each test. When test run passes, remove the recorded trace.
+* `'retain-on-first-failure'`: Record trace for the first run of each test, but not for retries. When test run passes, remove the recorded trace.
+* `'retain-on-failure-and-retries'`: Record trace for each test run. Retains all traces when an attempt fails.
+
+For more control, pass an object that specifies `mode` and trace features to enable.
+
+**Usage**
+
+```js title="playwright.config.ts"
+import { defineConfig } from '@playwright/electron';
+
+export default defineConfig({
+ use: {
+ trace: 'on-first-retry'
+ },
+});
+```
diff --git a/package-lock.json b/package-lock.json
index 2ca6b75f7b..69382f2cc8 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -9807,7 +9807,7 @@
"version": "1.60.0-next",
"license": "Apache-2.0",
"dependencies": {
- "playwright-core": "1.60.0-next"
+ "playwright": "1.60.0-next"
},
"engines": {
"node": ">=18"
diff --git a/packages/playwright-electron/index.d.ts b/packages/playwright-electron/index.d.ts
index 24667aeeea..71d3a172bd 100644
--- a/packages/playwright-electron/index.d.ts
+++ b/packages/playwright-electron/index.d.ts
@@ -14,4 +14,51 @@
* limitations under the License.
*/
+import type {
+ PlaywrightTestArgs as BasePlaywrightTestArgs,
+ PlaywrightTestOptions as BasePlaywrightTestOptions,
+ PlaywrightWorkerArgs as BasePlaywrightWorkerArgs,
+ PlaywrightWorkerOptions as BasePlaywrightWorkerOptions,
+ PlaywrightTestConfig as BasePlaywrightTestConfig,
+ TestType as BaseTestType,
+ BrowserContext,
+ Page,
+ Project,
+ Config,
+} from 'playwright/test';
+import type { Electron, ElectronApplication } from './types';
+
export * from './types';
+export { expect, devices, mergeExpects, mergeTests } from 'playwright/test';
+
+export type ElectronAppOptions = Parameters<Electron['launch']>[0];
+export type PlaywrightTestOptions = Pick<BasePlaywrightTestOptions, 'testIdAttribute'> & {
+ appOptions: ElectronAppOptions;
+};
+export type PlaywrightTestArgs = Pick<BasePlaywrightTestArgs, 'request'> & {
+ app: ElectronApplication;
+ context: BrowserContext;
+ page: Page;
+};
+export type PlaywrightWorkerArgs = Pick<BasePlaywrightWorkerArgs, 'playwright'>;
+export type PlaywrightWorkerOptions = Pick<BasePlaywrightWorkerOptions, 'screenshot' | 'trace'>;
+
+export type TestType<T, W> = BaseTestType<
+ PlaywrightTestOptions & PlaywrightTestArgs & T,
+ PlaywrightWorkerArgs & PlaywrightWorkerOptions & W
+>;
+export const test: TestType<{}, {}>;
+
+type ExcludeProps<A, B> = {
+ [K in Exclude<keyof A, keyof B>]: A[K];
+};
+type CustomProperties<T> = ExcludeProps<T, PlaywrightTestOptions & PlaywrightWorkerOptions & PlaywrightTestArgs & PlaywrightWorkerArgs>;
+export type PlaywrightTestProject<TestArgs = {}, WorkerArgs = {}> = Project<PlaywrightTestOptions & CustomProperties<TestArgs>, PlaywrightWorkerOptions & CustomProperties<WorkerArgs>>;
+export type PlaywrightTestConfig<TestArgs = {}, WorkerArgs = {}> = Config<PlaywrightTestOptions & CustomProperties<TestArgs>, PlaywrightWorkerOptions & CustomProperties<WorkerArgs>>;
+
+export function defineConfig(config: PlaywrightTestConfig): PlaywrightTestConfig;
+export function defineConfig<T>(config: PlaywrightTestConfig<T>): PlaywrightTestConfig<T>;
+export function defineConfig<T, W>(config: PlaywrightTestConfig<T, W>): PlaywrightTestConfig<T, W>;
+export function defineConfig(config: PlaywrightTestConfig, ...configs: PlaywrightTestConfig[]): PlaywrightTestConfig;
+export function defineConfig<T>(config: PlaywrightTestConfig<T>, ...configs: PlaywrightTestConfig<T>[]): PlaywrightTestConfig<T>;
+export function defineConfig<T, W>(config: PlaywrightTestConfig<T, W>, ...configs: PlaywrightTestConfig<T, W>[]): PlaywrightTestConfig<T, W>;
diff --git a/packages/playwright-electron/index.js b/packages/playwright-electron/index.js
index f1f1d57e07..227eee0fde 100644
--- a/packages/playwright-electron/index.js
+++ b/packages/playwright-electron/index.js
@@ -14,6 +14,4 @@
* limitations under the License.
*/
-const { selectors } = require('playwright-core');
-const { electron } = require('./lib/electron');
-module.exports = { electron, selectors };
+module.exports = require('./lib/index');
diff --git a/packages/playwright-electron/package.json b/packages/playwright-electron/package.json
index 4f743c1cb7..c746d6eca3 100644
--- a/packages/playwright-electron/package.json
+++ b/packages/playwright-electron/package.json
@@ -21,6 +21,6 @@
}
},
"dependencies": {
- "playwright-core": "1.60.0-next"
+ "playwright": "1.60.0-next"
}
}
diff --git a/packages/playwright-electron/src/DEPS.list b/packages/playwright-electron/src/DEPS.list
index 6d6d0a1a68..2eff62db60 100644
--- a/packages/playwright-electron/src/DEPS.list
+++ b/packages/playwright-electron/src/DEPS.list
@@ -1,5 +1,5 @@
[*]
@isomorphic/**
@utils/**
-playwright-core
+node_modules/playwright
node_modules/debug
diff --git a/packages/playwright-electron/src/electron.ts b/packages/playwright-electron/src/electron.ts
index cd3143f63d..c31c7aa873 100644
--- a/packages/playwright-electron/src/electron.ts
+++ b/packages/playwright-electron/src/electron.ts
@@ -17,7 +17,7 @@
import os from 'os';
import readline from 'readline';
import { EventEmitter } from 'events';
-import { chromium } from 'playwright-core';
+import { chromium } from 'playwright/test';
import debug from 'debug';
import { launchProcess } from '@utils/processLauncher';
@@ -27,7 +27,7 @@ import { ManualPromise } from '@isomorphic/manualPromise';
import { monotonicTime } from '@isomorphic/time';
import type { BrowserWindow } from 'electron';
-import type { Browser, BrowserContext, JSHandle, Page, Worker } from 'playwright-core';
+import type { Browser, BrowserContext, JSHandle, Page, Worker } from 'playwright/test';
import type childProcess from 'child_process';
import type * as api from '../types';
diff --git a/packages/playwright-electron/src/index.ts b/packages/playwright-electron/src/index.ts
new file mode 100644
index 0000000000..a25c567dc4
--- /dev/null
+++ b/packages/playwright-electron/src/index.ts
@@ -0,0 +1,50 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// @ts-expect-error
+import { _utilityTest } from 'playwright/test';
+import { selectors } from 'playwright/test';
+
+import { electron } from './electron';
+export { expect, devices, defineConfig, mergeExpects, mergeTests } from 'playwright/test';
+export { electron, selectors };
+
+import type { BrowserContext, TestType } from '../index.d.ts';
+
+const baseTest = _utilityTest as TestType<{
+ _decorateContext: (context: BrowserContext) => Promise<void>;
+}, {}>;
+
+export const test = baseTest.extend({
+ // @ts-expect-error
+ appOptions: [{}, { option: true }],
+
+ app: async ({ appOptions, testIdAttribute, _decorateContext }, use) => {
+ selectors.setTestIdAttribute(testIdAttribute);
+ const app = await electron.launch(appOptions);
+ await _decorateContext(app.context());
+ await use(app);
+ await app.close();
+ },
+
+ page: async ({ app }, use) => {
+ await use(await app.firstWindow());
+ },
+
+ context: async ({ app }, use) => {
+ await use(app.context());
+ },
+});
diff --git a/packages/playwright-electron/types.d.ts b/packages/playwright-electron/types.d.ts
index 4cfc8f77bf..99608c6bf9 100644
--- a/packages/playwright-electron/types.d.ts
+++ b/packages/playwright-electron/types.d.ts
@@ -342,39 +342,9 @@ export {};
/**
- * Playwright supports Electron automation, shipped as a separate package:
+ * Playwright supports Electron automation, shipped as a separate package.
*
- * An example of the Electron automation script would be:
- *
- * ```js
- * import { electron } from '@playwright/electron';
- *
- * (async () => {
- * // Launch Electron app.
- * const electronApp = await electron.launch({ args: ['main.js'] });
- *
- * // Evaluation expression in the Electron context.
- * const appPath = await electronApp.evaluate(async ({ app }) => {
- * // This runs in the main Electron process, parameter here is always
- * // the result of the require('electron') in the main app script.
- * return app.getAppPath();
- * });
- * console.log(appPath);
- *
- * // Get the first window that the app opens, wait if necessary.
- * const window = await electronApp.firstWindow();
- * // Print the title.
- * console.log(await window.title());
- * // Capture a screenshot.
- * await window.screenshot({ path: 'intro.png' });
- * // Direct Electron console to Node terminal.
- * window.on('console', console.log);
- * // Click button.
- * await window.click('text=Click me');
- * // Exit app.
- * await electronApp.close();
- * })();
- * ```
+ * After installation, you can write a test or an automation script.
*
* **Supported Electron versions are:**
* - v12.2.0+
diff --git a/packages/playwright/src/index.ts b/packages/playwright/src/index.ts
index 331a2c8ebe..2801495d49 100644
--- a/packages/playwright/src/index.ts
+++ b/packages/playwright/src/index.ts
@@ -64,6 +64,7 @@ type TestFixtures = PlaywrightTestArgs & PlaywrightTestOptions & {
_combinedContextOptions: BrowserContextOptions,
_setupContextOptions: void;
_setupArtifacts: void;
+ _decorateContext: (context: BrowserContext) => Promise<void>;
_contextFactory: (options?: BrowserContextOptions) => Promise<{ context: BrowserContext, close: () => Promise<void> }>;
};
@@ -75,21 +76,163 @@ type WorkerFixtures = PlaywrightWorkerArgs & PlaywrightWorkerOptions & {
_reuseContext: boolean,
};
-const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
- defaultBrowserType: ['chromium', { scope: 'worker', option: true, box: true }],
- browserName: [({ defaultBrowserType }, use) => use(defaultBrowserType), { scope: 'worker', option: true, box: true }],
+// Note: utility fixtures and _utilityTest are reused in electron package. Be mindful when changing them.
+type UtilityTestFixtures = Pick<TestFixtures, 'testIdAttribute' | 'request' | '_combinedContextOptions' | '_setupArtifacts' | '_decorateContext'>;
+type UtilityWorkerFixtures = Pick<WorkerFixtures, 'playwright' | 'screenshot' | 'trace'>;
+const utilityFixtures: Fixtures<UtilityTestFixtures, UtilityWorkerFixtures> = {
playwright: [async ({}, use) => {
await use(require('playwright-core'));
}, { scope: 'worker', box: true }],
+ screenshot: ['off', { scope: 'worker', option: true, box: true }],
+ trace: ['off', { scope: 'worker', option: true, box: true }],
+ testIdAttribute: ['data-testid', { option: true, box: true }],
+ _combinedContextOptions: [{}, { box: true }],
+ _decorateContext: [async ({}, use, testInfoPublic) => {
+ const testInfo = testInfoPublic as TestInfoImpl;
+ await use(async (context: BrowserContext) => {
+ testInfo._onCustomMessageCallback = createCustomMessageHandler(testInfo, context);
+ await runDaemonForContext(testInfo, context);
+ });
+ }, { box: true }],
+ _setupArtifacts: [async ({ playwright, screenshot, _combinedContextOptions }, use, testInfo) => {
+ // This fixture has a separate zero-timeout slot to ensure that artifact collection
+ // happens even after some fixtures or hooks time out.
+ // Now that default test timeout is known, we can replace zero with an actual value.
+ testInfo.setTimeout(testInfo.project.timeout);
+
+ const artifactsRecorder = new ArtifactsRecorder(playwright, tracing().artifactsDir(), screenshot);
+ await artifactsRecorder.willStartTest(testInfo as TestInfoImpl);
+
+ const tracingGroupSteps: TestStepInternal[] = [];
+ const pausedContexts = new Set<BrowserContextImpl>();
+ const csiListener: ClientInstrumentationListener = {
+ onApiCallBegin: (data, channel) => {
+ const testInfo = globals.currentTestInfo();
+ // Some special calls do not get into steps.
+ if (!testInfo || data.apiName.includes('setTestIdAttribute') || data.apiName === 'tracing.groupEnd')
+ return;
+ const zone = currentZone().data<TestStepInternal>('stepZone');
+ const isExpectCall = data.apiName === 'locator._expect' || data.apiName === 'frame._expect' || data.apiName === 'page._expectScreenshot';
+ if (zone && zone.category === 'expect' && isExpectCall) {
+ // Display the internal locator._expect call under the name of the enclosing expect call,
+ // and connect it to the existing expect step.
+ if (zone.apiName)
+ data.apiName = zone.apiName;
+ if (zone.shortTitle || zone.title)
+ data.title = zone.shortTitle ?? zone.title;
+ data.stepId = zone.stepId;
+ return;
+ }
+
+ // In the general case, create a step for each api call and connect them through the stepId.
+ const step = testInfo._addStep({
+ location: data.frames[0],
+ category: 'pw:api',
+ title: renderTitle(channel.type, channel.method, channel.params, data.title),
+ apiName: data.apiName,
+ params: channel.params,
+ group: getActionGroup({ type: channel.type, method: channel.method }),
+ }, tracingGroupSteps[tracingGroupSteps.length - 1]);
+ data.userData = step;
+ data.stepId = step.stepId;
+ if (data.apiName === 'tracing.group')
+ tracingGroupSteps.push(step);
+ },
+ onApiCallEnd: data => {
+
+ // "tracing.group" step will end later, when "tracing.groupEnd" finishes.
+ if (data.apiName === 'tracing.group')
+ return;
+ if (data.apiName === 'tracing.groupEnd') {
+ const step = tracingGroupSteps.pop();
+ step?.complete({ error: data.error });
+ return;
+ }
+ const step = data.userData;
+ step?.complete({ error: data.error });
+ },
+ onWillPause: ({ keepTestTimeout }) => {
+ if (!keepTestTimeout)
+ globals.currentTestInfo()?._setIgnoreTimeouts(true);
+ },
+ runBeforeCreateBrowserContext: async (options: BrowserContextOptions) => {
+ for (const [key, value] of Object.entries(_combinedContextOptions)) {
+ if (!(key in options))
+ options[key as keyof BrowserContextOptions] = value;
+ }
+ },
+ runBeforeCreateRequestContext: async (options: APIRequestContextOptions) => {
+ for (const [key, value] of Object.entries(_combinedContextOptions)) {
+ if (!(key in options))
+ options[key as keyof APIRequestContextOptions] = value;
+ }
+ },
+ runAfterCreateBrowserContext: async (context: BrowserContextImpl) => {
+ context.debugger.on('pausedstatechanged', () => {
+ const paused = !!context.debugger.pausedDetails();
+ if (pausedContexts.has(context) && !paused) {
+ pausedContexts.delete(context);
+ (testInfo as TestInfoImpl)._setIgnoreTimeouts(false);
+ } else if (!pausedContexts.has(context) && paused) {
+ pausedContexts.add(context);
+ (testInfo as TestInfoImpl)._setIgnoreTimeouts(true);
+ }
+ });
+
+ await artifactsRecorder.didCreateBrowserContext(context);
+ const testInfo = globals.currentTestInfo();
+ if (testInfo)
+ attachConnectedHeaderIfNeeded(testInfo, context.browser());
+ },
+ runAfterCreateRequestContext: async (context: APIRequestContextImpl) => {
+ await artifactsRecorder.didCreateRequestContext(context);
+ },
+ runBeforeCloseBrowserContext: async (context: BrowserContextImpl) => {
+ await artifactsRecorder.willCloseBrowserContext(context);
+ },
+ runBeforeCloseRequestContext: async (context: APIRequestContextImpl) => {
+ await artifactsRecorder.willCloseRequestContext(context);
+ },
+ };
+
+ const clientInstrumentation = playwright._instrumentation;
+ clientInstrumentation.addListener(csiListener);
+
+ await use();
+
+ clientInstrumentation.removeListener(csiListener);
+ await artifactsRecorder.didFinishTest();
+ }, { auto: 'all-hooks-included', title: 'trace recording', box: true, timeout: 0 } as any],
+
+ request: async ({ playwright }, use) => {
+ const request = await playwright.request.newContext();
+ await use(request);
+ const hook = (test.info() as TestInfoImpl)._currentHookType();
+ if (hook === 'beforeAll') {
+ await request.dispose({ reason: [
+ `Fixture { request } from beforeAll cannot be reused in a test.`,
+ ` - Recommended fix: use a separate { request } in the test.`,
+ ` - Alternatively, manually create APIRequestContext in beforeAll and dispose it in afterAll.`,
+ `See https://playwright.dev/docs/api-testing#sending-api-requests-from-ui-tests for more details.`,
+ ].join('\n') });
+ } else {
+ await request.dispose();
+ }
+ },
+};
+
+export const _utilityTest: TestType<UtilityTestFixtures, UtilityWorkerFixtures> = _baseTest.extend<UtilityTestFixtures, UtilityWorkerFixtures>(utilityFixtures);
+
+const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures, UtilityTestFixtures, UtilityWorkerFixtures> = ({
+ defaultBrowserType: ['chromium', { scope: 'worker', option: true, box: true }],
+ browserName: [({ defaultBrowserType }, use) => use(defaultBrowserType), { scope: 'worker', option: true, box: true }],
headless: [({ launchOptions }, use) => use(launchOptions.headless ?? true), { scope: 'worker', option: true, box: true }],
channel: [({ launchOptions }, use) => use(launchOptions.channel), { scope: 'worker', option: true, box: true }],
launchOptions: [{}, { scope: 'worker', option: true, box: true }],
connectOptions: [async ({ _optionConnectOptions }, use) => {
await use(connectOptionsFromEnv() || _optionConnectOptions);
}, { scope: 'worker', option: true, box: true }],
- screenshot: ['off', { scope: 'worker', option: true, box: true }],
video: ['off', { scope: 'worker', option: true, box: true }],
- trace: ['off', { scope: 'worker', option: true, box: true }],
_browserOptions: [async ({ playwright, headless, channel, launchOptions }, use) => {
const options: LaunchOptions = {
@@ -155,7 +298,6 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
userAgent: [({ contextOptions }, use) => use(contextOptions.userAgent), { option: true, box: true }],
viewport: [({ contextOptions }, use) => use(contextOptions.viewport === undefined ? { width: 1280, height: 720 } : contextOptions.viewport), { option: true, box: true }],
actionTimeout: [0, { option: true, box: true }],
- testIdAttribute: ['data-testid', { option: true, box: true }],
navigationTimeout: [0, { option: true, box: true }],
baseURL: [async ({ }, use) => {
await use(process.env.PLAYWRIGHT_TEST_BASE_URL);
@@ -237,7 +379,7 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
...contextOptions,
...options,
});
- }, { box: true }],
+ }, { scope: 'test', box: true }],
_setupContextOptions: [async ({ playwright, actionTimeout, navigationTimeout, testIdAttribute }, use, _testInfo) => {
const testInfo = _testInfo as TestInfoImpl;
@@ -255,116 +397,6 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
playwright._defaultContextNavigationTimeout = undefined;
}, { auto: 'all-hooks-included', title: 'context configuration', box: true } as any],
- _setupArtifacts: [async ({ playwright, screenshot, _combinedContextOptions }, use, testInfo) => {
- // This fixture has a separate zero-timeout slot to ensure that artifact collection
- // happens even after some fixtures or hooks time out.
- // Now that default test timeout is known, we can replace zero with an actual value.
- testInfo.setTimeout(testInfo.project.timeout);
-
- const artifactsRecorder = new ArtifactsRecorder(playwright, tracing().artifactsDir(), screenshot);
- await artifactsRecorder.willStartTest(testInfo as TestInfoImpl);
-
- const tracingGroupSteps: TestStepInternal[] = [];
- const pausedContexts = new Set<BrowserContextImpl>();
- const csiListener: ClientInstrumentationListener = {
- onApiCallBegin: (data, channel) => {
- const testInfo = globals.currentTestInfo();
- // Some special calls do not get into steps.
- if (!testInfo || data.apiName.includes('setTestIdAttribute') || data.apiName === 'tracing.groupEnd')
- return;
- const zone = currentZone().data<TestStepInternal>('stepZone');
- const isExpectCall = data.apiName === 'locator._expect' || data.apiName === 'frame._expect' || data.apiName === 'page._expectScreenshot';
- if (zone && zone.category === 'expect' && isExpectCall) {
- // Display the internal locator._expect call under the name of the enclosing expect call,
- // and connect it to the existing expect step.
- if (zone.apiName)
- data.apiName = zone.apiName;
- if (zone.shortTitle || zone.title)
- data.title = zone.shortTitle ?? zone.title;
- data.stepId = zone.stepId;
- return;
- }
-
- // In the general case, create a step for each api call and connect them through the stepId.
- const step = testInfo._addStep({
- location: data.frames[0],
- category: 'pw:api',
- title: renderTitle(channel.type, channel.method, channel.params, data.title),
- apiName: data.apiName,
- params: channel.params,
- group: getActionGroup({ type: channel.type, method: channel.method }),
- }, tracingGroupSteps[tracingGroupSteps.length - 1]);
- data.userData = step;
- data.stepId = step.stepId;
- if (data.apiName === 'tracing.group')
- tracingGroupSteps.push(step);
- },
- onApiCallEnd: data => {
-
- // "tracing.group" step will end later, when "tracing.groupEnd" finishes.
- if (data.apiName === 'tracing.group')
- return;
- if (data.apiName === 'tracing.groupEnd') {
- const step = tracingGroupSteps.pop();
- step?.complete({ error: data.error });
- return;
- }
- const step = data.userData;
- step?.complete({ error: data.error });
- },
- onWillPause: ({ keepTestTimeout }) => {
- if (!keepTestTimeout)
- globals.currentTestInfo()?._setIgnoreTimeouts(true);
- },
- runBeforeCreateBrowserContext: async (options: BrowserContextOptions) => {
- for (const [key, value] of Object.entries(_combinedContextOptions)) {
- if (!(key in options))
- options[key as keyof BrowserContextOptions] = value;
- }
- },
- runBeforeCreateRequestContext: async (options: APIRequestContextOptions) => {
- for (const [key, value] of Object.entries(_combinedContextOptions)) {
- if (!(key in options))
- options[key as keyof APIRequestContextOptions] = value;
- }
- },
- runAfterCreateBrowserContext: async (context: BrowserContextImpl) => {
- context.debugger.on('pausedstatechanged', () => {
- const paused = !!context.debugger.pausedDetails();
- if (pausedContexts.has(context) && !paused) {
- pausedContexts.delete(context);
- (testInfo as TestInfoImpl)._setIgnoreTimeouts(false);
- } else if (!pausedContexts.has(context) && paused) {
- pausedContexts.add(context);
- (testInfo as TestInfoImpl)._setIgnoreTimeouts(true);
- }
- });
-
- await artifactsRecorder.didCreateBrowserContext(context);
- const testInfo = globals.currentTestInfo();
- if (testInfo)
- attachConnectedHeaderIfNeeded(testInfo, context.browser());
- },
- runAfterCreateRequestContext: async (context: APIRequestContextImpl) => {
- await artifactsRecorder.didCreateRequestContext(context);
- },
- runBeforeCloseBrowserContext: async (context: BrowserContextImpl) => {
- await artifactsRecorder.willCloseBrowserContext(context);
- },
- runBeforeCloseRequestContext: async (context: APIRequestContextImpl) => {
- await artifactsRecorder.willCloseRequestContext(context);
- },
- };
-
- const clientInstrumentation = playwright._instrumentation;
- clientInstrumentation.addListener(csiListener);
-
- await use();
-
- clientInstrumentation.removeListener(csiListener);
- await artifactsRecorder.didFinishTest();
- }, { auto: 'all-hooks-included', title: 'trace recording', box: true, timeout: 0 } as any],
-
_contextFactory: [async ({ browser, video, _reuseContext, _combinedContextOptions /** mitigate dep-via-auto lack of traceability */ }, use, testInfo) => {
const testInfoImpl = testInfo as TestInfoImpl;
const videoMode = normalizeVideoMode(video);
@@ -448,15 +480,14 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
await use(reuse);
}, { scope: 'worker', title: 'context', box: true }],
- context: async ({ browser, video, _reuseContext, _contextFactory }, use, testInfoPublic) => {
+ context: async ({ browser, video, _reuseContext, _contextFactory, _decorateContext }, use, testInfoPublic) => {
const browserImpl = browser as BrowserImpl;
const testInfo = testInfoPublic as TestInfoImpl;
const show = typeof video === 'string' ? undefined : video.show;
attachConnectedHeaderIfNeeded(testInfo, browserImpl);
if (!_reuseContext) {
const { context, close } = await _contextFactory();
- testInfo._onCustomMessageCallback = createCustomMessageHandler(testInfo, context);
- await runDaemonForContext(testInfo, context);
+ await _decorateContext(context);
await installScreencastTitleUpdater(testInfo, context, show?.test);
await use(context);
await close();
@@ -464,8 +495,7 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
}
const context = await browserImpl._wrapApiCall(() => browserImpl._newContextForReuse(), { internal: true });
- testInfo._onCustomMessageCallback = createCustomMessageHandler(testInfo, context);
- await runDaemonForContext(testInfo, context);
+ await _decorateContext(context);
await installScreencastTitleUpdater(testInfo, context, show?.test);
await use(context);
const closeReason = testInfo.status === 'timedOut' ? 'Test timeout of ' + testInfo.timeout + 'ms exceeded.' : 'Test ended.';
@@ -484,22 +514,6 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures> = ({
page = await context.newPage();
await use(page);
},
-
- request: async ({ playwright }, use) => {
- const request = await playwright.request.newContext();
- await use(request);
- const hook = (test.info() as TestInfoImpl)._currentHookType();
- if (hook === 'beforeAll') {
- await request.dispose({ reason: [
- `Fixture { request } from beforeAll cannot be reused in a test.`,
- ` - Recommended fix: use a separate { request } in the test.`,
- ` - Alternatively, manually create APIRequestContext in beforeAll and dispose it in afterAll.`,
- `See https://playwright.dev/docs/api-testing#sending-api-requests-from-ui-tests for more details.`,
- ].join('\n') });
- } else {
- await request.dispose();
- }
- },
});
type ScreenshotOption = PlaywrightWorkerOptions['screenshot'] | undefined;
@@ -873,7 +887,7 @@ function tracing() {
return (test.info() as TestInfoImpl)._tracing;
}
-export const test = _baseTest.extend<TestFixtures, WorkerFixtures>(playwrightFixtures);
+export const test = _utilityTest.extend<TestFixtures, WorkerFixtures>(playwrightFixtures);
export { defineConfig, mergeTests } from './common';
export { mergeExpects } from './matchers/expect';
diff --git a/packages/playwright/test.mjs b/packages/playwright/test.mjs
index d30ae00732..69c5f6459b 100644
--- a/packages/playwright/test.mjs
+++ b/packages/playwright/test.mjs
@@ -26,6 +26,7 @@ export const request = playwright.request;
export const _electron = playwright._electron;
export const _android = playwright._android;
export const _baseTest = playwright._baseTest;
+export const _utilityTest = playwright._utilityTest;
export const test = playwright.test;
export const expect = playwright.expect;
export const defineConfig = playwright.defineConfig;
diff --git a/tests/electron/electron-app.js b/tests/electron/electron-app.js
index da709b60a1..0f0bcb707c 100644
--- a/tests/electron/electron-app.js
+++ b/tests/electron/electron-app.js
@@ -1,5 +1,5 @@
const assert = require('node:assert/strict');
-const { app, protocol } = require('electron');
+const { app, protocol, BrowserWindow } = require('electron');
const path = require('path');
assert(process.env.PWTEST_ELECTRON_USER_DATA_DIR, 'PWTEST_ELECTRON_USER_DATA_DIR env var is not set');
@@ -12,4 +12,12 @@ app.whenReady().then(() => {
const url = request.url.substring('vscode-file'.length + 3);
callback({ path: path.join(__dirname, 'assets', url) });
});
+ // Sandboxed windows share process with their window.open() children
+ // and can script them. We use that heavily in our tests.
+ const window = new BrowserWindow({
+ width: 800,
+ height: 600,
+ webPreferences: { sandbox: true },
+ });
+ window.loadURL('about:blank');
});
diff --git a/tests/electron/electron-app.spec.ts b/tests/electron/electron-app.spec.ts
index a2aba343b0..4067442d38 100644
--- a/tests/electron/electron-app.spec.ts
+++ b/tests/electron/electron-app.spec.ts
@@ -123,7 +123,7 @@ test('should dispatch ready event', async ({ launchElectronApp }) => {
]);
});
-test('should script application', async ({ electronApp }) => {
+test('should script application', async ({ app: electronApp }) => {
const appPath = await electronApp.evaluate(async ({ app }) => app.getAppPath());
expect(appPath).toBe(path.resolve(__dirname));
});
@@ -135,85 +135,82 @@ test('should preserve args', async ({ launchElectronApp, isMac }) => {
expect(argv).toEqual([expect.stringContaining(electronPath), expect.stringContaining(path.join('electron', 'electron-app-args.js')), 'foo', 'bar', '& <>^|\\"']);
});
-test('should return windows', async ({ electronApp, newWindow }) => {
- const window = await newWindow();
- expect(electronApp.windows()).toEqual([window]);
+test('should return windows', async ({ app, page }) => {
+ expect(app.windows()).toEqual([page]);
});
-test('should evaluate handle', async ({ electronApp }) => {
- const appHandle = await electronApp.evaluateHandle(({ app }) => app);
- expect(await electronApp.evaluate(({ app }, appHandle) => app === appHandle, appHandle)).toBeTruthy();
+test('should evaluate handle', async ({ app }) => {
+ const appHandle = await app.evaluateHandle(({ app }) => app);
+ expect(await app.evaluate(({ app }, appHandle) => app === appHandle, appHandle)).toBeTruthy();
});
-test('should infer evaluate types', async ({ electronApp }) => {
+test('should infer evaluate types', async ({ app }) => {
// No-arg evaluate, returning a primitive.
- const appPath: string = await electronApp.evaluate(({ app }) => app.getAppPath());
+ const appPath: string = await app.evaluate(({ app }) => app.getAppPath());
expect(typeof appPath).toBe('string');
// Arg evaluate with explicit typing on both sides.
- const sum: number = await electronApp.evaluate(({}, { a, b }) => a + b, { a: 1, b: 2 });
+ const sum: number = await app.evaluate(({}, { a, b }) => a + b, { a: 1, b: 2 });
expect(sum).toBe(3);
// Async evaluate returning an object literal.
- const info = await electronApp.evaluate(async ({ app }) => ({ name: app.getName(), version: app.getVersion() }));
+ const info = await app.evaluate(async ({ app }) => ({ name: app.getName(), version: app.getVersion() }));
const name: string = info.name;
const version: string = info.version;
expect(typeof name).toBe('string');
expect(typeof version).toBe('string');
// evaluateHandle returns JSHandle<R>; jsonValue() preserves R.
- const handle = await electronApp.evaluateHandle(({ app }) => ({ path: app.getAppPath() }));
+ const handle = await app.evaluateHandle(({ app }) => ({ path: app.getAppPath() }));
const jsonValue = await handle.jsonValue();
const path: string = jsonValue.path;
expect(typeof path).toBe('string');
// Passing a JSHandle as an arg unwraps it on the worker side.
- const numberHandle = await electronApp.evaluateHandle(() => 42);
- const doubled: number = await electronApp.evaluate(({}, n) => n * 2, numberHandle);
+ const numberHandle = await app.evaluateHandle(() => 42);
+ const doubled: number = await app.evaluate(({}, n) => n * 2, numberHandle);
expect(doubled).toBe(84);
});
-test('should register custom selector engine', async ({ newWindow }) => {
+test('should register custom selector engine', async ({ page, server }) => {
const tag = `electron-tag-${test.info().workerIndex}`;
await selectors.register(tag, `({
query(root, selector) { return root.querySelector(selector); },
queryAll(root, selector) { return Array.from(root.querySelectorAll(selector)); },
})`);
- const window = await newWindow();
- await window.setContent('<div><span></span></div><div></div>');
- expect(await window.$eval(`${tag}=DIV`, e => e.nodeName)).toBe('DIV');
- expect(await window.$$eval(`${tag}=DIV`, es => es.length)).toBe(2);
+ await page.goto(server.EMPTY_PAGE);
+ await page.setContent('<div><span></span></div><div></div>');
+ expect(await page.$eval(`${tag}=DIV`, e => e.nodeName)).toBe('DIV');
+ expect(await page.$$eval(`${tag}=DIV`, es => es.length)).toBe(2);
});
-test('should route network', async ({ electronApp, newWindow }) => {
- await electronApp.context().route('**/empty.html', async (route, request) => {
+test('should route network', async ({ app, page }) => {
+ await app.context().route('**/empty.html', async (route, request) => {
await route.fulfill({
status: 200,
contentType: 'text/html',
body: '<title>Hello World</title>',
});
});
- const window = await newWindow();
- await window.goto('https://localhost:1000/empty.html');
- expect(await window.title()).toBe('Hello World');
+ await page.goto('https://localhost:1000/empty.html');
+ expect(await page.title()).toBe('Hello World');
});
-test('should support init script', async ({ electronApp, newWindow }) => {
- await electronApp.context().addInitScript('window.magic = 42;');
- const window = await newWindow();
- await window.goto('data:text/html,<script>window.copy = magic</script>');
- expect(await window.evaluate(() => window['copy'])).toBe(42);
+test('should support init script', async ({ app, page }) => {
+ await app.context().addInitScript('window.magic = 42;');
+ await page.goto('data:text/html,<script>window.copy = magic</script>');
+ expect(await page.evaluate(() => window['copy'])).toBe(42);
});
-test('should expose function', async ({ electronApp, newWindow }) => {
- await electronApp.context().exposeFunction('add', (a, b) => a + b);
- const window = await newWindow();
- await window.goto('data:text/html,<script>window["result"] = add(20, 22);</script>');
- expect(await window.evaluate(() => window['result'])).toBe(42);
+test('should expose function', async ({ app, page }) => {
+ await app.context().exposeFunction('add', (a, b) => a + b);
+ await page.goto('data:text/html,<script>window["result"] = add(20, 22);</script>');
+ expect(await page.evaluate(() => window['result'])).toBe(42);
});
-test('should wait for first window', async ({ electronApp }) => {
+test('should wait for first window', async ({ launchElectronApp }) => {
+ const electronApp = await launchElectronApp('electron-app-args.js');
await electronApp.evaluate(({ BrowserWindow }) => {
const window = new BrowserWindow({ width: 800, height: 600 });
void window.loadURL('data:text/html,<title>Hello World!</title>');
@@ -222,10 +219,10 @@ test('should wait for first window', async ({ electronApp }) => {
expect(await window.title()).toBe('Hello World!');
});
-test('should have a clipboard instance', async ({ electronApp }) => {
+test('should have a clipboard instance', async ({ app }) => {
const clipboardContentToWrite = 'Hello from Playwright';
- await electronApp.evaluate(async ({ clipboard }, text) => clipboard.writeText(text), clipboardContentToWrite);
- const clipboardContentRead = await electronApp.evaluate(async ({ clipboard }) => clipboard.readText());
+ await app.evaluate(async ({ clipboard }, text) => clipboard.writeText(text), clipboardContentToWrite);
+ const clipboardContentRead = await app.evaluate(async ({ clipboard }) => clipboard.readText());
expect(clipboardContentRead).toEqual(clipboardContentToWrite);
});
diff --git a/tests/electron/electron-tracing.spec.ts b/tests/electron/electron-tracing.spec.ts
index 84c63d350c..43ccfe89fc 100644
--- a/tests/electron/electron-tracing.spec.ts
+++ b/tests/electron/electron-tracing.spec.ts
@@ -18,12 +18,11 @@ import { electronTest as test, expect } from './electronTest';
test.skip(({ trace }) => trace === 'on');
-test('should record trace', async ({ newWindow, server, runAndTrace }) => {
+test('should record trace', async ({ page, server, runAndTrace }) => {
const traceViewer = await runAndTrace(async () => {
- const window = await newWindow();
- await window.goto(server.PREFIX + '/input/button.html');
- await window.click('button');
- expect(await window.evaluate('result')).toBe('Clicked');
+ await page.goto(server.PREFIX + '/input/button.html');
+ await page.click('button');
+ expect(await page.evaluate('result')).toBe('Clicked');
});
await expect(traceViewer.actionTitles).toHaveText([
/Navigate/,
@@ -32,13 +31,12 @@ test('should record trace', async ({ newWindow, server, runAndTrace }) => {
]);
});
-test('should support custom protocol', async ({ electronApp, newWindow, server, runAndTrace }) => {
- const window = await newWindow();
- await electronApp.evaluate(({ BrowserWindow }) => {
+test('should support custom protocol', async ({ app, page, runAndTrace }) => {
+ await app.evaluate(({ BrowserWindow }) => {
void BrowserWindow.getAllWindows()[0].loadURL('vscode-file://index.html');
});
const traceViewer = await runAndTrace(async () => {
- await window.click('button');
+ await page.click('button');
});
const frame = await traceViewer.snapshotFrame('Click');
await expect(frame.locator('button')).toHaveCSS('color', 'rgb(255, 0, 0)');
diff --git a/tests/electron/electron-window.spec.ts b/tests/electron/electron-window.spec.ts
index 735b62823a..899c22fe1e 100644
--- a/tests/electron/electron-window.spec.ts
+++ b/tests/electron/electron-window.spec.ts
@@ -16,35 +16,31 @@
import { electronTest as test, expect } from './electronTest';
-test('should click the button', async ({ newWindow, server }) => {
- const window = await newWindow();
- await window.goto(server.PREFIX + '/input/button.html');
- await window.click('button');
- expect(await window.evaluate('result')).toBe('Clicked');
+test('should click the button', async ({ page, server }) => {
+ await page.goto(server.PREFIX + '/input/button.html');
+ await page.click('button');
+ expect(await page.evaluate('result')).toBe('Clicked');
});
-test('should check the box', async ({ newWindow }) => {
- const window = await newWindow();
- await window.setContent(`<input id='checkbox' type='checkbox'></input>`);
- await window.check('input');
- expect(await window.evaluate('checkbox.checked')).toBe(true);
+test('should check the box', async ({ page }) => {
+ await page.setContent(`<input id='checkbox' type='checkbox'></input>`);
+ await page.check('input');
+ expect(await page.evaluate('checkbox.checked')).toBe(true);
});
-test('should not check the checked box', async ({ newWindow }) => {
- const window = await newWindow();
- await window.setContent(`<input id='checkbox' type='checkbox' checked></input>`);
- await window.check('input');
- expect(await window.evaluate('checkbox.checked')).toBe(true);
+test('should not check the checked box', async ({ page }) => {
+ await page.setContent(`<input id='checkbox' type='checkbox' checked></input>`);
+ await page.check('input');
+ expect(await page.evaluate('checkbox.checked')).toBe(true);
});
-test('should type into a textarea', async ({ newWindow }) => {
- const window = await newWindow();
- await window.evaluate(() => {
+test('should type into a textarea', async ({ page }) => {
+ await page.evaluate(() => {
const textarea = document.createElement('textarea');
document.body.appendChild(textarea);
textarea.focus();
});
const text = 'Hello world. I am the text that was typed!';
- await window.keyboard.type(text);
- expect(await window.evaluate(() => document.querySelector('textarea').value)).toBe(text);
+ await page.keyboard.type(text);
+ expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe(text);
});
diff --git a/tests/electron/electronTest.ts b/tests/electron/electronTest.ts
index 9adfa8ca68..4d7319fd32 100644
--- a/tests/electron/electronTest.ts
+++ b/tests/electron/electronTest.ts
@@ -18,101 +18,72 @@ import { baseTest } from '../config/baseTest';
import path from 'path';
import fs from 'fs';
import os from 'os';
-import type { Page } from '@playwright/test';
import type { ElectronApplication, Electron } from '@playwright/electron';
-import { electron } from '@playwright/electron';
+import { mergeTests, electron, test as electronBaseTest } from '@playwright/electron';
import type { PageTestFixtures, PageWorkerFixtures } from '../page/pageTestApi';
import type { TraceViewerFixtures } from '../config/traceViewerFixtures';
import { traceViewerFixtures } from '../config/traceViewerFixtures';
import { utils } from '../../packages/playwright-core/lib/coreBundle';
import { inheritAndCleanEnv } from '../config/utils';
-export { expect } from '@playwright/test';
-export { selectors } from '@playwright/electron';
+export { expect, selectors } from '@playwright/electron';
const { removeFolders } = utils;
-type ElectronTestFixtures = PageTestFixtures & {
- electronApp: ElectronApplication;
+type LocalFixtures = PageTestFixtures & {
launchElectronApp: (appFile: string, args?: string[], options?: Parameters<Electron['launch']>[0]) => Promise<ElectronApplication>;
- newWindow: () => Promise<Page>;
createUserDataDir: () => Promise<string>;
};
-export const electronTest = baseTest.extend<TraceViewerFixtures>(traceViewerFixtures).extend<ElectronTestFixtures, PageWorkerFixtures>({
- browserVersion: [({}, use) => use(process.env.ELECTRON_CHROMIUM_VERSION), { scope: 'worker' }],
- browserMajorVersion: [({}, use) => use(Number(process.env.ELECTRON_CHROMIUM_VERSION.split('.')[0])), { scope: 'worker' }],
- electronMajorVersion: [({}, use) => use(parseInt(require('electron/package.json').version.split('.')[0], 10)), { scope: 'worker' }],
- isBidi: [false, { scope: 'worker' }],
- isAndroid: [false, { scope: 'worker' }],
- isElectron: [true, { scope: 'worker' }],
- isHeadlessShell: [false, { scope: 'worker' }],
- isFrozenWebkit: [false, { scope: 'worker' }],
+export const electronTest = mergeTests(baseTest, electronBaseTest)
+ .extend<TraceViewerFixtures>(traceViewerFixtures)
+ .extend<LocalFixtures, PageWorkerFixtures>({
+ browserVersion: [({}, use) => use(process.env.ELECTRON_CHROMIUM_VERSION), { scope: 'worker' }],
+ browserMajorVersion: [({}, use) => use(Number(process.env.ELECTRON_CHROMIUM_VERSION.split('.')[0])), { scope: 'worker' }],
+ electronMajorVersion: [({}, use) => use(parseInt(require('electron/package.json').version.split('.')[0], 10)), { scope: 'worker' }],
+ isBidi: [false, { scope: 'worker' }],
+ isAndroid: [false, { scope: 'worker' }],
+ isElectron: [true, { scope: 'worker' }],
+ isHeadlessShell: [false, { scope: 'worker' }],
+ isFrozenWebkit: [false, { scope: 'worker' }],
- createUserDataDir: async ({ mode }, run) => {
- const dirs: string[] = [];
- // We do not put user data dir in testOutputPath,
- // because we do not want to upload them as test result artifacts.
- await run(async () => {
- const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'playwright-test-'));
- dirs.push(dir);
- return dir;
- });
- await removeFolders(dirs);
- },
-
- launchElectronApp: async ({ createUserDataDir }, use) => {
- // This env prevents 'Electron Security Policy' console message.
- process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
- const apps: ElectronApplication[] = [];
- await use(async (appFile: string, args: string[] = [], options?: Parameters<Electron['launch']>[0]) => {
- const userDataDir = await createUserDataDir();
- const app = await electron.launch({
- ...options,
- args: [path.join(__dirname, appFile), ...args],
- env: inheritAndCleanEnv({ ...options?.env, PWTEST_ELECTRON_USER_DATA_DIR: userDataDir }),
- });
- apps.push(app);
- return app;
- });
- for (const app of apps)
- await app.close();
- },
+ createUserDataDir: async ({ mode }, run) => {
+ const dirs: string[] = [];
+ // We do not put user data dir in testOutputPath,
+ // because we do not want to upload them as test result artifacts.
+ await run(async () => {
+ const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'playwright-test-'));
+ dirs.push(dir);
+ return dir;
+ });
+ await removeFolders(dirs);
+ },
- electronApp: async ({ launchElectronApp }, use) => {
- await use(await launchElectronApp('electron-app.js'));
- },
+ appOptions: async ({ createUserDataDir }, use) => {
+ // This env prevents 'Electron Security Policy' console message.
+ process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
+ const userDataDir = await createUserDataDir();
+ await use({
+ args: [path.join(__dirname, 'electron-app.js')],
+ env: inheritAndCleanEnv({ PWTEST_ELECTRON_USER_DATA_DIR: userDataDir }),
+ });
+ },
- newWindow: async ({ electronApp }, run) => {
- const windows: Page[] = [];
- await run(async () => {
- const [window] = await Promise.all([
- electronApp.waitForEvent('window'),
- electronApp.evaluate(async electron => {
- // Avoid "Error: Cannot create BrowserWindow before app is ready".
- await electron.app.whenReady();
- const window = new electron.BrowserWindow({
- width: 800,
- height: 600,
- // Sandboxed windows share process with their window.open() children
- // and can script them. We use that heavily in our tests.
- webPreferences: { sandbox: true }
+ launchElectronApp: async ({ createUserDataDir }, use) => {
+ // This env prevents 'Electron Security Policy' console message.
+ process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
+ const apps: ElectronApplication[] = [];
+ const userDataDir = await createUserDataDir();
+ await use(async (appFile: string, args: string[] = [], options?: Parameters<Electron['launch']>[0]) => {
+ const app = await electron.launch({
+ ...options,
+ args: [path.join(__dirname, appFile), ...args],
+ env: inheritAndCleanEnv({ ...options?.env, PWTEST_ELECTRON_USER_DATA_DIR: userDataDir }),
});
- await window.loadURL('about:blank');
- })
- ]);
- windows.push(window);
- return window;
+ apps.push(app);
+ return app;
+ });
+ for (const app of apps)
+ await app.close();
+ },
});
- for (const window of windows)
- await window.close();
- },
-
- page: async ({ newWindow }, run) => {
- await run(await newWindow());
- },
-
- context: async ({ electronApp }, run) => {
- await run(electronApp.context());
- },
-});
diff --git a/utils/build/build.js b/utils/build/build.js
index b98b0b1ddb..de692fd301 100644
--- a/utils/build/build.js
+++ b/utils/build/build.js
@@ -549,19 +549,19 @@ for (const pkg of workspace.packages()) {
}));
}
-// playwright-electron/lib/electron.js — self-contained bundle that inlines
+// playwright-electron/lib/index.js — self-contained bundle that inlines
// @utils/* and @isomorphic/* sources (via tsconfig paths) plus the `node_modules`
-// deps. playwright-core, electron, and the sibling loader.js are resolved at
+// deps. playwright, electron, and the sibling loader.js are resolved at
// runtime.
{
const electronPkg = filePath('packages/playwright-electron');
steps.push(new EsbuildStep({
bundle: true,
- entryPoints: [path.join(electronPkg, 'src/electron.ts')],
- outfile: path.join(electronPkg, 'lib/electron.js'),
+ entryPoints: [path.join(electronPkg, 'src/index.ts')],
+ outfile: path.join(electronPkg, 'lib/index.js'),
external: [
- 'playwright-core',
- 'playwright-core/*',
+ 'playwright',
+ 'playwright/*',
'electron',
'electron/*',
'./loader',
diff --git a/utils/generate_types/index.js b/utils/generate_types/index.js
index 1fe6a24fe1..2778848fa4 100644
--- a/utils/generate_types/index.js
+++ b/utils/generate_types/index.js
@@ -619,6 +619,7 @@ class TypesGenerator {
documentation,
doNotGenerate: new Set([
...coreDocumentation.classesArray.map(cls => cls.name),
+ 'ElectronFixtures',
]),
});
return await generator.generateTypes(path.join(__dirname, 'overrides-electron.d.ts'));