1

How can we assert that a javascript-variable embedded in HTML has some expected value within an application built with electron? The current testing framework is spectron, mocha, chai, chai.should(), and chai.use(chaiAsPromised).

I want to assert that the global variable foo has the value 'foo'. When I try foo.should.equal('foo') I get ReferenceError: foo is not defined at Context.<anonymous> (test\spec.js:63:28)

Below is a reworked spec.js.

const Application = require('spectron').Application
const assert = require('assert')
const electronPath = require('electron') // Require Electron from the binaries included in node_modules.
const path = require('path')
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const should = require('chai').should();

describe('Isolated testbeds house independent suites of tests.', function() {
  this.timeout(30000);

  before(function() {
    this.app = new Application({
      path: electronPath,

      // directory structure:

      //  |__ myProject
      //     |__ ...
      //     |__ main.js
      //     |__ package.json
      //     |__ index.html
      //     |__ ...
      //     |__ test
      //        |__ spec.js  <- You are here! ~ Well you should be.

      args: [path.join(__dirname, '..')]
    })
    return this.app.start()
  });

  after(function() {
    if (this.app && this.app.isRunning()) {
      return this.app.stop()
    }
  });

/* BELOW IS THE TEST IN QUESTION */
  it('should have a given value', function() {
    return Promise.resolve(foo).should.eventually.equal('foo'); // HERE IS THE LINE IN QUESTION
  });

})

1 Answers1

2

Spectron is "remote-controlling" your Electron app, and is not in the same namespace. That is why foo is not defined in your test script.

If foo is in your Electron front-end, you can access it using this.app.client if it is in the DOM. this.app.browserWindow or this.app.webContents might be able to access globals?

(I do know that executeJavaScript() won't work - any function that returns a promise, won't work, basically.)

If foo is on your back-end, I show a workaround in my question: Can Spectron call a function in back-end directly? (but I am still hunting for an approach that doesn't require me to modify the code to test)

Darren Cook
  • 27,837
  • 13
  • 117
  • 217