Unit Testing Browser Extension Background Scripts and Service Workers
Background scripts (or service workers in Manifest V3) are the core logic layer of browser extensions — they handle messages from content scripts, manage storage, make API calls, and coordinate the extension's behavior. They're also the hardest part to test.
The challenge: background scripts run inside the browser runtime with access to chrome.* APIs that don't exist in Node.js test environments. You can't just run them in Jest without mocking the entire browser extension API surface.
This guide covers practical strategies for unit testing background scripts and service workers.
The Testing Problem with Background Scripts
Background scripts differ from regular JavaScript in important ways:
They use the chrome.* API: chrome.tabs, chrome.storage, chrome.runtime, chrome.alarms — none of these exist outside a browser or a mock.
They respond to events: chrome.runtime.onMessage, chrome.tabs.onUpdated, chrome.alarms.onAlarm — event-driven code that's harder to test than synchronous functions.
They have no DOM: Unlike content scripts, background scripts have no access to the page DOM. But they also can't use document or window in any meaningful way.
MV3 service workers have lifecycle constraints: Service workers can be terminated and restarted. State that relies on module-level variables will be lost.
Setting Up the Mock chrome API
The jest-chrome package provides Jest mocks for the entire Chrome extension API:
npm install --save-dev jest-chromeConfigure it in your Jest setup:
// jest.setup.js
const { chrome } = require('jest-chrome');
global.chrome = chrome;// jest.config.js
module.exports = {
testEnvironment: 'node',
setupFilesAfterFramework: ['./jest.setup.js'],
};For more control, or when jest-chrome doesn't cover your needs, create manual mocks:
// __mocks__/chrome.js
const chrome = {
runtime: {
onMessage: {
addListener: jest.fn(),
removeListener: jest.fn(),
hasListener: jest.fn(),
},
sendMessage: jest.fn(),
onInstalled: {
addListener: jest.fn(),
},
getManifest: jest.fn(() => ({ version: '1.0.0', manifest_version: 3 })),
},
storage: {
local: {
get: jest.fn(),
set: jest.fn(),
remove: jest.fn(),
clear: jest.fn(),
},
sync: {
get: jest.fn(),
set: jest.fn(),
},
},
tabs: {
query: jest.fn(),
create: jest.fn(),
update: jest.fn(),
remove: jest.fn(),
sendMessage: jest.fn(),
onUpdated: {
addListener: jest.fn(),
removeListener: jest.fn(),
},
},
alarms: {
create: jest.fn(),
clear: jest.fn(),
getAll: jest.fn(),
onAlarm: {
addListener: jest.fn(),
},
},
};
global.chrome = chrome;
module.exports = chrome;Testing Message Handling
The most common background script pattern is responding to messages from content scripts or popups:
// background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'GET_USER_DATA') {
getUserData(sender.tab.id)
.then(data => sendResponse({ success: true, data }))
.catch(error => sendResponse({ success: false, error: error.message }));
return true; // Keep channel open for async response
}
if (message.type === 'CLEAR_CACHE') {
clearCache()
.then(() => sendResponse({ success: true }))
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
}
});Testing this requires capturing the listener and calling it directly:
// tests/background.test.js
import { getUserData, clearCache } from '../background';
describe('message handling', () => {
beforeEach(() => {
jest.clearAllMocks();
// Re-import to re-register listeners
jest.resetModules();
require('../background');
});
it('handles GET_USER_DATA message', async () => {
// Get the registered listener
const listener = chrome.runtime.onMessage.addListener.mock.calls[0][0];
// Mock the data
const mockData = { userId: 'u123', name: 'Test User' };
jest.spyOn(global, 'getUserData').mockResolvedValue(mockData);
// Simulate the message
const sendResponse = jest.fn();
const message = { type: 'GET_USER_DATA' };
const sender = { tab: { id: 5 } };
listener(message, sender, sendResponse);
// Wait for async operations
await new Promise(resolve => setTimeout(resolve, 0));
expect(sendResponse).toHaveBeenCalledWith({
success: true,
data: mockData
});
});
it('returns error response when GET_USER_DATA fails', async () => {
const listener = chrome.runtime.onMessage.addListener.mock.calls[0][0];
jest.spyOn(global, 'getUserData').mockRejectedValue(new Error('Network error'));
const sendResponse = jest.fn();
listener({ type: 'GET_USER_DATA' }, { tab: { id: 5 } }, sendResponse);
await new Promise(resolve => setTimeout(resolve, 0));
expect(sendResponse).toHaveBeenCalledWith({
success: false,
error: 'Network error'
});
});
it('returns true to keep message channel open for async responses', () => {
const listener = chrome.runtime.onMessage.addListener.mock.calls[0][0];
const result = listener({ type: 'GET_USER_DATA' }, {}, jest.fn());
// Must return true for async responses
expect(result).toBe(true);
});
it('ignores unknown message types', () => {
const listener = chrome.runtime.onMessage.addListener.mock.calls[0][0];
const sendResponse = jest.fn();
const result = listener({ type: 'UNKNOWN_TYPE' }, {}, sendResponse);
expect(sendResponse).not.toHaveBeenCalled();
expect(result).toBeFalsy();
});
});Testing Storage Operations
// services/settings.js
export async function getSettings() {
return new Promise((resolve) => {
chrome.storage.sync.get(['theme', 'notifications', 'language'], resolve);
});
}
export async function saveSettings(settings) {
return new Promise((resolve, reject) => {
chrome.storage.sync.set(settings, () => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
} else {
resolve();
}
});
});
}// tests/services/settings.test.js
import { getSettings, saveSettings } from '../services/settings';
describe('settings storage', () => {
beforeEach(() => jest.clearAllMocks());
it('retrieves settings from sync storage', async () => {
const mockSettings = { theme: 'dark', notifications: true, language: 'en' };
chrome.storage.sync.get.mockImplementation((keys, callback) => {
callback(mockSettings);
});
const result = await getSettings();
expect(chrome.storage.sync.get).toHaveBeenCalledWith(
['theme', 'notifications', 'language'],
expect.any(Function)
);
expect(result).toEqual(mockSettings);
});
it('saves settings to sync storage', async () => {
chrome.storage.sync.set.mockImplementation((data, callback) => {
callback(); // Simulate successful save
});
chrome.runtime.lastError = undefined;
await saveSettings({ theme: 'light' });
expect(chrome.storage.sync.set).toHaveBeenCalledWith(
{ theme: 'light' },
expect.any(Function)
);
});
it('rejects on storage quota exceeded', async () => {
chrome.storage.sync.set.mockImplementation((data, callback) => {
chrome.runtime.lastError = { message: 'QUOTA_BYTES_PER_ITEM quota exceeded' };
callback();
});
await expect(saveSettings({ largeData: 'x'.repeat(10000) }))
.rejects.toThrow('QUOTA_BYTES_PER_ITEM quota exceeded');
});
});Testing Tab Management
// background.js
export async function openOptionsPage() {
const tabs = await chrome.tabs.query({ url: chrome.runtime.getURL('options.html') });
if (tabs.length > 0) {
chrome.tabs.update(tabs[0].id, { active: true });
} else {
chrome.tabs.create({ url: 'options.html' });
}
}describe('tab management', () => {
it('focuses existing options tab if open', async () => {
chrome.tabs.query.mockResolvedValue([{ id: 42 }]);
chrome.runtime.getURL.mockReturnValue('chrome-extension://abc/options.html');
await openOptionsPage();
expect(chrome.tabs.update).toHaveBeenCalledWith(42, { active: true });
expect(chrome.tabs.create).not.toHaveBeenCalled();
});
it('creates new options tab when none is open', async () => {
chrome.tabs.query.mockResolvedValue([]); // No existing tabs
chrome.runtime.getURL.mockReturnValue('chrome-extension://abc/options.html');
await openOptionsPage();
expect(chrome.tabs.create).toHaveBeenCalledWith({ url: 'options.html' });
expect(chrome.tabs.update).not.toHaveBeenCalled();
});
});Testing Alarm-Based Logic
MV3 service workers use chrome.alarms for periodic tasks instead of setInterval:
// background.js
chrome.alarms.create('sync-data', { periodInMinutes: 60 });
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === 'sync-data') {
syncUserData();
}
});describe('alarm handling', () => {
it('creates sync alarm with correct period', () => {
require('../background'); // Trigger background script initialization
expect(chrome.alarms.create).toHaveBeenCalledWith('sync-data', {
periodInMinutes: 60
});
});
it('triggers data sync when sync-data alarm fires', async () => {
const syncMock = jest.fn().mockResolvedValue(undefined);
jest.mock('../services/sync', () => ({ syncUserData: syncMock }));
require('../background');
const alarmListener = chrome.alarms.onAlarm.addListener.mock.calls[0][0];
await alarmListener({ name: 'sync-data' });
expect(syncMock).toHaveBeenCalled();
});
it('ignores unknown alarms', async () => {
const syncMock = jest.fn();
jest.mock('../services/sync', () => ({ syncUserData: syncMock }));
require('../background');
const alarmListener = chrome.alarms.onAlarm.addListener.mock.calls[0][0];
await alarmListener({ name: 'some-other-alarm' });
expect(syncMock).not.toHaveBeenCalled();
});
});Testing Service Worker Lifecycle (MV3)
MV3 service workers can be terminated by the browser. Logic that relies on module-level state breaks:
// WRONG - state lost when service worker restarts
let requestCount = 0; // This resets to 0 on every service worker restart
// CORRECT - use storage for persistent state
async function incrementRequestCount() {
const { requestCount = 0 } = await chrome.storage.local.get('requestCount');
await chrome.storage.local.set({ requestCount: requestCount + 1 });
return requestCount + 1;
}Test both the module-state bug and the storage-based fix:
describe('service worker state persistence', () => {
it('request count persists across service worker restarts', async () => {
// Simulate first session
chrome.storage.local.get.mockImplementation((key, cb) => cb({ requestCount: 5 }));
chrome.storage.local.set.mockImplementation((data, cb) => cb && cb());
const count = await incrementRequestCount();
expect(count).toBe(6);
expect(chrome.storage.local.set).toHaveBeenCalledWith(
{ requestCount: 6 },
expect.anything()
);
});
it('starts from 0 if no previous count in storage', async () => {
chrome.storage.local.get.mockImplementation((key, cb) => cb({})); // empty
chrome.storage.local.set.mockImplementation((data, cb) => cb && cb());
const count = await incrementRequestCount();
expect(count).toBe(1);
});
});Summary
Unit testing browser extension background scripts requires mocking the chrome.* API surface. Key patterns:
- Use
jest-chromeor manual mocks to providechrome.*globals in Jest - Capture
onMessageandonAlarmlisteners viaaddListener.mock.calls[0][0]and call them directly - Mock
chrome.storageoperations withmockImplementationto control return values - Test both happy paths and error scenarios for each message type
- For MV3: test that state is stored in
chrome.storage, not module-level variables
These unit tests run fast and catch logic bugs without needing a browser. Complement them with integration tests that load the actual extension in Playwright for end-to-end coverage.