For given versions of Electron you must depend on a very specific version range of Spectron. Below is a version mapping table between Spectron version and Electron version.
|Electron Version||Spectron Version|
Learn more from this presentation.
🚨 Upgrading from
3.x? Read the changelog.
npm install --save-dev spectron
Spectron works with any testing framework but the following example uses mocha:
To get up and running from your command line:
# Install mocha locally as a dev dependency.npm i mocha -D# From the project root, create a folder called test, in that directory, create a file called 'spec.js'touch test/spec.js# Change directory to testcd test
Then simply include the following in your first
const Application = Applicationconst assert =const electronPath = // Require Electron from the binaries included in node_modules.const path =
Create an npm task in your package.json file
And from the root of your project, in your command-line simply run:
By default, mocha searches for a folder with the name
test ( which we created before ).
For more information on how to configure mocha, please visit mocha.
As stated in issue #19, Spectron will not be able to start if your Electron app is launched using the
remote-debugging-port command-line switch (i.e.
app.commandLine.appendSwitch('remote-debugging-port', <debugging-port-number>);). Please make sure to include the necessary logic in your app's code to disable the switch during tests.
Spectron exports an
Application class that when configured, can start and
stop your Electron application.
Create a new application with the following options:
path- Required. String path to the Electron application executable to launch. Note: If you want to invoke
electrondirectly with your app's main script then you should specify
electron-prebuiltand specify your app's main script path as the first argument in the
args- Array of arguments to pass to the Electron application.
chromeDriverArgs- Array of arguments to pass to ChromeDriver. See here for details on the Chrome arguments.
cwd- String path to the working directory to use for the launched application. Defaults to
env- Object of additional environment variables to set in the launched application.
host- String host name of the launched
chromedriverprocess. Defaults to
port- Number port of the launched
chromedriverprocess. Defaults to
nodePath- String path to a
nodeexecutable to launch ChromeDriver with. Defaults to
connectionRetryCount- Number of retry attempts to make when connecting to ChromeDriver. Defaults to
connectionRetryTimeout- Number in milliseconds to wait for connections to ChromeDriver to be made. Defaults to
quitTimeout- Number in milliseconds to wait for application quitting. Defaults to
requireName- Custom property name to use when requiring modules. Defaults to
require. This should only be used if your application deletes the main
window.requirefunction and assigns it to another property name on
startTimeout- Number in milliseconds to wait for ChromeDriver to start. Defaults to
waitTimeout- Number in milliseconds to wait for calls like
waitUntilWindowLoadedto complete. Defaults to
debuggerAddress- String address of a Chrome debugger server to connect to.
chromeDriverLogPath- String path to file to store ChromeDriver logs in. Setting this option enables
--verboselogging when starting ChromeDriver.
webdriverLogPath- String path to a directory where Webdriver will write logs to. Setting this option enables
verboselogging from Webdriver.
webdriverOptions- Object of additional options for Webdriver
The Electron helpers provided by Spectron require accessing the core Electron
APIs in the renderer processes of your application. So, either your Electron
nodeIntegration set to
true or you'll need to expose a
require window global to Spectron so it can access the core Electron APIs.
You can do this by adding a
preload script that does the following:
if processenvNODE_ENV === 'test'windowelectronRequire = require
Then create the Spectron
Application with the
requireName option set to
'electronRequire' and then runs your tests via
NODE_ENV=test npm test.
Note: This is only required if your tests are accessing any Electron APIs.
You don't need to do this if you are only accessing the helpers on the
property which do not require Node integration.
Spectron uses WebdriverIO and exposes the managed
client property on the created
client API is WebdriverIO's
browser object. Documentation can be found
Several additional commands are provided specific to Electron.
All the commands return a
So if you wanted to get the text of an element you would do:
electron property is your gateway to accessing the full Electron API.
Each Electron module is exposed as a property on the
so you can think of it as an alias for
require('electron') from within your
So if you wanted to access the clipboard API in your tests you would do:
browserWindow property is an alias for
It provides you access to the current BrowserWindow and contains all the APIs.
So if you wanted to check if the current window is visible in your tests you would do:
It is named
browserWindow instead of
window so that it doesn't collide
with the WebDriver command of that name.
capturePage API is supported but instead of taking a callback it
Promise that resolves to a
Buffer that is the image data of
webContents property is an alias for
It provides you access to the WebContents for the current window and contains all the APIs.
So if you wanted to check if the current window is loading in your tests you would do:
savePage API is supported but instead of taking a callback it
Promise that will raise any errors and resolve to
Promise that will resolve with the result of the last statement of the
mainProcess property is an alias for
It provides you access to the main process's process global.
So if you wanted to get the
argv for the main process in your tests you would
Properties on the
process are exposed as functions that return promises so
make sure to call
mainProcess.env().then(...) instead of
rendererProcess property is an alias for
It provides you access to the renderer process's process global.
So if you wanted to get the environment variables for the renderer process in your tests you would do:
Starts the application. Returns a
Promise that will be resolved when the
application is ready to use. You should always wait for start to complete
before running any commands.
Stops the application. Returns a
Promise that will be resolved once the
application has stopped.
Stops the application and then starts it. Returns a
Promise that will be
resolved once the application has started again.
Checks to determine if the application is running or not.
Get all the configured options passed to the
new Application() constructor.
This will include the default options values currently being used.
console log output from the main process. The logs are cleared
after they are returned.
Promise that resolves to an array of string log messages
console log output from the render process. The logs are cleared
after they are returned.
Promise that resolves to an array of log objects.
Get the selected text in the current window.
Gets the number of open windows.
<webview> tags are also counted as separate windows.
client.waitUntilTextExists(selector, text, [timeout])
Waits until the element matching the given selector contains the given
text. Takes an optional timeout in milliseconds that defaults to
Wait until the window is no longer loading. Takes an optional timeout
in milliseconds that defaults to
Focus a window using its index from the
<webview> tags can also be focused as a separate window.
Focus a window using its URL or title.
// switch via url matchappclient// switch via title matchappclient
Spectron bundles the Accessibility Developer Tools
provided by Google and adds support for auditing each window and
tag in your application.
Run an accessibility audit in the focused window with the specified options.
options- An optional Object with the following keys:
trueto ignore failures with a severity of
'Warning'and only include failures with a severity of
'Severe'. Defaults to
ignoreRules- Array of String rule code values such as
AX_COLOR_01to ignore failures for. The full list is available here.
audit Object with the following properties:
message- A detailed String message about the results
failed- A Boolean,
falsewhen the audit has failures
results- An array of detail objects for each failed rule. Each object in the array has the following properties:
code- A unique String accessibility rule identifier
elements- An Array of Strings representing the selector path of each HTML element that failed the rule
message- A String message about the failed rule
url- A String URL providing more details about the failed rule
See https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules for more details about the audit rules.
If you are using a
<webview> tag in your app and want to audit both the outer
page and the
<webview>'s page then you will need to do the following:
// Focus main page and audit itappclient
On Travis CI
You will want to add the following to your
.travis.yml file when building on
before_script:- "export DISPLAY=:99.0"- "sh -e /etc/init.d/xvfb start"- sleep 3 # give xvfb some time to start
Check out Spectron's .travis.yml file for a production example.
You will want to add the following to your
Check out Spectron's appveyor.yml file for a production example.
Test Library Examples
With Chai As Promised
Using these together allows you to chain assertions together and have fewer callback blocks. See below for a simple example:
npm install --save-dev chainpm install --save-dev chai-as-promised
const Application = Applicationconst chai =const chaiAsPromised =const electronPath =const path =chaichai
Spectron works with AVA, which allows you to write your tests in ES2015+ without doing any extra work.
AVA has built-in support for async functions, which simplifies async operations: