Aller au contenu principal
ProduitsOutils de bureauTASTECADConsultation de plansTASTEFILESGestion de fichiersTASTEFTPTransfert de fichiersTASTESSHEspace de travail à distanceTASTEZIPCompression et extractionOutils pour développeursTASTECODEEnvironnement de développement intégré pour RustTASTESTUDIOEnvironnement intégré de développement et de testTASTEETLIntégration de données (ETL)ServeursTASTEREMOTEServeur de bureau à distanceTASTEGEOServeur géospatialTASTEMAILEspace de travail e-mailCommencerTéléchargementsDocumentationAcheterTous les produits
Marketplace
Actualités
TechActualitésL’actu dev du jourDocs développeursLangages de programmationRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks front-end webNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks serveurSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks d'applications et de bureauTauriFlutterReact NativeElectronAlgorithmesBases des algorithmesAlgorithmes essentielsAlgorithmes avancésAlgorithmes pratiques
CommunautéProjetsJournaux de développementPromptsProblèmes d’outils d’IAVitrineGuide de la communauté
CollaborerTransfert techniqueRéalisation de site webRéalisation d'application de bureauChaîne de publication et de paiementPartenaire commercialContact
ServicesBureau à distancePaquets d'installation sur mesure
TASTEDEV
Produits

Outils de bureau

TASTECADDes plans complexes, ouverts en toute légèretéTASTEFILESSeulement les fichiers utiles, au plus viteTASTEFTPLe chemin le plus net pour vos fichiersTASTESSHEntre vos serveurs et vous, un lien plus solideTASTEZIPCompresser plus vite, extraire en toute sécurité

Outils pour développeurs

TASTECODEModifier, compiler, déboguer et tester vos apps Rust dans une seule fenêtreTASTESTUDIODe l’édition aux tests à distance et aux corrections IA approuvéesTASTEETLDéplacer les données, les valeurs sous les yeux

Serveurs

TASTEREMOTEUn bureau à distance hébergé sur votre propre serveurTASTEGEOUn serveur géospatial compatible GeoServer, reconstruit en RustTASTEMAILReprenez la maîtrise de vos e-mails

Commencer

TéléchargementsDernières versions de chaque produitDocsUtiliser chaque produitAcheterAbonnements et licences perpétuellesTous les produitsTous les produits en un coup d’œil
Tous les produits
MarketplaceActualités
Tech

Actualités

L’actu dev du jourAnnonces officielles : langages, frameworks, GitHub et IADocs développeursGuides des langages, frameworks et algorithmes

Langages de programmation

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks front-end webNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks serveurSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks d'applications et de bureauTauriFlutterReact NativeElectron

Algorithmes

Bases des algorithmesAnalyse de complexité · Tri · Recherche · Structures de données de base · Arbres et tasAlgorithmes essentielsParcours de graphe · Plus courts chemins et arbres couvrants · Programmation dynamique · Algorithmes gloutons · Diviser pour régner · Backtracking (retour sur trace)Algorithmes avancésAlgorithmes sur les chaînes · Mathématiques et théorie des nombres · Manipulation de bits · Arbres de segments · Union-FindAlgorithmes pratiquesStratégie pour les entretiens de codage · Cache LRU · Limitation de débit · Hachage cohérent
Toute la documentation de développement
Communauté
ProjetsDécouvrir les créateurs et leurs travauxJournaux de développementDécisions et enseignementsPromptsInstructions réutilisablesProblèmes d’outils d’IAProblèmes et contournements de Claude, Codex, GeminiVitrineRéalisations terminéesGuide de la communautéConstruire en toute transparence
Collaborer
Transfert techniqueApplications natives en Rust et eguiRéalisation de site web10 langues, comptes, documentation et téléchargementsRéalisation d'application de bureauRust et egui, sans WebViewChaîne de publication et de paiementSignature, MSI, deb, rpm, AppImage, empreintesPartenaire commercialRecommandez-nous, touchez 30 %ContactDéveloppement, partenariats, investissement
Services
Bureau à distanceAccédez à votre ordinateur depuis le navigateurPaquets d'installation sur mesureSeulement l'utile, réglages préchargés
Acheter
FR
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Se connecter
Se connecter
TASTEDEV

Des petits outils à un meilleur développement.

support@tastedev.netSoutenir TASTEDEV
ProduitsGamme de produitsAcheterDocsTéléchargementsMarketplaceAssistance
CommunautéProjetsJournaux de développementPromptsProblèmes d’outils d’IAVitrine
RèglesPolitique de confidentialitéConditions d'utilisationConditions d’abonnementRemboursementRègles de la communauté
CompteSe connecterS'inscrire
Visiteurs
Aujourd’hui
012345678901234567890123456789012345678901234567890123456789
Hier
012345678901234567890123456789012345678901234567890123456789
Vues au total
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
Société
GXSOFT
Représentant
CHOI YOUNG GU
Numéro d’enregistrement
853-44-00368
Adresse
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Téléphone
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsable de la confidentialité
CHOI YOUNG GU

© 2026 TASTEDEVLes informations produit s'appuient sur des sources de développement vérifiées.Publié · en amélioration

Documentation Electron
Electron
Getting Started with ElectronProject StructureCore ConceptsData and StateTestingDeployment
Discussions

Guide Electron · 5/6

Testing

Ce chapitre n'est disponible qu'en anglais pour le moment.

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'))
})
Des questions sur ce chapitre ?
Chapitre précédentData and StateChapitre suivantDeployment

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 commentaire

Meilleurs commentairesPlus récents d'abord

Se connecter · Connectez-vous pour laisser un commentaire.