app.browserWindow returns TypeError during testing of electron app with Spectron

Viewed 293

I am trying to run simple tests on my electron application using Spectron and mocha. However, whenever I try to use the browserWindow API I obtain an error of the form:

TypeError: Cannot read property '.....' of undefined

I did a bit of research on the internet. Some proposed solutions I found were to ensure nodeIntegration is set to true, and that DevTools is not open on the application window. I have ensured that both these criteria are satisfied, but I am still receiving the same error. What am I missing here? I am attaching my code for reference.

main.js

const {app, BrowserWindow} = require('electron')
const path = require('path')
let mainWindow

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'), 
      nodeIntegration:true
    }
  })

  mainWindow.loadFile('index.html')

}

app.whenReady().then(() => {
  createWindow()
  
  app.on('activate', function () {

    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

test.js

const Application = require('spectron').Application
const assert = require('assert')
const electronPath = require('electron') 
const path = require('path')
const { app } = require('electron')
const { expect } = require('chai')

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

  before(function () {
    this.app = new Application({
      path: electronPath,
      args: [path.join(__dirname, '.')]
    })
    return this.app.start()
  })

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

  it('should be a focused window', function(){
    return this.app.client.waitUntilWindowLoaded().browserWindow.isFocused().then(res => {
      expect(res).to.be.true
    })
  })
})

The issue arises at the line this.app.client.waitUntilWindowLoaded().browserWindow.isFocused()

0 Answers
Related