Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguro

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
012345678901234567890123456789012345678901234567890123456789
Ayer
012345678901234567890123456789012345678901234567890123456789
Vistas totales
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de Electron
Electron
Getting Started with ElectronProject StructureCore ConceptsData and StateTestingDeployment
Debates

Guía de Electron · 5/6

Testing

Por ahora, este capítulo solo está disponible en inglés.

An Electron app has a main process, preload scripts, and renderers working together, so no single kind of test covers everything. This chapter shows how to unit test logic that does not depend on Electron, and how to write end-to-end (E2E) tests with Playwright that launch the real app and drive its windows.

A testing strategy

KindTargetTools
Unit testsPure functions, data transforms, validationVitest, Jest
Module testsMain process code that calls Electron APIsVitest with a mocked electron
Renderer component testsReact or Vue componentsYour UI framework's testing tools
E2E testsThe whole running appPlaywright, WebdriverIO

The first step toward a testable app is to separate business logic from Electron APIs. Rather than writing long logic inside IPC handlers, extract it into pure functions and have the handlers simply call them.

Unit testing pure logic

Take a function that maintains a recent-files list. It knows nothing about Electron, so plain Node.js tests can check it.

// src/lib/recent-files.js
export function addRecentFile(list, file, max = 10) {
  return [file, ...list.filter((item) => item !== file)].slice(0, max)
}
npm install --save-dev vitest
npx vitest
// tests/recent-files.test.js
import { describe, it, expect } from 'vitest'
import { addRecentFile } from '../src/lib/recent-files'

describe('addRecentFile', () => {
  it('puts a new file first', () => {
    expect(addRecentFile(['a.txt'], 'b.txt')).toEqual(['b.txt', 'a.txt'])
  })

  it('moves an existing file to the front', () => {
    expect(addRecentFile(['a.txt', 'b.txt'], 'b.txt')).toEqual(['b.txt', 'a.txt'])
  })

  it('never exceeds the maximum length', () => {
    expect(addRecentFile(['a', 'b', 'c'], 'd', 3)).toEqual(['d', 'a', 'b'])
  })
})

Mocking the electron module

In plain Node.js, require('electron') returns the path to the Electron executable as a string, not the API. To load main process code in a Node.js test runner, replace the electron module with a mock.

// src/main/settings-path.js
import { app } from 'electron'
import path from 'node:path'

export const settingsPath = () => path.join(app.getPath('userData'), 'settings.json')
// tests/settings-path.test.ts
import { vi, it, expect } from 'vitest'
import path from 'node:path'

vi.mock('electron', () => ({
  app: { getPath: vi.fn(() => '/tmp/test-user-data') },
}))

import { settingsPath } from '../src/main/settings-path'

it('points at settings.json under userData', () => {
  expect(settingsPath()).toBe(path.join('/tmp/test-user-data', 'settings.json'))
})
¿Tienes preguntas sobre este capítulo?
Capítulo anteriorData and StateCapítulo siguienteDeployment

vi.mock is hoisted to the top of the file, so it takes effect before the imports below it. Note that Vitest mocks apply to modules that Vitest itself transforms and loads, not to CommonJS modules that Node.js loads directly through require. That is why the main process code above uses ES module syntax, which comes naturally in projects that bundle the main process, such as the Forge Vite and webpack templates.

End-to-end tests with Playwright

Playwright has experimental support for launching and controlling Electron apps. _electron.launch() starts your app and returns an ElectronApplication; from it you get windows as regular Page objects and drive them like any web test. evaluate() runs code inside the main process.

npm install --save-dev @playwright/test
npx playwright test
// tests/app.spec.ts
import { test, expect, _electron as electron } from '@playwright/test'

test('opens the main window', async () => {
  const electronApp = await electron.launch({ args: ['main.js'] })

  // Runs in the main process
  const isPackaged = await electronApp.evaluate(async ({ app }) => app.isPackaged)
  expect(isPackaged).toBe(false)

  const window = await electronApp.firstWindow()
  await expect(window).toHaveTitle('Hello Electron')
  await expect(window.locator('h1')).toHaveText('Hello from Electron')

  await electronApp.close()
})

Native dialogs cannot be automated, so swap out the dialog functions in the main process from inside the test.

test('opens a file', async () => {
  const electronApp = await electron.launch({ args: ['main.js'] })
  await electronApp.evaluate(({ dialog }, filePath) => {
    dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [filePath] })
  }, '/tmp/sample.txt')

  const window = await electronApp.firstWindow()
  await window.getByRole('button', { name: 'Open' }).click()
  await expect(window.locator('#file')).toHaveText('/tmp/sample.txt')
  await electronApp.close()
})

To test a packaged build, pass the path of the built executable as electron.launch({ executablePath: '...' }).

Running in CI

Linux CI machines have no display, so Electron windows need a virtual one.

# Ubuntu example
sudo apt-get install -y xvfb
xvfb-run --auto-servernum npx playwright test

WebdriverIO also supports Electron E2E testing through its Electron service (wdio-electron-service). Spectron, which older guides mention, is no longer maintained and should not be used for new projects.

Summary

  • Pull business logic out of Electron APIs into pure functions and unit test them with Vitest or Jest.
  • Mock the electron module when loading main process code in a Node.js test runner.
  • Use Playwright's _electron.launch() to start the real app, drive its windows, and inspect the main process with evaluate().
  • Provide a virtual display with xvfb-run on Linux CI.

0 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.