Electron模拟工厂 electron-mock-factory

Electron 模拟工厂是一个用于为 Electron 桌面应用框架的 API 生成模拟对象的工具。它主要用于前端开发和测试领域,帮助开发者在无需启动完整 Electron 环境的情况下,对应用的主进程和渲染器进程代码进行高效的单元测试。关键词:Electron 模拟,单元测试,前端测试,Jest,Vitest,Mock,桌面应用测试。

测试 0 次安装 0 次浏览 更新于 2/25/2026

名称: electron-mock-factory 描述: 为 Electron API(ipcMain、ipcRenderer、dialog 等)生成模拟对象,用于单元测试 允许使用的工具: Read, Write, Edit, Bash, Glob, Grep 标签: [electron, 测试, 模拟, 单元测试, jest]

electron-mock-factory

为 Electron API 生成模拟对象,使得无需运行 Electron 即可对主进程和渲染器进程的代码进行单元测试。

功能

  • 模拟 ipcMain/ipcRenderer
  • 模拟 dialog 模块
  • 模拟 BrowserWindow
  • 模拟 shell、clipboard、app
  • 生成 Jest/Vitest 模拟对象
  • 创建测试工具

输入模式

{
  "type": "object",
  "properties": {
    "projectPath": { "type": "string" },
    "testFramework": { "enum": ["jest", "vitest", "mocha"] },
    "modulesToMock": { "type": "array" }
  },
  "required": ["projectPath"]
}

生成的模拟对象

// __mocks__/electron.js
module.exports = {
  app: {
    getPath: jest.fn(name => `/mock/${name}`),
    getVersion: jest.fn(() => '1.0.0'),
    quit: jest.fn(),
    on: jest.fn()
  },
  ipcMain: {
    on: jest.fn(),
    handle: jest.fn(),
    removeHandler: jest.fn()
  },
  ipcRenderer: {
    on: jest.fn(),
    send: jest.fn(),
    invoke: jest.fn()
  },
  dialog: {
    showOpenDialog: jest.fn(() => Promise.resolve({ filePaths: [] })),
    showSaveDialog: jest.fn(() => Promise.resolve({ filePath: undefined })),
    showMessageBox: jest.fn(() => Promise.resolve({ response: 0 }))
  },
  BrowserWindow: jest.fn().mockImplementation(() => ({
    loadURL: jest.fn(),
    on: jest.fn(),
    webContents: { send: jest.fn(), on: jest.fn() }
  }))
};

使用方法

jest.mock('electron');
const { ipcRenderer } = require('electron');

test('发送消息', () => {
  myModule.sendMessage('hello');
  expect(ipcRenderer.send).toHaveBeenCalledWith('channel', 'hello');
});

相关技能

  • playwright-electron-config
  • desktop-unit-testing 流程