You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron+Spectron测试启动报错:waitUntilWindowLoaded及require未定义

解决Electron + Spectron测试中的两个核心问题

看起来你碰到了两个典型的Electron测试相关问题,我来帮你一步步拆解修复:

问题1:TypeError: Cannot read property 'waitUntilWindowLoaded' of undefined

这个错误的核心原因是测试钩子中的异步操作没有正确等待。你在before函数里直接调用了app.start(),但它是一个返回Promise的异步方法——Mocha不会自动等待这个异步操作完成,就直接执行后面的测试用例了。这时候应用还没初始化好,app.client自然是undefined,调用它的方法肯定会报错。

修复方法

给before和after钩子加上async/await,确保应用完全启动后再跑测试,也确保应用能正确停止:

before(async function () {
  await app.start()
})

after(async function () {
  if (app && app.isRunning()) {
    await app.stop()
  }
})

问题2:Uncaught ReferenceError: require is not defined

这个错误是因为Electron 5及以上版本默认在渲染进程中禁用了Node.js集成。你的view.js里用require('jquery')调用Node模块,但渲染进程默认没有权限访问Node的require方法,所以会抛出这个错误。

修复方法

在创建BrowserWindow的时候,显式开启nodeIntegration选项;如果你的Electron版本是12+,还需要关闭contextIsolation(默认开启的上下文隔离会阻止渲染进程直接访问Node API):

function createWindow() {
  win = new BrowserWindow({
    width: 800, 
    height: 600,
    webPreferences: {
      nodeIntegration: true, // 开启Node.js集成
      contextIsolation: false // Electron 12+ 必须添加这一行
    }
  })
  // 其他代码不变
}

完整修复后的核心代码片段

测试文件(./test/index.js)

const assert = require('assert')
const path = require('path')
const { Application } = require('spectron')
const electronPath = require('electron')
const baseDir = path.join(__dirname, '..')

describe('Application launch', function () {
  this.timeout(30000)
  const app = new Application({
    path: electronPath,
    args: [baseDir]
  })

  before(async function () {
    await app.start()
  })

  after(async function () {
    if (app && app.isRunning()) {
      await app.stop()
    }
  })

  it('show an initial window', async function () {
    await app.client.waitUntilWindowLoaded();
    const count = await app.client.getWindowCount();
    assert.equal(count, 1)
  })

  // 额外给你加个点击按钮的测试用例,符合你的需求
  it('should increment counter when button is clicked', async function () {
    await app.client.waitUntilWindowLoaded();
    // 获取初始计数
    let initialCount = await app.client.getText('#click-counter');
    assert.equal(initialCount, '0');
    
    // 点击按钮
    await app.client.click('#countbtn');
    
    // 获取更新后的计数
    let updatedCount = await app.client.getText('#click-counter');
    assert.equal(updatedCount, '1');
  })
})

main.js

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

function createWindow() {
  win = new BrowserWindow({
    width: 800, 
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })

  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  win.webContents.openDevTools();
}

app.on('ready', createWindow)

额外小提示

  1. 先手动启动应用确认能正常运行(修复require错误后),再跑测试会更顺利
  2. 你的依赖版本是兼容的:Spectron 9.x对应Electron 7.x,不用调整版本
  3. 如果还是碰到超时问题,可以适当延长Mocha的超时时间,比如改成this.timeout(40000)

内容的提问来源于stack exchange,提问作者wallage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:03:09