Automated Testing

Test automation is an efficient way of validating that your application code works as intended. While Electron doesn’t actively maintain its own testing solution, this guide will go over a couple ways you can run end-to-end automated tests on your Electron app.

Using the WebDriver interface

From ChromeDriver - WebDriver for Chrome:

WebDriver is an open source tool for automated testing of web apps across many browsers. It provides capabilities for navigating to web pages, user input, JavaScript execution, and more. ChromeDriver is a standalone server which implements WebDriver’s wire protocol for Chromium. It is being developed by members of the Chromium and WebDriver teams.

There are a few ways that you can set up testing using WebDriver.

With WebdriverIO

WebdriverIO (WDIO) is a test automation framework that provides a Node.js package for testing with WebDriver. Its ecosystem also includes various plugins (e.g. reporter and services) that can help you put together your test setup.

Install the testrunner

First you need to run the WebdriverIO starter toolkit in your project root directory:

```sh npm2yarn npx wdio . —yes

  1. This installs all necessary packages for you and generates a `wdio.conf.js` configuration file.
  2. #### Connect WDIO to your Electron app
  3. Update the capabilities in your configuration file to point to your Electron app binary:
  4. ```javascript title='wdio.conf.js'
  5. export.config = {
  6. // ...
  7. capabilities: [{
  8. browserName: 'chrome',
  9. 'goog:chromeOptions': {
  10. binary: '/path/to/your/electron/binary', // Path to your Electron binary.
  11. args: [/* cli arguments */] // Optional, perhaps 'app=' + /path/to/your/app/
  12. }
  13. }]
  14. // ...
  15. }

Run your tests

To run your tests:

  1. $ npx wdio run wdio.conf.js

With Selenium

Selenium is a web automation framework that exposes bindings to WebDriver APIs in many languages. Their Node.js bindings are available under the selenium-webdriver package on NPM.

Run a ChromeDriver server

In order to use Selenium with Electron, you need to download the electron-chromedriver binary, and run it:

```sh npm2yarn npm install —save-dev electron-chromedriver ./node_modules/.bin/chromedriver Starting ChromeDriver (v2.10.291558) on port 9515 Only local connections are allowed.

  1. Remember the port number `9515`, which will be used later.
  2. #### Connect Selenium to ChromeDriver
  3. Next, install Selenium into your project:
  4. ```sh npm2yarn
  5. npm install --save-dev selenium-webdriver

Usage of selenium-webdriver with Electron is the same as with normal websites, except that you have to manually specify how to connect ChromeDriver and where to find the binary of your Electron app:

```js title=’test.js’ const webdriver = require(‘selenium-webdriver’) const driver = new webdriver.Builder() // The “9515” is the port opened by ChromeDriver. .usingServer(‘http://localhost:9515‘) .withCapabilities({ ‘goog:chromeOptions’: { // Here is the path to your Electron binary. binary: ‘/Path-to-Your-App.app/Contents/MacOS/Electron’ } }) .forBrowser(‘chrome’) // note: use .forBrowser(‘electron’) for selenium-webdriver <= 3.6.0 .build() driver.get(‘http://www.google.com‘) driver.findElement(webdriver.By.name(‘q’)).sendKeys(‘webdriver’) driver.findElement(webdriver.By.name(‘btnG’)).click() driver.wait(() => { return driver.getTitle().then((title) => { return title === ‘webdriver - Google Search’ }) }, 1000) driver.quit()

  1. ## Using Playwright
  2. [Microsoft Playwright](https://playwright.dev) is an end-to-end testing framework built
  3. using browser-specific remote debugging protocols, similar to the [Puppeteer] headless
  4. Node.js API but geared towards end-to-end testing. Playwright has experimental Electron
  5. support via Electron's support for the [Chrome DevTools Protocol] (CDP).
  6. ### Install dependencies
  7. You can install Playwright through your preferred Node.js package manager. The Playwright team
  8. recommends using the `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` environment variable to avoid
  9. unnecessary browser downloads when testing an Electron app.
  10. ```sh npm2yarn
  11. PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm install --save-dev playwright

Playwright also comes with its own test runner, Playwright Test, which is built for end-to-end testing. You can also install it as a dev dependency in your project:

```sh npm2yarn npm install —save-dev @playwright/test

  1. :::caution Dependencies
  2. This tutorial was written `playwright@1.16.3` and `@playwright/test@1.16.3`. Check out
  3. [Playwright's releases][playwright-releases] page to learn about
  4. changes that might affect the code below.
  5. :::
  6. :::info Using third-party test runners
  7. If you're interested in using an alternative test runner (e.g. Jest or Mocha), check out
  8. Playwright's [Third-Party Test Runner][playwright-test-runners] guide.
  9. :::
  10. ### Write your tests
  11. Playwright launches your app in development mode through the `_electron.launch` API.
  12. To point this API to your Electron app, you can pass the path to your main process
  13. entry point (here, it is `main.js`).
  14. ```js {5}
  15. const { _electron: electron } = require('playwright')
  16. const { test } = require('@playwright/test')
  17. test('launch app', async () => {
  18. const electronApp = await electron.launch({ args: ['main.js'] })
  19. // close app
  20. await electronApp.close()
  21. })

After that, you will access to an instance of Playwright’s ElectronApp class. This is a powerful class that has access to main process modules for example:

```js {6-11} const { _electron: electron } = require(‘playwright’) const { test } = require(‘@playwright/test’)

test(‘get isPackaged’, async () => { const electronApp = await electron.launch({ args: [‘main.js’] }) const isPackaged = await electronApp.evaluate(async ({ app }) => { // This runs in Electron’s main process, parameter here is always // the result of the require(‘electron’) in the main app script. return app.isPackaged }) console.log(isPackaged) // false (because we’re in development mode) // close app await electronApp.close() })

  1. It can also create individual [Page][playwright-page] objects from Electron BrowserWindow instances.
  2. For example, to grab the first BrowserWindow and save a screenshot:
  3. ```js {6-7}
  4. const { _electron: electron } = require('playwright')
  5. const { test } = require('@playwright/test')
  6. test('save screenshot', async () => {
  7. const electronApp = await electron.launch({ args: ['main.js'] })
  8. const window = await electronApp.firstWindow()
  9. await window.screenshot({ path: 'intro.png' })
  10. // close app
  11. await electronApp.close()
  12. })

Putting all this together using the PlayWright Test runner, let’s create a example.spec.js test file with a single test and assertion:

```js title=’example.spec.js’ const { _electron: electron } = require(‘playwright’) const { test, expect } = require(‘@playwright/test’)

test(‘example test’, async () => { const electronApp = await electron.launch({ args: [‘.’] }) const isPackaged = await electronApp.evaluate(async ({ app }) => { // This runs in Electron’s main process, parameter here is always // the result of the require(‘electron’) in the main app script. return app.isPackaged; });

expect(isPackaged).toBe(false);

// Wait for the first BrowserWindow to open // and return its Page object const window = await electronApp.firstWindow() await window.screenshot({ path: ‘intro.png’ })

// close app await electronApp.close() });

  1. Then, run Playwright Test using `npx playwright test`. You should see the test pass in your
  2. console, and have an `intro.png` screenshot on your filesystem.
  3. ```console
  4. ☁ $ npx playwright test
  5. Running 1 test using 1 worker
  6. ✓ example.spec.js:4:1 › example test (1s)

:::info Playwright Test will automatically run any files matching the .*(test|spec)\.(js|ts|mjs) regex. You can customize this match in the Playwright Test configuration options. :::

:::tip Further reading Check out Playwright’s documentation for the full Electron and ElectronApplication class APIs. :::

Using a custom test driver

It’s also possible to write your own custom driver using Node.js’ built-in IPC-over-STDIO. Custom test drivers require you to write additional app code, but have lower overhead and let you expose custom methods to your test suite.

To create a custom driver, we’ll use Node.js’ child_process API. The test suite will spawn the Electron process, then establish a simple messaging protocol:

```js title=’testDriver.js’ const childProcess = require(‘child_process’) const electronPath = require(‘electron’)

// spawn the process const env = { // } const stdio = [‘inherit’, ‘inherit’, ‘inherit’, ‘ipc’] const appProcess = childProcess.spawn(electronPath, [‘./app’], { stdio, env })

// listen for IPC messages from the app appProcess.on(‘message’, (msg) => { // … })

// send an IPC message to the app appProcess.send({ my: ‘message’ })

  1. From within the Electron app, you can listen for messages and send replies using the Node.js
  2. [`process`](https://nodejs.org/api/process.html) API:
  3. ```js title='main.js'
  4. // listen for messages from the test suite
  5. process.on('message', (msg) => {
  6. // ...
  7. })
  8. // send a message to the test suite
  9. process.send({ my: 'message' })

We can now communicate from the test suite to the Electron app using the appProcess object.

For convenience, you may want to wrap appProcess in a driver object that provides more high-level functions. Here is an example of how you can do this. Let’s start by creating a TestDriver class:

```js title=’testDriver.js’ class TestDriver { constructor ({ path, args, env }) { this.rpcCalls = []

  1. // start child process
  2. env.APP_TEST_DRIVER = 1 // let the app know it should listen for messages
  3. this.process = childProcess.spawn(path, args, { stdio: ['inherit', 'inherit', 'inherit', 'ipc'], env })
  4. // handle rpc responses
  5. this.process.on('message', (message) => {
  6. // pop the handler
  7. const rpcCall = this.rpcCalls[message.msgId]
  8. if (!rpcCall) return
  9. this.rpcCalls[message.msgId] = null
  10. // reject/resolve
  11. if (message.reject) rpcCall.reject(message.reject)
  12. else rpcCall.resolve(message.resolve)
  13. })
  14. // wait for ready
  15. this.isReady = this.rpc('isReady').catch((err) => {
  16. console.error('Application failed to start', err)
  17. this.stop()
  18. process.exit(1)
  19. })

}

// simple RPC call // to use: driver.rpc(‘method’, 1, 2, 3).then(…) async rpc (cmd, …args) { // send rpc request const msgId = this.rpcCalls.length this.process.send({ msgId, cmd, args }) return new Promise((resolve, reject) => this.rpcCalls.push({ resolve, reject })) }

stop () { this.process.kill() } }

module.exports = { TestDriver };

  1. In your app code, can then write a simple handler to receive RPC calls:
  2. ```js title='main.js'
  3. const METHODS = {
  4. isReady () {
  5. // do any setup needed
  6. return true
  7. }
  8. // define your RPC-able methods here
  9. }
  10. const onMessage = async ({ msgId, cmd, args }) => {
  11. let method = METHODS[cmd]
  12. if (!method) method = () => new Error('Invalid method: ' + cmd)
  13. try {
  14. const resolve = await method(...args)
  15. process.send({ msgId, resolve })
  16. } catch (err) {
  17. const reject = {
  18. message: err.message,
  19. stack: err.stack,
  20. name: err.name
  21. }
  22. process.send({ msgId, reject })
  23. }
  24. }
  25. if (process.env.APP_TEST_DRIVER) {
  26. process.on('message', onMessage)
  27. }

Then, in your test suite, you can use your TestDriver class with the test automation framework of your choosing. The following example uses ava, but other popular choices like Jest or Mocha would work as well:

```js title=’test.js’ const test = require(‘ava’) const electronPath = require(‘electron’) const { TestDriver } = require(‘./testDriver’)

const app = new TestDriver({ path: electronPath, args: [‘./app’], env: { NODE_ENV: ‘test’ } }) test.before(async t => { await app.isReady }) test.after.always(‘cleanup’, async t => { await app.stop() }) ```