Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 36 ยท Testing and Performance

Testing Electron Apps: Unit, Integration and End-to-end

Build a test strategy for Electron: keep logic in plain modules, unit test with node:test, fake the electron module, test IPC handlers, and run end-to-end tests with Playwright.

Electron apps are awkward to test for one reason: much of the code needs a running Electron to do anything. BrowserWindow, dialog and app do not exist in a plain Node process. The trick is not to fight that, but to arrange the code so most of it never needs Electron, and cover the remaining thin layer with a few end-to-end tests that launch the real app.

This lesson shows the test pyramid for Electron, the architecture that makes it possible, how to fake the electron module and how to drive the real app with Playwright.

The test pyramid

flowchart TD
  A["End-to-end: a few tests, real app, real windows (Playwright)"] --> B["Integration: IPC handlers with a fake electron module"]
  B --> C["Unit: many tests, pure functions and classes, plain Node"]

Most tests live at the bottom: fast, no Electron needed.

Keep business logic in plain modules: the settings store, note parsing, validators, path confinement, update-version comparison. These functions receive their inputs as arguments and return values. The Electron-specific files (main.js, preload.js) become thin glue that wires them together.

Unit tests with node:test

Node's built-in runner is enough, with no extra dependency. Suppose notes.js holds a pure function:

JavaScript
// src/notes.js
export function wordCount(text) {
  return text.trim() === '' ? 0 : text.trim().split(/\s+/).length;
}
JavaScript
// test/notes.test.js
import test from 'node:test';
import assert from 'node:assert/strict';
import { wordCount } from '../src/notes.js';

test('counts words', () => {
  assert.equal(wordCount('one two  three'), 3);
});

Run with node --test. Vitest and Jest are equally fine; the point is that these tests run in milliseconds in CI without a display.

Node.js Unit testing a pure module with node:test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last line fails on purpose so you can read what a failing assertion looks like. In a real project node --test prints the full diff.

Faking the electron module

Handlers in main.js call ipcMain.handle, dialog.showOpenDialog and friends. To test a handler without Electron, make it a factory that receives its dependencies:

JavaScript
// src/handlers.js
export function createHandlers({ dialog, fs, settings }) {
  return {
    async openFile(event) {
      const { canceled, filePaths } = await dialog.showOpenDialog({ properties: ['openFile'] });
      if (canceled) return null;
      const text = await fs.readFile(filePaths[0], 'utf8');
      settings.addRecent(filePaths[0]);
      return { path: filePaths[0], text };
    },
  };
}
JavaScript
// main.js
import { dialog, ipcMain } from 'electron';
import fs from 'node:fs/promises';
const handlers = createHandlers({ dialog, fs, settings });
ipcMain.handle('file:open', handlers.openFile);

This is dependency injection in its simplest form: no framework, just an argument. In the test you pass fakes. The next example does exactly that, including a spy that records which calls happened.

Node.js Testing a handler with fake dependencies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If you cannot restructure, tools like vi.mock('electron') (Vitest) or jest.mock('electron') replace the module wholesale. Injection is simpler and survives refactors better.

Testing the renderer

The renderer is ordinary web code. Test its components with Vitest plus jsdom or Testing Library like any web app, with window.api replaced by a stub that records calls:

JavaScript
window.api = { saveNote: vi.fn().mockResolvedValue({ ok: true }) };

Because the preload exposes a small named API (Security Checklist), that stub is small too.

End-to-end with Playwright

Unit tests cannot tell you whether the window opens, the preload loads, or the menu works. For that, launch the real app. Playwright has first-class Electron support:

JavaScript
// e2e/app.spec.js
import { test, expect, _electron as electron } from '@playwright/test';

test('creates and saves a note', async () => {
  const app = await electron.launch({ args: ['.'], env: { ...process.env, NODE_ENV: 'test' } });
  const window = await app.firstWindow();

  await window.getByRole('button', { name: 'New note' }).click();
  await window.getByLabel('Title').fill('Shopping');
  await window.getByLabel('Body').fill('milk, bread');
  await window.getByRole('button', { name: 'Save' }).click();

  await expect(window.getByText('Saved')).toBeVisible();

  const title = await window.title();
  expect(title).toContain('Shopping');

  // Run code in the main process
  const version = await app.evaluate(({ app }) => app.getVersion());
  expect(version).toMatch(/^\d+\.\d+\.\d+/);

  await app.close();
});

Guidelines that keep E2E tests reliable:

  • Isolate state. Start the app with a temporary userData (an env var your main.js honours when NODE_ENV === 'test') so tests do not share settings.
  • Avoid native dialogs. They are outside the web page, so Playwright cannot click them. Let main.js read a path from an env var in test mode, or stub dialog.showOpenDialog with app.evaluate.
  • Use role and label selectors, not CSS classes. They match what users and assistive technology see.
  • Run on a virtual display in Linux CI (xvfb-run npm run test:e2e).
  • Keep the suite small: sign in, create, save, quit-and-relaunch persistence. Everything else belongs lower in the pyramid.

Test the packaged app too

Dev mode and the packaged app differ (ASAR paths, fuses, missing devDependencies). A final smoke test on the output of npm run package catches errors that appear only there. Point Playwright at the executable:

JavaScript
const app = await electron.launch({ executablePath: './out/Notes Studio-linux-x64/notes-studio' });

A tiny test harness for async IPC

When a handler talks to a store with timing, you often want to assert the order of calls. This example records events in order with fake timers and checks that a debounced save fires once.

Node.js Asserting call order and debouncing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why keep logic in plain modules instead of main.js?

    Pure modules need no BrowserWindow or app. They are fast to test, and main.js becomes thin wiring.
  2. 2. What is the simplest way to test an IPC handler that uses dialog and fs?

    Dependency injection lets a test hand in fakes and assert on results and calls, with no Electron process.
  3. 3. Which tool drives a real Electron app for end-to-end tests?

    Playwright's Electron support launches the app, gives you its windows as pages, and lets you evaluate code in the main process.
  4. 4. Why should E2E tests use a temporary userData folder?

    Isolation keeps tests independent and repeatable, and keeps them from touching the developer's real data.

Summary

  • Shape the code as a pyramid: many plain-Node unit tests, some handler tests with fakes, few real-app E2E tests.
  • Inject dialog, fs and settings into handler factories; no mocking library needed.
  • Test renderer code like any web app with a stubbed window.api.
  • Use Playwright's Electron API with isolated state and role-based selectors; avoid native dialogs.
  • Smoke-test the packaged build as well as the dev build.

Next: Startup Performance