Testing Your Desktop Application
8 min read
Building an Electron application means you are essentially managing two different worlds at once: a Node.js backend (the Main Process) and a Chromium frontend (the Renderer Process). Ensuring both worlds communicate correctly and handle edge cases without crashing requires a solid testing strategy.
In this guide, we will break down exactly how to test, mock, and debug your application using modern industry standards.
1. Unit Testing Main Process Logic 🧱
Definition: Unit testing is the practice of testing small, isolated pieces of code (functions, classes, or modules) to ensure they function exactly as intended, entirely independent of the rest of the application.
Problem: Your Electron Main Process manages native operating system interactions, window creation, and the application lifecycle. If you try to test this logic by launching the entire application every single time, your tests will be painfully slow. Worse, they will randomly fail (a phenomenon known as "flakiness") because they depend on UI rendering times and background OS tasks.
Solution: Run your tests in a pure, lightweight Node.js environment using a test runner like Vitest or Jest, and replace (mock) the native Electron modules. This ensures the test checks your logic without actually opening physical windows on your screen.
Imagine you are running a pizza shop (your application). Unit testing the Main Process is like testing the chef's ability to knead dough in an isolated back room. You do not need to unlock the front doors, seat customers, and wait for them to order just to check if the dough recipe works. You just test the dough.
Hands-on Practice
Industry standard currently favors Vitest for its blazing-fast speed and native TypeScript support. Let's look at how to test a file named windowManager.js that relies on the electron module.
First, install the testing framework:
npm install -D vitestAssume we have a simple function in windowManager.js that creates a window:
// windowManager.js
const { BrowserWindow } = require('electron');
function createMainWindow() {
const win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL('https://freecodecamp.org');
return win;
}
module.exports = { createMainWindow };To test this without firing up a real Chromium window, we intercept the electron import and provide a "fake" mock version:
// windowManager.test.js
import { describe, it, expect, vi } from 'vitest';
import { createMainWindow } from './windowManager';
// 1. We mock the entire 'electron' module before the test runs
vi.mock('electron', () => {
return {
// Return a fake class with a mock loadURL method
BrowserWindow: vi.fn().mockImplementation(() => ({
loadURL: vi.fn(),
})),
};
});
// Import the mocked module to assert against it
import { BrowserWindow } from 'electron';
describe('Window Manager', () => {
it('should create a window with correct dimensions', () => {
const win = createMainWindow();
// 2. Assert that our code called the Electron API correctly
expect(BrowserWindow).toHaveBeenCalledWith({ width: 800, height: 600 });
expect(win.loadURL).toHaveBeenCalledWith('https://freecodecamp.org');
});
});Note: Under the hood, Vitest intercepts the Node module resolution. When windowManager.js asks for electron, Vitest hands it our fake object instead of the real binary.
2. End-to-End Testing with Playwright 🎭
Definition: End-to-End (E2E) testing validates the entire software stack from start to finish by programmatically controlling the application exactly as a real user would.
Problem: Unit tests guarantee that individual pieces work, but they do not guarantee that the pieces fit together. Your UI button might work perfectly in a unit test, but if the bridge connecting it to the Main Process is broken, the app fails when a user clicks it.
Solution: Automate your actual, compiled Electron application using Playwright. Playwright connects directly to Electron's Chromium runtime via the Chrome DevTools Protocol (CDP), allowing you to click buttons, read text, and take screenshots as if a ghost were using your computer.
Hands-on Practice
While you can use WebdriverIO, Playwright's experimental Electron support is currently the darling of the industry due to its modern API and speed.
Install Playwright:
npm install --save-dev @playwright/testHere is how you write an E2E test to launch your app and verify the UI:
// app.spec.js
import { test, expect, _electron as electron } from '@playwright/test';
import path from 'path';
test.describe('Electron Application E2E', () => {
let electronApp;
let window;
test.beforeAll(async () => {
// 1. Launch the Electron app directly
// The '.' argument tells Electron to look at the current directory's package.json main entry
electronApp = await electron.launch({ args: ['.'] });
// 2. Wait for the first BrowserWindow to open
window = await electronApp.firstWindow();
});
test.afterAll(async () => {
// Clean up after tests finish
await electronApp.close();
});
test('should render the main page and click a button', async () => {
// 3. Interact with the DOM exactly like a web app
const title = await window.title();
expect(title).toBe('My Electron App');
// Click a button and verify a state change
await window.locator('#submit-btn').click();
await expect(window.locator('#success-message')).toBeVisible();
});
});To run the test, use: npx playwright test. Playwright will literally open your desktop app, click around at superhuman speeds, and close it.
3. Mocking IPC Calls for Reliable Automated Tests 📯
Definition: Mocking Inter-Process Communication (IPC) involves replacing the asynchronous messaging channels between the Main and Renderer processes with predictable, synchronous fake responses during frontend testing.
Problem: When you test your frontend UI components (like a React or Vue component) in isolation, the Main Process does not exist. If your component renders and immediately calls window.electronAPI.getUserSettings(), the test environment will crash because window.electronAPI is undefined in a pure web testing environment.
Solution: Provide a fake version of your IPC bridge before the frontend component mounts in your test environment.
Imagine your kitchen (Main Process) and the cash register (Renderer Process) communicate via a walkie-talkie (IPC). If you want to test if the cashier correctly handles a "pizza is ready" message, you do not need to fire up the kitchen ovens. You just use a tape recorder (Mock) to play the "pizza is ready" message through the walkie-talkie and watch how the cashier reacts.
Hands-on Practice
Industry standard dictates using a preload.js script to expose specific APIs via contextBridge.
Assume your app has this exposed API:
// What your real app does
window.electronAPI = {
saveFile: (data) => ipcRenderer.invoke('save-file', data)
}When writing a component unit test (e.g., using React Testing Library), we hijack the global window object before the test begins:
// UIComponent.test.jsx
import { render, screen, fireEvent } from '@testing-library/react';
import { vi } from 'vitest';
import SaveButton from './SaveButton';
// Setup the fake IPC bridge before testing
beforeAll(() => {
global.window.electronAPI = {
// We create a fake function that instantly returns true
saveFile: vi.fn().mockResolvedValue({ success: true })
};
});
test('shows success message when file is saved via IPC', async () => {
render(<SaveButton />);
// User clicks the button in the UI
fireEvent.click(screen.getByText('Save File'));
// Ensure our UI called the mocked IPC bridge
expect(global.window.electronAPI.saveFile).toHaveBeenCalled();
// Verify UI reacts to the mocked response
expect(await screen.findByText('Saved successfully!')).toBeVisible();
});This guarantees your test runs in milliseconds. No real files are written to the disk, and no IPC timeouts occur.
4. Advanced Debugging Techniques and DevTools Extensions 🕵️
Definition: Advanced debugging is the process of inspecting the internal state, memory, and execution flow of an application using specialized diagnostic tools, rather than relying purely on text-based logs.
Problem: Relying solely on console.log('here 1') and console.log('here 2') is a time-honored tradition, but when your Main Process is quietly leaking memory or your frontend UI state is deeply nested in Redux/Vuex, a printed string will not help you. You need to inspect variables as they change in real-time.
Solution: Attach a Node.js debugger to the Main Process, and install official Chrome DevTools Extensions (like React or Vue DevTools) into the Renderer Process.
Debugging the Main Process
Because the Main Process is essentially a Node.js runtime, you can pass the --inspect flag to Electron.
Run your app with:
electron . --inspect=5858Now, open Google Chrome and navigate to chrome://inspect. You will see your Electron app listed under "Remote Target". Clicking "inspect" opens a dedicated DevTools window solely for your Main Process, allowing you to pause code execution using breakpoints and inspect memory usage.
Installing DevTools Extensions in the Renderer
Since the Renderer Process is a Chromium browser, it supports regular Chrome extensions. However, installing them programmatically across different operating systems can be a headache of absolute file paths.
The standard industry fix is using the electron-devtools-installer library, which fetches the extension directly from the Chrome Web Store and unpacks it into your app's temporary session.
Install it for development:
npm install -D electron-devtools-installerHook it into your main.js file:
// main.js
const { app, BrowserWindow } = require('electron');
const installExtension = require('electron-devtools-installer').default;
const { REACT_DEVELOPER_TOOLS } = require('electron-devtools-installer');
app.whenReady().then(() => {
// Only load this in development mode!
if (!app.isPackaged) {
installExtension(REACT_DEVELOPER_TOOLS)
.then((name) => console.log(`Successfully Added Extension: ${name}`))
.catch((err) => console.log('Failed to add extension: ', err));
}
const win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL('http://localhost:3000');
// Automatically open the devtools for the developer
win.webContents.openDevTools();
});Next time you start your app, your regular DevTools panel will have a shiny new "React" or "Vue" tab waiting for you, complete with full state inspection.
References for Extra Reading 📚
Challenge
You are tasked with writing a unit test for a function in an Electron application's main process. The function, createMainWindow, is responsible for creating and configuring the main application window.
Your goal is to write a test file using Vitest that verifies the behavior of createMainWindow without actually creating a visual window.
Your test must:
- Use Vitest's mocking capabilities to completely mock the
electronmodule. - The mock for
BrowserWindowmust be a mock constructor (vi.fn()) that can be instantiated. The instance it returns should also have a mockedloadFilemethod to prevent errors. - Write a test case that calls the
createMainWindowfunction. - Assert that the
BrowserWindowconstructor was called exactly one time. - Assert that the
BrowserWindowconstructor was called with a configuration object that includes awebPreferencesproperty matching the one specified in thecreateMainWindowfunction.
Expected result
Your solution should be a single block of JavaScript code representing the content of the test file.
The code must include:
- Imports for
vi,describe,it, andexpectfrom Vitest. - The import for the
createMainWindowfunction. - A call to
vi.mock('electron', ...)to set up the mock. The mock factory function should return an object containing a mockedBrowserWindowclass. - The
BrowserWindowmock should be avi.fn()constructor that returns an object with its own mock method,loadFile. - A
describeblock for the test suite. - An
itblock for the specific test case. - An
expectstatement to check thatBrowserWindowhas been called once. - An
expectstatement usingtoHaveBeenCalledWithto validate that the constructor was called with an object containing the correctwebPreferences.