How to Test a Chrome Extension After Its Service Worker Stops
Stop a Manifest V3 worker in a test profile, trigger the action again, and verify a new worker reads the same persisted state.
Table of Contents8 sections

A Chrome extension saves a preference and reads it back perfectly in development. Leave the extension alone, then try again, and the same button suddenly returns a default. The first run tested a service worker that was already alive. The second discovered that the feature depended on memory that Chrome is free to discard. To catch this before shipping, make the worker restart a test step rather than an accident.
Quick solution: Save a known value, invoke a real extension action, then terminate that extension’s worker in a disposable Chrome profile. Trigger the action again without reloading the extension. Assert the reply came from a fresh worker and still reflects the saved value. Test interrupted writes separately.
Seed saved item: fixture-42
First click: generation A, result fixture-42
Terminate the worker; keep the extension installed.
Second click: generation B, result fixture-42
Test the transition, not a fixed waiting period
A warm-worker test tells you whether a handler works once initialization has completed. A restart test tells you whether the first event can wake a new instance and reconstruct what it needs. The assertion has two parts: the observed result still makes sense, and the result actually came from a new execution of the worker. Without the second part, a worker that never stopped can make a broken test look green.
Chrome’s extension service worker lifecycle documentation describes normal idle shutdown conditions and how incoming events can revive a dormant worker. Do not assume sleeping for a given number of seconds proves a shutdown happened. Extension events and API calls can change the idle timer. A debug setup can also differ from ordinary use. A forced termination is useful for a fast regression test because it removes the wait from your proof. Natural idling is still worth checking in a separate smoke test.
For this scenario, leave the extension installed. A reload from the extensions page or a full browser restart makes a different scenario: it may change which events are delivered or which storage remains. If you reload on every attempt, you can accidentally rerun initialization that the existing user’s next click will not get. Keep the same profile, extension ID, and stored fixture for the warm and cold checks.
Write a fixture a reset cannot fake
Choose a value that is deliberately different from a default or empty value. For a hypothetical clipping extension, save a synthetic marker such as fixture-42 and verify a read command returns it. Seed it through a real extension path before the test, or through an explicit fixture setup with a visible readback. Do not embed that marker as the handler’s fallback. If a broken handler silently defaults to the same value, the test has no way to detect the missing storage read.
Put a diagnostic generation identifier in the test build’s worker, created once at its top level, such as a random UUID. Return it alongside the saved field to the fixture page. It is an identity for that execution only, not a durable identifier for users, installations, or analytics. Remove test-specific behavior from the public bundle. You can also verify target destruction and recreation with browser automation, but a response-level generation immediately tells you which worker answered the click.
The fixture page should call the same dispatcher as the popup or another supported extension surface. It should update its response attributes only after the awaited reply, and count replies separately from clicks. Otherwise the second click could produce an immediate optimistic UI update and satisfy the test with the old response. Do not use a diagnostic ping on an unrelated handler as a stand-in for the real operation. A ping can succeed even while the feature loses its state.
Force termination in a disposable test profile
Google’s Puppeteer termination guide shows selecting the extension worker and closing it with Puppeteer’s worker API. Use a compatible browser and Puppeteer version, and load your own test extension into an isolated profile. The helper below assumes the page and a stored test item are ready, the result element records completed replies, and the test starts with zero replies. Give the test runner a bounded timeout. The code checks a new worker generation in the actual response rather than assuming a successful close means the next click completed.
// Node test helper; browser and page belong to a disposable profile.
// The fixture page reports worker responses in data-* attributes.
async function assertWake(browser, page, extensionId, assert) {
const prefix = 'chrome-extension://' + extensionId + '/';
const button = page.locator('#read-saved');
const response = () => page.$eval('#result', el => ({
boot: el.dataset.boot, saved: el.dataset.saved
}));
await button.click();
await page.waitForSelector('#result[data-reply="1"]');
const before = await response();
assert.ok(before.boot);
assert.equal(before.saved, 'fixture-42');
const target = await browser.waitForTarget(
t => t.type() === 'service_worker' && t.url().startsWith(prefix)
);
const worker = await target.worker();
assert.ok(worker, 'Expected extension service worker');
await worker.close();
await button.click();
await page.waitForSelector('#result[data-reply="2"]');
const after = await response();
assert.ok(after.boot);
assert.notEqual(after.boot, before.boot, 'Expected a fresh worker');
assert.equal(after.saved, before.saved);
}
Use the exact origin of the installed test extension, including the trailing slash, to avoid closing a worker owned by a different extension. Target type matters too: extension pages, tabs, and ordinary website service workers are not the target you want. Close only the selected worker. Do not add a background poll that constantly wakes it; a clean reproduction has one trigger for the second response. The helper is a test fixture pattern, not a claim that this extension was tested in a user browser.
When the test fails, keep the concrete symptom. No second reply points you toward event registration, message handling, timeouts, or startup errors. A new generation with a wrong saved value points you toward persistence and read timing. An unchanged generation means the test did not demonstrate the transition, even if the value is correct. Those are three bugs to investigate, not one generic failure called “Chrome slept.”
Make the first event a first-class path
Chrome’s Manifest V3 service worker migration guide explains that listeners must be registered synchronously rather than after asynchronous initialization. Register the message or action handler at module scope. Within the handler, load settings or durable state before deciding what to return. Putting the registration inside a storage callback can leave the event without a handler when the worker starts cold. A handler that starts correctly but answers before its data loads may return an equally misleading default.
Keep installation work separate from startup needs. One-time tasks, like adding an initial context menu or setting migration defaults, can belong in installation handling. The user action cannot depend on a variable written only by that installation event. The installation event is not a promise that it will run each time a dormant worker wakes. Use modules and globals for caches that can be rebuilt, never as the only copy of the user’s durable choices.
Choose storage based on the lifetime you promise, not just on whether it survives this one test. Chrome’s Storage API reference distinguishes session storage from local storage. Session storage can bridge worker restarts within the same loaded extension, but it is cleared on a browser restart, extension reload, disable, or update. Use it for session-scoped state where appropriate. Use local storage for ordinary persisted settings that must survive a browser restart, and design a separate browser-restart scenario to prove it. A test that stops only the worker can pass with either storage area and cannot distinguish those two promises.
A reply should reflect a real storage result. If a write is part of the action, acknowledge success only after it succeeds. If the browser stops the worker before the reply, the caller may not know whether the write happened. Keep the user’s input and state visible enough to retry or look up the operation. For account-scoped decisions, RayLabs’ shared Free and Pro extension guide describes why a recovered grant must still match the current session rather than simply existing somewhere in storage.
Test interruptions on both sides of the write
An idle restart after a completed read is the smallest case. It cannot tell you what happens when an action makes a write and never replies. Add a separate scenario with a controlled pause before a write, then another after the write but before the reply. Terminate at those boundaries in a scratch environment and reissue the same logical operation. Assert that the first case eventually writes once and the second case does not duplicate the existing result. Keep any checkpoint hook confined to test builds.
Give the operation a stable identifier before its first attempt. Retain it in the caller’s pending record or in durable storage that survives the worker restart. A retry identifiable only by the worker’s generation is not stable. For local state, choose an operation whose record can be looked up or updated by that identifier. For a remote write, the server also needs compatible idempotency behavior; a local map cannot settle whether a response was lost after the server already committed the request.
Test the two write interruption points independently of multitasking, offline mode, and browser restart. If everything fails at once, you will not know which boundary caused the unexpected result. Once the isolated checkpoints pass, add realistic combinations that matter to your extension, such as the popup closing while a request runs. The first goal is not an enormous matrix, but evidence that each failure point you intend to support has one clear expected outcome.
Separate test failures from product failures
If the harness cannot find the worker after the first successful reply, check whether it really selected the installed test extension and whether the worker already became dormant. Do not trigger repeated background calls simply to get a target. Mark the run inconclusive and surface the browser version, extension version, the targeted extension ID, and the last fixture event. A bad fixture that never exercises a restart should not become a passing feature test.
Compare what happens with the worker inspector closed. Tools used for debugging may change the lifetime of the inspected worker, while test fixtures that send heartbeat messages can keep it active. Do not change the extension to stay awake to make the test green. The goal is a handler that survives when memory disappears, not one that accidentally depends on the test environment protecting it.
Keep fixture assertions on user-visible meaning as well as developer signals. If a restored object has a valid ID but the wrong selected workspace, the operation did not recover correctly. Read back the minimum fields that distinguish the correct outcome, and include a negative test in which the fixture is intentionally missing. That case should show your chosen empty state or recoverable error, not reuse a stale value from a previous run.
Run a natural idle smoke test once the deterministic test passes. With no popup or inspector open and no test heartbeat active, allow the worker to go dormant, then trigger the same action and confirm a new execution and correct result. A forced stop exercises the reentry path quickly, while the smoke test helps catch unexpected activity that prevents ordinary idling. Record which type of result you observed. They answer related but different questions.
Keep the release checklist small and concrete
Start with one smoke operation that users can recognize: read a saved choice, open a previously saved item, or resume a pending local action. Use the same case in a warm run and a restarted run so you can compare outputs. Then add only the state boundaries the extension actually promises. A feature that has no in-flight writes need not pretend it has an interrupted remote request; one that queues work should cover that path before shipping.
- Use an isolated browser profile and a synthetic saved value.
- Verify one good response before stopping the targeted extension worker.
- Trigger the real action again without reinstalling or reloading.
- Prove a new worker answered and the persisted value is correct.
- Test before-write and after-write interruption when the operation writes.
- Keep a natural idle check separate from deterministic termination.
A successful wake-up is not a console message that says the worker started. It is the first real action after Chrome discarded memory returning the right result, or a clear, recoverable error. Test that transition directly and you will catch failures that a full afternoon of warm development clicks can miss.
You Might Also Like
View all articles
How to Keep Free and Pro Chrome Extension Features in One Codebase
Bundle free and paid features in one Chrome extension, gate actions through a shared policy, and keep account switches and offline states safe.

How to Automate Chrome Firefox and Edge Extension Releases
Build one browser extension release pipeline with reproducible archives, store-specific APIs, safe credentials, bounded retries, and independent publication verification.

How to Test an Android APK Upgrade With Existing User Data
Build realistic Android upgrade fixtures, install the candidate without clearing data, and verify saved state before and after sync.