Helper functions for Electron end-to-end testing using Playwright
npm install electron-playwright-helpers

Helper functions to make it easier to use Playwright for end-to-end testing with
Electron. Parse packaged Electron projects so you can run tests on them. Click Electron menu items, send IPC messages, get menu structures, stub dialog.showOpenDialog() results, etc.
``shell`
npm i -D electron-playwright-helpers
For a full example of how to use this library, see the
electron-playwright-example project.
But here's a quick example:
Javascript:
`JS
const eph = require('electron-playwright-helpers')
// - or cherry pick -
const { findLatestBuild, parseElectronApp, clickMenuItemById } = require('electron-playwright-helpers')
let electronApp: ElectronApplication
test.beforeAll(async () => {
// find the latest build in the out directory
const latestBuild = findLatestBuild()
// parse the packaged Electron app and find paths and other info
const appInfo = parseElectronApp(latestBuild)
electronApp = await electron.launch({
args: [appInfo.main], // main file from package.json
executablePath: appInfo.executable // path to the Electron executable
})
})
test.afterAll(async () => {
await electronApp.close()
})
test('open a file', async () => {
// stub electron dialog so dialog.showOpenDialog()
// will return a file path without opening a dialog
await eph.stubDialog(electronApp, 'showOpenDialog', { filePaths: ['/path/to/file'] })
// call the click method of menu item in the Electron app's application menu
await eph.clickMenuItemById(electronApp, 'open-file')
// get the result of an ipcMain.handle() function
const result = await eph.ipcMainInvokeHandler(electronApp, 'get-open-file-path')
// result should be the file path
expect(result).toBe('/path/to/file')
})
`
Typescript:
`TS
import * as eph from 'electron-playwright-helpers'
// - or cherry pick -
import { electronWaitForFunction, ipcMainCallFirstListener, clickMenuItemById } from 'electron-playwright-helpers'
// then same as Javascript above
`
Yes, please! Pull requests are always welcome. Feel free to add or suggest new features, fix bugs, etc.
Please use Conventional Commit messages for your commits. This project uses semantic-release to automatically publish new versions to NPM. The commit messages are used to determine the version number and changelog. We're also using Prettier as our code format and ESlint to enforce formatting, so please make sure your code is formatted before submitting a PR.
Version 2.0 introduces significant improvements to handle flakiness issues that appeared with Electron 27+ and Playwright. Starting with Electron 27, Playwright's evaluate() calls became unreliable, often throwing errors like "context or browser has been closed", "Promise was collected", or "Execution context was destroyed" seemingly at random.
#### Built-in Retry Logic
All helper functions now automatically retry operations that fail due to Playwright context issues. This happens transparently - your existing code will work without changes, but will be more reliable.
#### New Utility Functions
- retry(fn, options) - Wrap any Playwright call to automatically retry on context errors
- retryUntilTruthy(fn, options) - Like Playwright's page.waitForFunction() but with automatic retry on errorssetRetryOptions(options)
- - Configure default retry behavior globallygetRetryOptions()
- - Get current retry configurationresetRetryOptions()
- - Reset retry options to defaults
#### Conditional Dialog Stubbing (New!)
- stubDialogMatchers(app, stubs, options) - Stub dialogs with conditional matching based on dialog options
- clearDialogMatchers(app) - Clear dialog matcher stubs
#### 1. Node.js 18+ Required
Version 2.0 requires Node.js 18 or later due to modern JavaScript features like structuredClone().
#### 2. IPC Helper Function Signatures
IPC helpers now accept an optional RetryOptions object as the last argument:
`typescript
// v1.x
await ipcRendererSend(page, 'my-channel', arg1, arg2)
// v2.0 - still works exactly the same
await ipcRendererSend(page, 'my-channel', arg1, arg2)
// v2.0 - with retry options
await ipcRendererSend(page, 'my-channel', arg1, arg2, { timeout: 10000 })
`
This applies to: ipcRendererSend, ipcRendererInvoke, ipcRendererEmit, ipcRendererCallFirstListener, ipcMainEmit, ipcMainCallFirstListener, ipcMainInvokeHandler
#### 3. Menu Helper Function Signatures
Menu helpers now accept an optional RetryOptions object:
`typescript
// v1.x
await clickMenuItemById(electronApp, 'my-menu-item')
// v2.0 - still works exactly the same
await clickMenuItemById(electronApp, 'my-menu-item')
// v2.0 - with retry options
await clickMenuItemById(electronApp, 'my-menu-item', { timeout: 10000 })
`
For most projects, upgrading is straightforward:
1. Update Node.js to version 18 or later
2. Update the package: npm install electron-playwright-helpers@latest
3. Test your suite - existing code should work without changes
If you need to adjust retry behavior globally:
`typescript
import { setRetryOptions, resetRetryOptions } from 'electron-playwright-helpers'
// Increase timeout for slow CI environments
setRetryOptions({
timeout: 10000, // 10 seconds (default: 5000)
poll: 500, // poll every 500ms (default: 200)
})
// Reset to defaults
resetRetryOptions()
`
Or disable retries for specific calls:
`typescript`
await ipcRendererSend(page, 'channel', arg, { disable: true })
If you have custom Playwright evaluate() calls that aren't using our helpers, wrap them with retry():
`typescript
import { retry, retryUntilTruthy } from 'electron-playwright-helpers'
// Wrap evaluate calls to handle context errors
const result = await retry(() =>
electronApp.evaluate(({ app }) => app.getName())
)
// Wait for a condition with automatic error recovery
await retryUntilTruthy(() =>
page.evaluate(() => document.body.classList.contains('ready'))
)
`
* Electron Playwright Example - an example of how to use this library
* Playwright Electron Class - Playwright API docs for Electron
* Electron API - Electron API documentation
Union type of all dialog matcher stubs.
Convert a string or RegExp to a serializable StringMatcher.
RegExp objects cannot be transferred via Playwright's evaluate(),
so we serialize them as {source, flags}.
Check if a value matches a StringMatcher.
Used inside app.evaluate() where the matcher is already serialized.
stringParses the out directory to find the latest build of your Electron project.
Use npm run package (or similar) to build your app prior to testing.
Assumptions: We assume that your build will be in the out directory, and that
the build directory will be named with a hyphen-delimited platform name, e.g.out/my-app-win-x64. If your build directory is not out, you can
pass the name of the directory as the buildDirectory parameter. If your
build directory is not named with a hyphen-delimited platform name, this
function will not work. However, you can pass the build path intoparseElectronApp() directly.
ElectronAppInfoGiven a directory containing an Electron app build,
or the path to the app itself (directory on Mac, executable on Windows),
return a bunch of metadata, including the path to the app's executable
and the path to the app's main file.
Format of the data returned is an object with the following properties:
Promise.<void>Wait for a function to evaluate to true in the main Electron process. This really
should be part of the Playwright API, but it's not.
This function is to electronApp.evaluate()
as page.waitForFunction() is page.evaluate().
Promise.<R>Electron's evaluate function can be flakey,
throwing an error saying the execution context has been destroyed.
This function retries the evaluation several times to see if it can
run the evaluation without an error. If it fails after the retries,
it throws the error.
Type guard to check if a SerializedNativeImage is a success case
Type guard to check if a SerializedNativeImage is an error case
Promise.<T>Retries a given function until it returns a truthy value or the timeout is reached.
This offers similar functionality to Playwright's page.waitForFunction()
method – but with more flexibility and control over the retry attempts. It also defaults to ignoring common errors due to
the way that Playwright handles browser contexts.
Helper to match a string against a pattern (string or RegExp).
For strings, performs a substring match (includes).
For RegExp, tests the pattern against the value.
Promise.<void>Stub a single dialog method. This is a convenience function that calls stubMultipleDialogs
for a single method.
Playwright does not have a way to interact with Electron dialog windows,
so this function allows you to substitute the dialog module's methods during your tests.
By stubbing the dialog module, your Electron application will not display any dialog windows,
and you can control the return value of the dialog methods. You're basically saying
"when my application calls dialog.showOpenDialog, return this value instead". This allows you
to test your application's behavior when the user selects a file, or cancels the dialog, etc.
Note: Each dialog method can only be stubbed with one value at a time, so you will want to callstubDialog before each time that you expect your application to call the dialog method.
Promise.<void>Stub methods of the Electron dialog module.
Playwright does not have a way to interact with Electron dialog windows,
so this function allows you to mock the dialog module's methods during your tests.
By mocking the dialog module, your Electron application will not display any dialog windows,
and you can control the return value of the dialog methods. You're basically saying
"when my application calls dialog.showOpenDialog, return this value instead". This allows you
to test your application's behavior when the user selects a file, or cancels the dialog, etc.
Promise.<void>Stub all dialog methods. This is a convenience function that calls stubMultipleDialogs
for all dialog methods. This is useful if you want to ensure that dialogs are not displayed
during your tests. However, you may want to use stubDialog or stubMultipleDialogs to
control the return value of specific dialog methods (e.g. showOpenDialog) during your tests.
Stub dialog methods with matchers that check dialog options before returning values.
This allows you to set up multiple different return values based on the dialog's
title, message, buttons, or other options.
Matchers are checked in order - the first matching stub wins.
If no stub matches, either an error is thrown (if throwOnUnmatched is true)
or the default value is returned.
Clear all dialog matcher stubs and restore original dialog methods.
Note: This requires the app to have stored the original methods,
which is not done by default. You may need to restart the app
to fully restore dialog functionality.
Promise.<boolean>Emit an ipcMain message from the main process.
This will trigger all ipcMain listeners for the message.
This does not transfer data between main and renderer processes.
It simply emits an event in the main process.
Promise.<unknown>Call the first listener for a given ipcMain message in the main process
and return its result.
NOTE: ipcMain listeners usually don't return a value, but we're using
this to retrieve test data from the main process.
Generally, it's probably better to use ipcMainInvokeHandler() instead.
Promise.<unknown>Get the return value of an ipcMain.handle() function
Promise.<unknown>Send an ipcRenderer.send() (to main process) from a given window.
Note: nodeIntegration must be true and contextIsolation must be false
in the webPreferences for this BrowserWindow.
Promise.<unknown>Send an ipcRenderer.invoke() from a given window.
Note: nodeIntegration must be true and contextIsolation must be false
in the webPreferences for this window
Promise.<unknown>Call just the first listener for a given ipcRenderer channel in a given window.
UNLIKE MOST Electron ipcRenderer listeners, this function SHOULD return a value.
This function does not send data between main and renderer processes.
It simply retrieves data from the renderer process.
Note: nodeIntegration must be true for this BrowserWindow.
Promise.<boolean>Emit an IPC message to a given window.
This will trigger all ipcRenderer listeners for the message.
This does not transfer data between main and renderer processes.
It simply emits an event in the renderer process.
Note: nodeIntegration must be true for this window
Promise.<void>Execute the .click() method on the element with the given id.
NOTE: All menu testing functions will only work with items in the
application menu.
Promise.<void>Click the first matching menu item by any of its properties. This is
useful for menu items that don't have an id. HOWEVER, this is not as fast
or reliable as using clickMenuItemById() if the menu item has an id.
NOTE: All menu testing functions will only work with items in the
application menu.
Promise.<string>Get a given attribute the MenuItem with the given id.
Promise.<MenuItemPartial>Get information about the MenuItem with the given id. Returns serializable values including
primitives, objects, arrays, and other non-recursive data structures.
Promise.<Array.<MenuItemPartial>>Get the current state of the application menu. Contains serializable values including
primitives, objects, arrays, and other non-recursive data structures.
Very similar to menu
construction template structure
in Electron.
Promise.<MenuItemPartial>Find a MenuItem by any of its properties
Promise.<void>Wait for a MenuItem to exist
Promise.<void>Wait for a MenuItem to have a specific attribute value.
For example, wait for a MenuItem to be enabled... or be visible.. etc
Promise.<T>Add a timeout to any Promise
Promise.<T>Add a timeout to any helper function from this library which returns a Promise.
Promise.<T>Retries a function until it returns without throwing an error.
Starting with Electron 27, Playwright can get very flakey when running code in Electron's main or renderer processes.
It will often throw errors like "context or browser has been closed" or "Promise was collected" for no apparent reason.
This function retries a given function until it returns without throwing one of these errors, or until the timeout is reached.
Sets the default retry() options. These options will be used for all subsequent calls to retry() unless overridden.
You can reset the defaults at any time by calling resetRetryOptions().
Gets the current default retry options.
Resets the retry options to their default values.
The default values are:
Converts an unknown error to a string representation.
This function handles different types of errors and attempts to convert them
to a string in a meaningful way. It checks if the error is an object with atoString method and uses that method if available. If the error is a string,
it returns the string directly. For other types, it converts the error to a
JSON string.
Get all windows whose URL matches the given pattern.
Get all windows whose title matches the given pattern.
Get all windows that match the provided matcher function.
Wait for a window whose URL matches the given pattern.
This function checks existing windows first, then listens for new windows.
It uses polling to handle windows that may have their URL change after opening.
Wait for a window whose title matches the given pattern.
This function checks existing windows first, then listens for new windows.
It uses polling to handle windows that may have their title change after opening.
Wait for a window that matches the provided matcher function.
This function:
Format of the data returned from parseElectronApp()
Union type of all dialog matcher stubs.
Convert a string or RegExp to a serializable StringMatcher.
RegExp objects cannot be transferred via Playwright's evaluate(),
so we serialize them as {source, flags}.
Check if a value matches a StringMatcher.
Used inside app.evaluate() where the matcher is already serialized.
stringParses the out directory to find the latest build of your Electron project.
Use npm run package (or similar) to build your app prior to testing.
Assumptions: We assume that your build will be in the out directory, and that
the build directory will be named with a hyphen-delimited platform name, e.g.out/my-app-win-x64. If your build directory is not out, you can
pass the name of the directory as the buildDirectory parameter. If your
build directory is not named with a hyphen-delimited platform name, this
function will not work. However, you can pass the build path intoparseElectronApp() directly.
Kind: global function
Returns: string -
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| buildDirectory | string | "out" |
optional - the directory to search for the latest build (path/name relative to package root or full path starting with /). Defaults to out.
ElectronAppInfoGiven a directory containing an Electron app build,
or the path to the app itself (directory on Mac, executable on Windows),
return a bunch of metadata, including the path to the app's executable
and the path to the app's main file.
Format of the data returned is an object with the following properties:
Kind: global function
Returns: ElectronAppInfo -
metadata about the app
| Param | Type | Description |
| --- | --- | --- |
| buildDir | string |
absolute path to the build directory or the app itself
|Promise.<void>Wait for a function to evaluate to true in the main Electron process. This really
should be part of the Playwright API, but it's not.
This function is to electronApp.evaluate()
as page.waitForFunction() is page.evaluate().
Kind: global function
Fulfil: void Resolves when the function returns true
| Param | Type | Description |
| --- | --- | --- |
| electronApp | ElectronApplication |
the Playwright ElectronApplication
|function | the function to evaluate in the main process - must return a boolean
|Any | optional - an argument to pass to the function
|Promise.<R>Electron's evaluate function can be flakey,
throwing an error saying the execution context has been destroyed.
This function retries the evaluation several times to see if it can
run the evaluation without an error. If it fails after the retries,
it throws the error.
Kind: global function
Returns: Promise.<R> -
| Param | Type | Description |
| --- | --- | --- |
| electronApp | ElectronApplication |
the Playwright ElectronApplication
|function | the function to evaluate in the main process
|Any | an argument to pass to the function
|the number of times to retry the evaluation
|the interval between retries
|Type guard to check if a SerializedNativeImage is a success case
Type guard to check if a SerializedNativeImage is an error case
Promise.<T>Retries a given function until it returns a truthy value or the timeout is reached.
This offers similar functionality to Playwright's page.waitForFunction()
method – but with more flexibility and control over the retry attempts. It also defaults to ignoring common errors due to
the way that Playwright handles browser contexts.
Kind: global function
Returns: Promise.<T> -
- Error
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| fn | function | |
The function to retry. It can return a promise or a value. It should NOT return void/undefined.
|number | 5000 | The maximum time in milliseconds to keep retrying the function. Defaults to 5000ms.
|number | 100 | The delay between each retry attempt in milliseconds. Defaults to 100ms.
|number | 5000 | The maximum time in milliseconds to wait for an individual try to return a result. Defaults to 5000ms.
|number | 200 | The delay between each retry attempt in milliseconds. Defaults to 200ms.
|string \| Array.<string> \| RegExp | | The error message or pattern to match against. Errors that don't match will throw immediately.
|Example
`javascript
test('my test', async () => {
// this will fail immediately if Playwright's context gets weird:
const oldWay = await page.waitForFunction(() => document.body.classList.contains('ready'))
// this will not fail if Playwright's context gets weird:
const newWay = await retryUntilTruthy(() =>
page.evaluate(() => document.body.classList.contains('ready'))
)
})
`
Helper to match a string against a pattern (string or RegExp).
For strings, performs a substring match (includes).
For RegExp, tests the pattern against the value.
Format of the data returned from parseElectronApp()
Kind: global typedef
Properties
| Name | Type | Description |
| --- | --- | --- |
| executable | string |
path to the Electron executable
|string | path to the main (JS) file
|string | name of the your application
|string | path to the resources directory
|boolean | whether the app is packaged as an asar archive
|string | 'darwin', 'linux', or 'win32'
|string | 'x64', 'x32', or 'arm64'
|PackageJson | the JSON.parse()'d contents of the package.json file.
Promise.<void>Stub a single dialog method. This is a convenience function that calls stubMultipleDialogs
for a single method.
Playwright does not have a way to interact with Electron dialog windows,
so this function allows you to substitute the dialog module's methods during your tests.
By stubbing the dialog module, your Electron application will not display any dialog windows,
and you can control the return value of the dialog methods. You're basically saying
"when my application calls dialog.showOpenDialog, return this value instead". This allows you
to test your application's behavior when the user selects a file, or cancels the dialog, etc.
Note: Each dialog method can only be stubbed with one value at a time, so you will want to callstubDialog before each time that you expect your application to call the dialog method.
Kind: global function
Returns: Promise.<void> -
A promise that resolves when the mock is applied.
void - A promise that resolves when the mock is applied. | Param | Type | Description |
| --- | --- | --- |
| app | ElectronApplication |
The Playwright ElectronApplication instance.
|String | The dialog method to mock.
|ReturnType.<Electron.Dialog> | The value that your application will receive when calling this dialog method. See the Electron docs for the return value of each method.
|Example
`ts`
await stubDialog(app, 'showOpenDialog', {
filePaths: ['/path/to/file'],
canceled: false,
})
await clickMenuItemById(app, 'open-file')
// when time your application calls dialog.showOpenDialog,
// it will return the value you specified
Promise.<void>Stub methods of the Electron dialog module.
Playwright does not have a way to interact with Electron dialog windows,
so this function allows you to mock the dialog module's methods during your tests.
By mocking the dialog module, your Electron application will not display any dialog windows,
and you can control the return value of the dialog methods. You're basically saying
"when my application calls dialog.showOpenDialog, return this value instead". This allows you
to test your application's behavior when the user selects a file, or cancels the dialog, etc.
Kind: global function
Returns: Promise.<void> -
A promise that resolves when the mocks are applied.
void - A promise that resolves when the mocks are applied. | Param | Type | Description |
| --- | --- | --- |
| app | ElectronApplication |
The Playwright ElectronApplication instance.
|Array.<DialogMethodStubPartial> | An array of dialog method mocks to apply.
|Example
`ts`
await stubMultipleDialogs(app, [
{
method: 'showOpenDialog',
value: {
filePaths: ['/path/to/file1', '/path/to/file2'],
canceled: false,
},
},
{
method: 'showSaveDialog',
value: {
filePath: '/path/to/file',
canceled: false,
},
},
])
await clickMenuItemById(app, 'save-file')
// when your application calls dialog.showSaveDialog,
// it will return the value you specified
Promise.<void>Stub all dialog methods. This is a convenience function that calls stubMultipleDialogs
for all dialog methods. This is useful if you want to ensure that dialogs are not displayed
during your tests. However, you may want to use stubDialog or stubMultipleDialogs to
control the return value of specific dialog methods (e.g. showOpenDialog) during your tests.
Kind: global function
Returns: Promise.<void> -
A promise that resolves when the mocks are applied.
void - A promise that resolves when the mocks are applied. | Param | Type | Description |
| --- | --- | --- |
| app | ElectronApplication |
The Playwright ElectronApplication instance.
|Stub dialog methods with matchers that check dialog options before returning values.
This allows you to set up multiple different return values based on the dialog's
title, message, buttons, or other options.
Matchers are checked in order - the first matching stub wins.
If no stub matches, either an error is thrown (if throwOnUnmatched is true)
or the default value is returned.
Kind: global function
Returns:
A promise that resolves when the stubs are applied.
| Param | Description |
| --- | --- |
| app |
The Playwright ElectronApplication instance.
|Array of dialog matcher stubs to apply.
|Optional configuration.
|Example
`ts`
// Set up multiple dialog stubs at the start of your test
await stubDialogMatchers(app, [
{
method: 'showMessageBox',
matcher: { title: /delete/i, buttons: /yes/i },
value: { response: 1 }, // Click "Yes" for delete dialogs
},
{
method: 'showMessageBox',
matcher: { title: /save/i },
value: { response: 0 }, // Click "Save" for save dialogs
},
{
method: 'showOpenDialog',
matcher: { title: 'Select Image' },
value: { filePaths: ['/path/to/image.png'], canceled: false },
},
{
method: 'showOpenDialog',
matcher: {}, // Match all other open dialogs
value: { canceled: true },
},
])
Clear all dialog matcher stubs and restore original dialog methods.
Note: This requires the app to have stored the original methods,
which is not done by default. You may need to restart the app
to fully restore dialog functionality.
Kind: global function
Returns:
A promise that resolves when the stubs are cleared.
| Param | Description |
| --- | --- |
| app |
The Playwright ElectronApplication instance.
|Promise.<boolean>Emit an ipcMain message from the main process.
This will trigger all ipcMain listeners for the message.
This does not transfer data between main and renderer processes.
It simply emits an event in the main process.
Kind: global function
Category: IPCMain
Fulfil: boolean true if there were listeners for this message
Reject: Error if there are no ipcMain listeners for the event
| Param | Type | Description |
| --- | --- | --- |
| electronApp | ElectronApplication |
the ElectronApplication object from Playwright
|string | the channel to call all ipcMain listeners for
|unknown | one or more arguments to send
|RetryOptions | optional - options for retrying upon error
|Promise.<unknown>Call the first listener for a given ipcMain message in the main process
and return its result.
NOTE: ipcMain listeners usually don't return a value, but we're using
this to retrieve test data from the main process.
Generally, it's probably better to use ipcMainInvokeHandler() instead.
Kind: global function
Category: IPCMain
Fulfil: unknown resolves with the result of the function
Reject: Error if there are no ipcMain listeners for the event
| Param | Type | Description |
| --- | --- | --- |
| electronApp | ElectronApplication |
the ElectronApplication object from Playwright
|string | the channel to call the first listener for
|unknown | one or more arguments to send
|RetryOptions | optional - options for retrying upon error
|Promise.<unknown>Get the return value of an ipcMain.handle() function
Kind: global function
Category: IPCMain
Fulfil: unknown resolves with the result of the function called in main process
| Param | Type | Description |
| --- | --- | --- |
| electronApp | ElectronApplication |
the ElectronApplication object from Playwright
|string | the channel to call the first listener for
|unknown | one or more arguments to send
|RetryOptions | optional - options for retrying upon error
|Promise.<unknown>Send an ipcRenderer.send() (to main process) from a given window.
Note: nodeIntegration must be true and contextIsolation must be false
in the webPreferences for this BrowserWindow.
Kind: global function
Category: IPCRenderer
Fulfil: unknown resolves with the result of ipcRenderer.send()
| Param | Type | Description |
| --- | --- | --- |
| page | Page |
the Playwright Page to send the ipcRenderer.send() from
|string | the channel to send the ipcRenderer.send() to
|unknown | one or more arguments to send to the ipcRenderer.send()
RetryOptions | optional last argument - options for retrying upon error
|Promise.<unknown>Send an ipcRenderer.invoke() from a given window.
Note: nodeIntegration must be true and contextIsolation must be false
in the webPreferences for this window
Kind: global function
Category: IPCRenderer
Fulfil: unknown resolves with the result of ipcRenderer.invoke()
| Param | Type | Description |
| --- | --- | --- |
| page | Page |
the Playwright Page to send the ipcRenderer.invoke() from
|string | the channel to send the ipcRenderer.invoke() to
|unknown | one or more arguments to send to the ipcRenderer.invoke()
|RetryOptions | optional last argument - options for retrying upon error
|Promise.<unknown>Call just the first listener for a given ipcRenderer channel in a given window.
UNLIKE MOST Electron ipcRenderer listeners, this function SHOULD return a value.
This function does not send data between main and renderer processes.
It simply retrieves data from the renderer process.
Note: nodeIntegration must be true for this BrowserWindow.
Kind: global function
Category: IPCRenderer
Fulfil: unknown the result of the first ipcRenderer.on() listener
| Param | Type | Description |
| --- | --- | --- |
| page | Page |
The Playwright Page to with the ipcRenderer.on() listener
string | The channel to call the first listener for
|unknown | optional - One or more arguments to send to the ipcRenderer.on() listener
|RetryOptions | optional - options for retrying upon error
|Promise.<boolean>Emit an IPC message to a given window.
This will trigger all ipcRenderer listeners for the message.
This does not transfer data between main and renderer processes.
It simply emits an event in the renderer process.
Note: nodeIntegration must be true for this window
Kind: global function
Category: IPCRenderer
Fulfil: boolean true if the event was emitted
Reject: Error if there are no ipcRenderer listeners for the event
| Param | Type | Description |
| --- | --- | --- |
| page | Page |
the Playwright Page to with the ipcRenderer.on() listener
|string | the channel to call all ipcRenderer listeners for
|unknown | optional - one or more arguments to send
|RetryOptions | optional - options for retrying upon error
|Promise.<void>Execute the .click() method on the element with the given id.
NOTE: All menu testing functions will only work with items in the
application menu.
Kind: global function
Category: Menu
Fulfil: void resolves with the result of the click() method - probably undefined
| Param | Type | Description |
| --- | --- | --- |
| electronApp | ElectronApplication |
the Electron application object (from Playwright)
|string | the id of the MenuItem to click
|Promise.<void>Click the first matching menu item by any of its properties. This is
useful for menu items that don't have an id. HOWEVER, this is not as fast
or reliable as using clickMenuItemById() if the menu item has an id.
NOTE: All menu testing functions will only work with items in the
application menu.
Kind: global function
Category: Menu
Fulfil: void resolves with the result of the click() method - probably undefined
| Param | Type | Description |
| --- | --- | --- |
| electronApp | ElectronApplication |
the Electron application object (from Playwright)
|String | a property of the MenuItem to search for
|String \| Number \| Boolean | the value of the property to search for
|Promise.<string>Get a given attribute the MenuItem with the given id.
Kind: global function
Category: Menu
Fulfil: string resolves with the attribute value
| Param | Type | Description |
| --- | --- | --- |
| electronApp | ElectronApplication |
the Electron application object (from Playwright)
|string | the id of the MenuItem to retrieve the attribute from
|string | the attribute to retrieve
|Promise.<MenuItemPartial>Get information about the MenuItem with the given id. Returns serializable values including
primitives, objects, arrays, and other non-recursive data structures.
Kind: global function
Category: Menu
Fulfil: MenuItemPartial the MenuItem with the given id
| Param | Type | Description |
| --- | --- | --- |
| electronApp | ElectronApplication |
the Electron application object (from Playwright)
|string | the id of the MenuItem to retrieve
|Promise.<Array.<MenuItemPartial>>Get the current state of the application menu. Contains serializable values including
primitives, objects, arrays, and other non-recursive data structures.
Very similar to menu
construction template structure
in Electron.
Kind: global function
Category: Menu
Fulfil: MenuItemPartial[] an array of MenuItem-like objects
| Param | Type | Description |
| --- | --- | --- |
| electronApp | ElectronApplication |
the Electron application object (from Playwright)
|Promise.<MenuItemPartial>Find a MenuItem by any of its properties
Kind: global function
Category: Menu
Fulfil: MenuItemPartial the first MenuItem with the given property and value
| Param | Type | Description |
| --- | --- | --- |
| electronApp | ElectronApplication |
the Electron application object (from Playwright)
|string | the property to search for
|string | the value to search for
|MenuItemPartial \| Array.<MenuItemPartial> | optional - single MenuItem or array - if not provided, will be retrieved from the application menu
|Promise.<void>Wait for a MenuItem to exist
Kind: global function
Category: Menu
Fulfil: void resolves when the MenuItem is found
| Param | Type | Description |
| --- | --- | --- |
| electronApp | ElectronApplication |
the Electron application object (from Playwright)
|string | the id of the MenuItem to wait for
|Promise.<void>Wait for a MenuItem to have a specific attribute value.
For example, wait for a MenuItem to be enabled... or be visible.. etc
Kind: global function
Category: Menu
Fulfil: void resolves when the MenuItem with correct status is found
| Param | Type | Description |
| --- | --- | --- |
| electronApp | ElectronApplication |
the Electron application object (from Playwright)
|string | the id of the MenuItem to wait for
|string | the property to search for
|string \| number \| boolean | the value to search for
|Promise.<T>Add a timeout to any Promise
Kind: global function
Returns: Promise.<T> -
the result of the original promise if it resolves before the timeout
| Param | Default | Description |
| --- | --- | --- |
| promise | |
the promise to add a timeout to - must be a Promise
|5000 | the timeout in milliseconds - defaults to 5000
|optional - the message to return if the timeout is reached
|Promise.<T>Add a timeout to any helper function from this library which returns a Promise.
Kind: global function
Returns: Promise.<T> -
the result of the helper function if it resolves before the timeout
| Param | Default | Description |
| --- | --- | --- |
| functionName | |
the name of the helper function to call
|5000 | the timeout in milliseconds - defaults to 5000
|optional - the message to return if the timeout is reached
|any arguments to pass to the helper function
|Promise.<T>Retries a function until it returns without throwing an error.
Starting with Electron 27, Playwright can get very flakey when running code in Electron's main or renderer processes.
It will often throw errors like "context or browser has been closed" or "Promise was collected" for no apparent reason.
This function retries a given function until it returns without throwing one of these errors, or until the timeout is reached.
Kind: global function
Returns: Promise.<T> -
A promise that resolves with the result of the function or rejects with an error or timeout message.
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| fn | function | |
The function to retry.
|RetryOptions | {} | The options for retrying the function.
|number | 5000 | The maximum time to wait before giving up in milliseconds.
|number | 200 | The delay between each retry attempt in milliseconds.
|string \| Array.<string> \| RegExp | "['context or browser has been closed', 'Promise was collected', 'Execution context was destroyed']" | String(s) or regex to match against error message. If the error does not match, it will throw immediately. If it does match, it will retry.
|Example
You can simply wrap your Playwright calls in this function to make them more reliable:
`javascript() =>
test('my test', async () => {
// instead of this:
const oldWayRenderer = await page.evaluate(() => document.body.classList.contains('active'))
const oldWayMain = await electronApp.evaluate(({}) => document.body.classList.contains('active'))
// use this:
const newWay = await retry(() =>
page.evaluate(() => document.body.classList.contains('active'))
)
// note the in front of the original function callawait
// and the keyword in front of retry,page.evaluate
// but NOT in front of `
})
Sets the default retry() options. These options will be used for all subsequent calls to retry() unless overridden.
You can reset the defaults at any time by calling resetRetryOptions().
Kind: global function
Returns:
The updated retry options.
| Param | Description |
| --- | --- |
| options |
A partial object containing the retry options to be set.
|Gets the current default retry options.
Kind: global function
Returns:
The current retry options.
Resets the retry options to their default values.
The default values are:
Kind: global function
Category: Utilities
Converts an unknown error to a string representation.
This function handles different types of errors and attempts to convert them
to a string in a meaningful way. It checks if the error is an object with atoString method and uses that method if available. If the error is a string,
it returns the string directly. For other types, it converts the error to a
JSON string.
Kind: global function
Returns:
A string representation of the error.
| Param | Description |
| --- | --- |
| err |
The unknown error to be converted to a string.
|Get all windows whose URL matches the given pattern.
Kind: global function
Returns:
An array of matching Pages
| Param | Description |
| --- | --- |
| electronApp |
The Playwright ElectronApplication
|A string (substring match) or RegExp to match against the URL
|Options with all: true to return all matches
Example
`ts`
const allSettingsWindows = await getWindowByUrl(app, '/settings', { all: true })
Get all windows whose title matches the given pattern.
Kind: global function
Returns:
An array of matching Pages
| Param | Description |
| --- | --- |
| electronApp |
The Playwright ElectronApplication
|A string (substring match) or RegExp to match against the title
|Options with all: true to return all matches
Example
`ts`
const allNumberedWindows = await getWindowByTitle(app, /Window \d+/, { all: true })
Get all windows that match the provided matcher function.
Kind: global function
Returns:
An array of matching Pages
| Param | Description |
| --- | --- |
| electronApp |
The Playwright ElectronApplication
|A function that receives a Page and returns true if it matches
|Options with all: true to return all matches
Example
`ts`
const allLargeWindows = await getWindowByMatcher(app, async (page) => {
const size = await page.viewportSize()
return size && size.width > 1000
}, { all: true })
Wait for a window whose URL matches the given pattern.
This function checks existing windows first, then listens for new windows.
It uses polling to handle windows that may have their URL change after opening.
Kind: global function
Returns:
The matching Page
-
Error if timeout is reached before a matching window is found
| Param | Description |
| --- | --- |
| electronApp |
The Playwright ElectronApplication
|A string (substring match) or RegExp to match against the URL
|Optional timeout and interval settings
|Example
`ts`
// Click something that opens a new window, then wait for it
await page.click('#open-settings')
const settingsWindow = await waitForWindowByUrl(app, '/settings', { timeout: 5000 })
Wait for a window whose title matches the given pattern.
This function checks existing windows first, then listens for new windows.
It uses polling to handle windows that may have their title change after opening.
Kind: global function
Returns:
The matching Page
-
Error if timeout is reached before a matching window is found
| Param | Description |
| --- | --- |
| electronApp |
The Playwright ElectronApplication
|A string (substring match) or RegExp to match against the title
|Optional timeout and interval settings
|Example
`ts`
// Wait for a window with a specific title to appear
const prefsWindow = await waitForWindowByTitle(app, 'Preferences', { timeout: 5000 })
Wait for a window that matches the provided matcher function.
This function:
Kind: global function
Returns:
The matching Page
-
Error if timeout is reached before a matching window is found
| Param | Description |
| --- | --- |
| electronApp |
The Playwright ElectronApplication
|A function that receives a Page and returns true if it matches
|Optional timeout and interval settings
|Example
`ts``
const window = await waitForWindowByMatcher(app, async (page) => {
const title = await page.title()
return title.startsWith('Document:')
}, { timeout: 10000 })