4

I'm testing library code for an Electron app with Jest. Jest does weird things to require, which is interfering with that Electron needs to do... I think.

Spectron is meant to allow you to access the various Electron bits from within a test framework, by allowing you to create an Electron app via library calls.

Ultimately, I need to be able to mock require('electron') with some real stuff from Electron (like the creation of browser windows), mostly so that various library bits can work as intended.

Here's what it looks like should work:

in package.json:

  "jest": {
    "moduleNameMapper": {
      "^electron$": "<rootDir>/test/mocks/electron.js"
    }
  }

test/mocks/electron.js:

const Path = require("path")
const Application = require('spectron').Application
const electronPath = Path.join(__dirname, "../../node_modules/electron/dist/Electron.app/Contents/MacOS/Electron")
const app = new Application({ path: electronPath })
module.exports = app.electron

According to the docs, app.electron should give access to the same things as require('electron') does under normal operation.

Some test:

const { BrowserWindow } = require("electron")
test("some test", () => {
  const window = new BrowserWindow()
  // ...
})

However, this fails because app.electron is undefined, although App itself is defined:

    console.log test/mocks/electron.js:58
  <ref *1> Application {
    host: '127.0.0.1',
    port: 9515,
    quitTimeout: 1000,
    startTimeout: 5000,
    waitTimeout: 5000,
    connectionRetryCount: 10,
    connectionRetryTimeout: 30000,
    nodePath: '~/.nvm/versions/node/v13.0.1/bin/node',
    path: '~/electron-hello-world/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron',
    args: [],
    chromeDriverArgs: [],
    env: {},
    workingDirectory: '~/electron-hello-world',
    debuggerAddress: undefined,
    chromeDriverLogPath: undefined,
    webdriverLogPath: undefined,
    webdriverOptions: {},
    requireName: 'require',
    api: Api { app: [Circular *1], requireName: 'require' },
    transferPromiseness: [Function (anonymous)]
  }

Not really sure where to go from here. Looking for any solutions

Narfanator
  • 4,951
  • 3
  • 32
  • 57

0 Answers0