Developing Apps with Electron and Spectron (Part 2): The First Test

In part one we installed Electron and Spectron and scaffolded a simple project.

Now, let’s write a simple test that will check that the app is running and that the main app window is visible.

Sample Test

In your test folder create a file called sample-test.js.

Open this file and require the Spectron library and Node’s assertion library:

var Application = require('spectron').Application
var assert = require('assert')

Instantiate the Electron application and pass it the path to the electron executable and the path to your app’s entry point:

var app = new Application({
    path: __dirname + '/../node_modules/.bin/electron',
    args: [
        __dirname + '/../main.js'
    ]
})

Now call the function starts the app:

app.start()

This function returns a promise, and this means that we can chain another function to it and then execute that function only after the app has finished initialising.

So, a simple test that starts the app, checks that the app is running and then checks that the app window is visible would look like this:

app.start().then(function () {
    assert.equal(app.isRunning(), true)
    return app.browserWindow.isVisible()
}).then(function (isVisible) {
    assert.equal(isVisible, true)
})

Once we have finished testing the application, it should be stopped by adding:

.then(function () {
    return app.stop()
})

And then finally, catch any errors that have been thrown (ie. the assertions that have failed):

.catch(function (error) {
    console.error('Test failed', error.message)
})

If you have been following along, your full test should look like this:

var Application = require('spectron').Application
var assert = require('assert')

app.start().then(function () {
    assert.equal(app.isRunning(), true)
    return app.browserWindow.isVisible()
}).then(function (isVisible) {
    assert.equal(isVisible, true)
}).then(funtion () {
    return app.stop()
}).catch(function (error) {
    console.error('Test failed', error.message)
})

Running the test

You should now be able to run this test from the root of your application using:

node test/sample-test.js

What Next?

At this point, the terminal should just hang because we have not yet created an Electron app (cancel with ctrl-c).

That will, of course, be the subject of the next post.