electronmocha.jsspectron

How do I use Mocha to test my custom module that requires Node API? "Cannot read property 'require' of undefined"


I'm building an Electron app. I'm setting up testing with Mocha and Spectron. Mocha is erroring on the line

const filebrowser = require("../src/filebrowser.js")

specifically, it's failing in the filebrowser module on line 2 when I try to require node's fs module:

const {remote} = require('electron');
const fs = remote.require('fs');

I imagine this has something to do with the Main process/Renderer process scope in Electron but I don't understand how to make it work properly with Mocha. How do I properly require my modules in a Mocha test file when they rely on a Node api that I normally access through electron's remote module?

test/test.js (this is the spectron example code from their github page). I run it with the "mocha" command through a package.json script (npm test). Note that I haven't even written a test yet for my filebrowser module, it is failing on the require statement.

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 filebrowser = require("../src/filebrowser.js")

describe('Application launch', function () {
  this.timeout(10000)

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

      // use the main.js file in package.json located 1 level above.
      args: [path.join(__dirname, '..')]
    })

    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)
    })
  })
})

src/filebrowser.js

const {remote} = require('electron');
const fs = remote.require('fs');
const Path = require('path');

module.exports = {        
    //note that I would be calling fs functions in here, but I never get that far because the error happens on remote.require('fs')
    determineFiletype: function(currentDirectory, fileName){}
}


Solution

  • After more research, it seems that Spectron is not able to do this. Spectron starts up in a Webdriver process rather than in the main process of your electron app. This works for end to end testing but not for normal module testing. Luckily, the electron-mocha module works great for module testing. It lets you specify which process to run tests from, and any modules to include in the main process. Best of all it runs in Chromium so you can access all APIs of your app like normal.