Unit Testing Main and Renderer Process Separation in Electron

Unit Testing Main and Renderer Process Separation in Electron

Electron applications have a split personality: the main process runs in Node.js with full system access, while renderer processes run in a Chromium context with (optionally) limited Node.js access. This architectural split creates a testing challenge — you can't simply import your main process code into a renderer test, and you can't run renderer tests with Jest's default Node.js environment.

Most teams skip unit testing Electron-specific code and rely entirely on end-to-end tests. That's a mistake. E2E tests are slow, flaky on CI, and give poor signal for logic bugs. A solid unit testing strategy that treats the two processes separately gives you fast feedback and precise failure diagnostics. This guide shows you exactly how to set that up.

The Process Separation Problem

Consider this code structure:

src/
  main/
    index.ts          # Electron entry point
    window-manager.ts # BrowserWindow creation and management
    auto-updater.ts   # electron-updater integration
    ipc-handlers.ts   # ipcMain.handle() registrations
  renderer/
    App.tsx           # React root component
    hooks/
      useFileSystem.ts  # Calls ipcRenderer.invoke()
      useSettings.ts    # Reads/writes settings via IPC
  preload/
    index.ts          # contextBridge exposure

Main process files import from electron (e.g., BrowserWindow, ipcMain, app). Renderer files import from electron too, but use different exports (ipcRenderer, contextBridge). When Jest tries to run either in a plain Node.js environment, it fails because electron isn't a real npm package — it's a runtime-injected module.

The fix is two separate Jest configurations: one for main process code, one for renderer code.

Setting Up Jest for the Main Process

The main process runs in Node.js, so Jest's default testEnvironment: 'node' works. The only issue is mocking the electron module.

Install dependencies:

npm install --save-dev jest @types/jest ts-jest jest-mock-extended

Create jest.main.config.ts:

import type { Config } from 'jest';

const config: Config = {
  displayName: 'main',
  testEnvironment: 'node',
  testMatch: ['<rootDir>/src/main/**/*.test.ts'],
  transform: {
    '^.+\\.tsx?$': ['ts-jest', {
      tsconfig: '<rootDir>/tsconfig.main.json',
    }],
  },
  moduleNameMapper: {
    // Mock the electron module for all main process tests
    '^electron$': '<rootDir>/tests/mocks/electron-main.ts',
  },
};

export default config;

The key is moduleNameMapper pointing electron imports to a mock module. Create tests/mocks/electron-main.ts:

// Mock all Electron main process APIs
const mockBrowserWindow = {
  loadURL: jest.fn(),
  loadFile: jest.fn(),
  on: jest.fn(),
  once: jest.fn(),
  webContents: {
    send: jest.fn(),
    openDevTools: jest.fn(),
    on: jest.fn(),
    setWindowOpenHandler: jest.fn(),
  },
  show: jest.fn(),
  hide: jest.fn(),
  close: jest.fn(),
  destroy: jest.fn(),
  isDestroyed: jest.fn().mockReturnValue(false),
  setTitle: jest.fn(),
  getSize: jest.fn().mockReturnValue([1200, 800]),
  setSize: jest.fn(),
  maximize: jest.fn(),
  isMaximized: jest.fn().mockReturnValue(false),
};

const MockBrowserWindow = jest.fn().mockImplementation(() => mockBrowserWindow);
(MockBrowserWindow as any).getAllWindows = jest.fn().mockReturnValue([]);
(MockBrowserWindow as any).getFocusedWindow = jest.fn().mockReturnValue(null);

export const BrowserWindow = MockBrowserWindow;

export const app = {
  getName: jest.fn().mockReturnValue('TestApp'),
  getVersion: jest.fn().mockReturnValue('1.0.0'),
  getPath: jest.fn().mockImplementation((name: string) => `/mock/${name}`),
  getLocale: jest.fn().mockReturnValue('en-US'),
  isReady: jest.fn().mockReturnValue(true),
  whenReady: jest.fn().mockResolvedValue(undefined),
  quit: jest.fn(),
  on: jest.fn(),
  once: jest.fn(),
  emit: jest.fn(),
};

export const ipcMain = {
  handle: jest.fn(),
  on: jest.fn(),
  once: jest.fn(),
  removeHandler: jest.fn(),
  removeAllListeners: jest.fn(),
};

export const dialog = {
  showOpenDialog: jest.fn().mockResolvedValue({ canceled: false, filePaths: [] }),
  showSaveDialog: jest.fn().mockResolvedValue({ canceled: false, filePath: undefined }),
  showMessageBox: jest.fn().mockResolvedValue({ response: 0 }),
  showErrorBox: jest.fn(),
};

export const shell = {
  openExternal: jest.fn().mockResolvedValue(undefined),
  openPath: jest.fn().mockResolvedValue(''),
  showItemInFolder: jest.fn(),
};

export const nativeTheme = {
  themeSource: 'system' as const,
  shouldUseDarkColors: false,
  on: jest.fn(),
};

export const Menu = {
  buildFromTemplate: jest.fn().mockReturnValue({ popup: jest.fn() }),
  setApplicationMenu: jest.fn(),
  getApplicationMenu: jest.fn().mockReturnValue(null),
};

export const Tray = jest.fn().mockImplementation(() => ({
  setToolTip: jest.fn(),
  setContextMenu: jest.fn(),
  on: jest.fn(),
}));

export default { BrowserWindow, app, ipcMain, dialog, shell, nativeTheme, Menu, Tray };

Unit Testing the Window Manager

With the mock in place, you can test window creation logic in complete isolation:

// src/main/window-manager.test.ts
import { BrowserWindow, app } from 'electron';
import { WindowManager } from './window-manager';

// Reset mocks between tests
beforeEach(() => {
  jest.clearAllMocks();
});

describe('WindowManager', () => {
  it('creates a BrowserWindow with correct default dimensions', () => {
    const manager = new WindowManager();
    manager.createMainWindow();
    
    expect(BrowserWindow).toHaveBeenCalledWith(
      expect.objectContaining({
        width: 1200,
        height: 800,
        minWidth: 800,
        minHeight: 600,
      })
    );
  });

  it('sets webPreferences with contextIsolation and no nodeIntegration', () => {
    const manager = new WindowManager();
    manager.createMainWindow();
    
    expect(BrowserWindow).toHaveBeenCalledWith(
      expect.objectContaining({
        webPreferences: expect.objectContaining({
          contextIsolation: true,
          nodeIntegration: false,
        }),
      })
    );
  });

  it('loads the correct URL in development mode', () => {
    process.env.NODE_ENV = 'development';
    const manager = new WindowManager();
    const win = manager.createMainWindow();
    
    const instance = (BrowserWindow as jest.Mock).mock.results[0].value;
    expect(instance.loadURL).toHaveBeenCalledWith('http://localhost:3000');
  });

  it('loads the index file in production mode', () => {
    process.env.NODE_ENV = 'production';
    const manager = new WindowManager();
    manager.createMainWindow();
    
    const instance = (BrowserWindow as jest.Mock).mock.results[0].value;
    expect(instance.loadFile).toHaveBeenCalledWith(
      expect.stringContaining('index.html')
    );
  });

  it('tracks open windows and returns them', () => {
    const manager = new WindowManager();
    manager.createMainWindow();
    manager.createMainWindow();
    
    expect(manager.getWindowCount()).toBe(2);
  });
});

Setting Up Jest for the Renderer Process

Renderer processes need testEnvironment: 'jsdom' because they run in a browser context. The React Testing Library setup is standard, but you need to mock electron differently — renderer code uses window.electron (exposed via contextBridge) rather than importing directly from electron.

Create jest.renderer.config.ts:

import type { Config } from 'jest';

const config: Config = {
  displayName: 'renderer',
  testEnvironment: 'jsdom',
  testMatch: ['<rootDir>/src/renderer/**/*.test.{ts,tsx}'],
  transform: {
    '^.+\\.tsx?$': ['ts-jest', {
      tsconfig: '<rootDir>/tsconfig.renderer.json',
    }],
  },
  setupFilesAfterFramework: ['<rootDir>/tests/setup/renderer-setup.ts'],
  moduleNameMapper: {
    '\\.(css|less|scss)$': '<rootDir>/tests/mocks/style-mock.ts',
    '\\.(png|jpg|svg)$': '<rootDir>/tests/mocks/file-mock.ts',
  },
};

export default config;

Create tests/setup/renderer-setup.ts:

import '@testing-library/jest-dom';

// Mock the contextBridge API that preload exposes as window.electron
const mockElectronAPI = {
  invoke: jest.fn(),
  on: jest.fn(),
  off: jest.fn(),
  send: jest.fn(),
  // App-specific methods your preload exposes
  readFile: jest.fn(),
  writeFile: jest.fn(),
  openDialog: jest.fn(),
  getSettings: jest.fn(),
  saveSettings: jest.fn(),
};

Object.defineProperty(window, 'electron', {
  value: mockElectronAPI,
  writable: true,
});

// Export so tests can access the mock
export { mockElectronAPI };

Testing Renderer Hooks

Your renderer hooks call IPC via window.electron. Here's how to test them:

// src/renderer/hooks/useFileSystem.test.ts
import { renderHook, act } from '@testing-library/react';
import { mockElectronAPI } from '../../../tests/setup/renderer-setup';
import { useFileSystem } from './useFileSystem';

beforeEach(() => {
  jest.clearAllMocks();
});

describe('useFileSystem', () => {
  it('reads a file and returns its content', async () => {
    mockElectronAPI.readFile.mockResolvedValueOnce('file content here');
    
    const { result } = renderHook(() => useFileSystem());
    
    await act(async () => {
      await result.current.readFile('/path/to/file.txt');
    });
    
    expect(mockElectronAPI.readFile).toHaveBeenCalledWith('/path/to/file.txt');
    expect(result.current.content).toBe('file content here');
    expect(result.current.error).toBeNull();
  });

  it('sets error state when read fails', async () => {
    mockElectronAPI.readFile.mockRejectedValueOnce(new Error('Permission denied'));
    
    const { result } = renderHook(() => useFileSystem());
    
    await act(async () => {
      await result.current.readFile('/protected/file.txt');
    });
    
    expect(result.current.content).toBeNull();
    expect(result.current.error).toBe('Permission denied');
  });

  it('sets loading state during read', async () => {
    let resolveRead: (val: string) => void;
    const pendingRead = new Promise<string>(res => { resolveRead = res; });
    mockElectronAPI.readFile.mockReturnValueOnce(pendingRead);
    
    const { result } = renderHook(() => useFileSystem());
    
    act(() => { result.current.readFile('/file.txt'); });
    expect(result.current.loading).toBe(true);
    
    await act(async () => { resolveRead('content'); });
    expect(result.current.loading).toBe(false);
  });
});

Testing IPC Handlers in Isolation

The cleanest way to unit test ipcMain.handle() registrations is to export them as pure functions and register them separately:

// src/main/ipc-handlers.ts
import { ipcMain, dialog, app } from 'electron';
import fs from 'fs/promises';
import path from 'path';

// Pure handler functions — testable without ipcMain
export async function handleReadFile(
  _event: Electron.IpcMainInvokeEvent,
  filePath: string
): Promise<string> {
  const resolved = path.resolve(filePath);
  
  // Security: only allow reads within user's home directory
  const userHome = app.getPath('home');
  if (!resolved.startsWith(userHome)) {
    throw new Error('Access denied: path outside home directory');
  }
  
  return fs.readFile(resolved, 'utf-8');
}

export async function handleOpenDialog(
  _event: Electron.IpcMainInvokeEvent,
): Promise<string | null> {
  const result = await dialog.showOpenDialog({
    properties: ['openFile'],
    filters: [{ name: 'Text files', extensions: ['txt', 'md'] }],
  });
  
  if (result.canceled) return null;
  return result.filePaths[0];
}

// Registration function called at app startup
export function registerIpcHandlers() {
  ipcMain.handle('read-file', handleReadFile);
  ipcMain.handle('open-dialog', handleOpenDialog);
}

Now test the pure functions directly:

// src/main/ipc-handlers.test.ts
import { handleReadFile, handleOpenDialog } from './ipc-handlers';
import { app, dialog } from 'electron';
import fs from 'fs/promises';

jest.mock('fs/promises');

const mockEvent = {} as Electron.IpcMainInvokeEvent;

describe('handleReadFile', () => {
  beforeEach(() => {
    (app.getPath as jest.Mock).mockReturnValue('/home/user');
  });

  it('reads a file within the home directory', async () => {
    (fs.readFile as jest.Mock).mockResolvedValueOnce('file content');
    
    const result = await handleReadFile(mockEvent, '/home/user/documents/file.txt');
    
    expect(fs.readFile).toHaveBeenCalledWith('/home/user/documents/file.txt', 'utf-8');
    expect(result).toBe('file content');
  });

  it('rejects paths outside the home directory', async () => {
    await expect(
      handleReadFile(mockEvent, '/etc/passwd')
    ).rejects.toThrow('Access denied: path outside home directory');
    
    expect(fs.readFile).not.toHaveBeenCalled();
  });
});

describe('handleOpenDialog', () => {
  it('returns the selected file path', async () => {
    (dialog.showOpenDialog as jest.Mock).mockResolvedValueOnce({
      canceled: false,
      filePaths: ['/home/user/file.txt'],
    });
    
    const result = await handleOpenDialog(mockEvent);
    expect(result).toBe('/home/user/file.txt');
  });

  it('returns null when dialog is canceled', async () => {
    (dialog.showOpenDialog as jest.Mock).mockResolvedValueOnce({
      canceled: true,
      filePaths: [],
    });
    
    const result = await handleOpenDialog(mockEvent);
    expect(result).toBeNull();
  });
});

Testing the Preload Script

The preload script is a third execution context — it has access to both Node.js APIs and the DOM. Test it with the Node environment but mock contextBridge:

// tests/mocks/electron-preload.ts
export const contextBridge = {
  exposeInMainWorld: jest.fn(),
};

export const ipcRenderer = {
  invoke: jest.fn(),
  on: jest.fn(),
  once: jest.fn(),
  send: jest.fn(),
  removeListener: jest.fn(),
  removeAllListeners: jest.fn(),
};
// src/preload/index.test.ts
import { contextBridge, ipcRenderer } from 'electron';

// Import triggers the preload script registration side effect
import '../../src/preload/index';

describe('preload script', () => {
  it('exposes electron API to the renderer', () => {
    expect(contextBridge.exposeInMainWorld).toHaveBeenCalledWith(
      'electron',
      expect.objectContaining({
        invoke: expect.any(Function),
        on: expect.any(Function),
        off: expect.any(Function),
      })
    );
  });

  it('exposed invoke delegates to ipcRenderer.invoke', () => {
    const exposedAPI = (contextBridge.exposeInMainWorld as jest.Mock).mock.calls[0][1];
    
    (ipcRenderer.invoke as jest.Mock).mockResolvedValueOnce('result');
    exposedAPI.invoke('my-channel', { key: 'value' });
    
    expect(ipcRenderer.invoke).toHaveBeenCalledWith('my-channel', { key: 'value' });
  });
});

Combining the Configs

Add a root-level config for running both suites together:

// package.json
{
  "scripts": {
    "test:main": "jest --config jest.main.config.ts",
    "test:renderer": "jest --config jest.renderer.config.ts",
    "test:unit": "jest --projects jest.main.config.ts jest.renderer.config.ts"
  }
}

The --projects flag runs both configurations in a single Jest invocation, showing a combined coverage report.

Coverage Configuration

Configure coverage collection to cover both process types accurately:

// In each config's coveragePathIgnorePatterns:
coveragePathIgnorePatterns: [
  '/node_modules/',
  '/src/main/index.ts',    // Entry point, not logic
  '/src/preload/index.ts', // Covered by preload tests
],
collectCoverageFrom: [
  'src/main/**/*.ts',
  '!src/main/**/*.test.ts',
],

Conclusion

The key insight is that Electron's process separation is actually a testing advantage — it forces you to write code that's separated by concern, which in turn makes unit testing straightforward. Mock electron for both process types, export your IPC handlers as pure functions, and keep the registration code thin. The result is a fast unit test suite that covers your security logic, business rules, and IPC contracts without needing to spin up a real Electron instance.

Read more

Start now free