Easily test your Electron apps using ChromeDriver and WebdriverIO.
This minor version of this library tracks the minor version of the Electron
versions released. So if you are using Electron 1.0.x
you would want to use
a spectron
dependency of ~3.0.0
in your package.json
file.
Learn more from this presentation.
๐จ Upgrading from 1.x
to 2.x
/3.x
? Read the changelog.
npm install --save-dev spectron
Spectron works with any testing framework but the following example uses mocha:
var Application = require('spectron').Application
var assert = require('assert')
describe('application launch', function () {
this.timeout(10000)
beforeEach(function () {
this.app = new Application({
path: '/Applications/MyApp.app/Contents/MacOS/MyApp'
})
return this.app.start()
})
afterEach(function () {
if (this.app && this.app.isRunning()) {
return this.app.stop()
}
})
it('shows an initial window', function () {
return this.app.client.getWindowCount().then(function (count) {
assert.equal(count, 1)
})
})
})
Spectron exports an Application
class that when configured, can start and
stop your Electron application.
Create a new application with the following options:
path
- String path to the application executable to launch. Requiredargs
- Array of arguments to pass to the executable. See here for details on the Chrome arguments.cwd
- String path to the working directory to use for the launched application. Defaults toprocess.cwd()
.env
- Object of additional environment variables to set in the launched application.host
- String host name of the launchedchromedriver
process. Defaults to'localhost'
.port
- Number port of the launchedchromedriver
process. Defaults to9515
.nodePath
- String path to anode
executable to launch ChromeDriver with. Defaults toprocess.execPath
.connectionRetryCount
- Number of retry attempts to make when connecting to ChromeDriver. Defaults to10
attempts.connectionRetryTimeout
- Number in milliseconds to wait for connections to ChromeDriver to be made. Defaults to30000
milliseconds.quitTimeout
- Number in milliseconds to wait for application quitting. Defaults to1000
milliseconds.requireName
- Custom property name to use when requiring modules. Defaults torequire
. This should only be used if your application deletes the mainwindow.require
function and assigns it to another property name onwindow
.startTimeout
- Number in milliseconds to wait for ChromeDriver to start. Defaults to5000
milliseconds.waitTimeout
- Number in milliseconds to wait for calls likewaitUntilTextExists
andwaitUntilWindowLoaded
to complete. Defaults to5000
milliseconds.
Spectron uses WebdriverIO and exposes the managed
client
property on the created Application
instances.
The full client
API provided by WebdriverIO can be found
here.
Several additional commands are provided specific to Electron.
All the commands return a Promise
.
So if you wanted to get the text of an element you would do:
app.client.getText('#error-alert').then(function (errorText) {
console.log('The #error-alert text content is ' + errorText)
})
The electron
property is your gateway to accessing the full Electron API.
Each Electron module is exposed as a property on the electron
property
so you can think of it as an alias for require('electron')
from within your
app.
So if you wanted to access the clipboard API in your tests you would do:
app.electron.clipboard.writeText('pasta')
.electron.clipboard.readText().then(function (clipboardText) {
console.log('The clipboard text is ' + clipboardText)
})
The browserWindow
property is an alias for require('electron').remote.getCurrentWindow()
.
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:
app.browserWindow.isVisible().then(function (visible) {
console.log('window is visible? ' + visible)
})
It is named browserWindow
instead of window
so that it doesn't collide
with the WebDriver command of that name.
The webContents
property is an alias for require('electron').remote.getCurrentWebContents()
.
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:
app.webContents.isLoading().then(function (visible) {
console.log('window is loading? ' + visible)
})
The mainProcess
property is an alias for require('electron').remote.process
.
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
do:
app.mainProcess.argv().then(function (argv) {
console.log('main process args: ' + argv)
})
Properties on the process
are exposed as functions that return promises so
make sure to call mainProcess.env().then(...)
instead of
mainProcess.env.then(...)
.
The rendererProcess
property is an alias for global.process
.
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:
app.rendererProcess.env().then(function (env) {
console.log('main process args: ' + env)
})
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.
Gets the console
log output from the main process. The logs are cleared
after they are returned.
Returns a Promise
that resolves to an array of string log messages
app.client.getMainProcessLogs().then(function (logs) {
logs.forEach(function (log) {
console.log(log)
})
})
Gets the console
log output from the render process. The logs are cleared
after they are returned.
Returns a Promise
that resolves to an array of log objects.
app.client.getRenderProcessLogs().then(function (logs) {
logs.forEach(function (log) {
console.log(log.message)
console.log(log.source)
console.log(log.level)
})
})
Get the selected text in the current window.
app.client.getSelectedText().then(function (selectedText) {
console.log(selectedText)
})
Gets the number of open windows.
app.client.getWindowCount().then(function (count) {
console.log(count)
})
Waits until the element matching the given selector contains the given
text. Takes an optional timeout in milliseconds that defaults to 5000
.
app.client.waitUntilTextExists('#message', 'Success', 10000)
Wait until the window is no longer loading. Takes an optional timeout
in milliseconds that defaults to 5000
.
app.client.waitUntilWindowLoaded(10000)
Focus a window using its index from the windowHandles()
array.
app.client.windowByIndex(1)
You will want to add the following to your .travis.yml
file when building on
Linux:
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 appveyor.yml
file:
os: unstable
Check out Spectron's appveyor.yml file for a production example.
WebdriverIO is promise-based and so it pairs really well with the Chai as Promised library that builds on top of Chai.
Using these together allows you to chain assertions together and have fewer callback blocks. See below for a simple example:
npm install --save-dev chai
npm install --save-dev chai-as-promised
var Application = require('spectron').Application
var chai = require('chai')
var chaiAsPromised = require('chai-as-promised')
var path = require('path')
chai.should()
chai.use(chaiAsPromised)
describe('application launch', function () {
beforeEach(function () {
this.app = new Application({
path: '/Applications/MyApp.app/Contents/MacOS/MyApp'
})
return this.app.start()
})
beforeEach(function () {
chaiAsPromised.transferPromiseness = this.app.transferPromiseness
})
afterEach(function () {
if (this.app && this.app.isRunning()) {
return this.app.stop()
}
})
it('opens a window', function () {
return this.app.client.waitUntilWindowLoaded()
.getWindowCount().should.eventually.equal(1)
.browserWindow.isMinimized().should.eventually.be.false
.browserWindow.isDevToolsOpened().should.eventually.be.false
.browserWindow.isVisible().should.eventually.be.true
.browserWindow.isFocused().should.eventually.be.true
.browserWindow.getBounds().should.eventually.have.property('width').and.be.above(0)
.browserWindow.getBounds().should.eventually.have.property('height').and.be.above(0)
})
})
Spectron works with AVA which allows you to write your tests in ES2015 without extra support.
'use strict';
import test from 'ava';
import {Application} from 'spectron';
test.beforeEach(t => {
t.context.app = new Application({
path: '/Applications/MyApp.app/Contents/MacOS/MyApp'
});
return t.context.app.start();
});
test.afterEach(t => {
return t.context.app.stop();
});
test(t => {
return t.context.app.client.waitUntilWindowLoaded()
.getWindowCount().then(count => {
t.is(count, 1);
}).browserWindow.isMinimized().then(min => {
t.false(min);
}).browserWindow.isDevToolsOpened().then(opened => {
t.false(opened);
}).browserWindow.isVisible().then(visible => {
t.true(visible);
}).browserWindow.isFocused().then(focused => {
t.true(focused);
}).browserWindow.getBounds().then(bounds => {
t.ok(bounds.width > 0);
t.ok(bounds.height > 0);
});
});
AVA supports ECMAScript advanced features not only promise but also async/await.
test(async t => {
await t.context.app.client.waitUntilWindowLoaded();
t.is(1, await app.client.getWindowCount());
t.false(await app.browserWindow.isMinimized());
t.false(await app.browserWindow.isDevToolsOpened());
t.true(await app.browserWindow.isVisible());
t.true(await app.browserWindow.isFocused());
t.ok((await app.browserWindow.getBounds()).width > 0);
t.ok((await app.browserWindow.getBounds()).height > 0);
});