Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 36 ยท Testing and Debugging

Unit Testing Extension Code with Mocks

Write testable extension code by separating pure logic from chrome APIs, inject a fake chrome object, test storage and message handlers with Vitest or Jest, and run fast tests without a browser.

The chrome object only exists in a real extension, so code that calls it everywhere is hard to test: you would need to load a browser for every check. The solution is a design habit, not a tool. Keep your logic pure and your chrome calls thin, then replace chrome with a simple fake in tests. This lesson shows the pattern, with a tiny test runner you can try right here.

Split logic from the API

Compare these two versions of "count visits per site".

JavaScript
// Hard to test: logic mixed with chrome
chrome.tabs.onUpdated.addListener(async (id, info, tab) => {
  if (info.status !== "complete") return;
  const host = new URL(tab.url).hostname;
  const { counts = {} } = await chrome.storage.local.get("counts");
  counts[host] = (counts[host] ?? 0) + 1;
  await chrome.storage.local.set({ counts });
});
JavaScript
// Testable: pure function + a thin wrapper
export function increment(counts, url) {
  const host = new URL(url).hostname;
  return { ...counts, [host]: (counts[host] ?? 0) + 1 };
}

chrome.tabs.onUpdated.addListener(async (id, info, tab) => {
  if (info.status !== "complete") return;
  const { counts = {} } = await chrome.storage.local.get("counts");
  await chrome.storage.local.set({ counts: increment(counts, tab.url) });
});

increment is plain JavaScript: a test calls it with values and checks the result. The wrapper is so small that a few lines of manual testing cover it.

flowchart LR
    A["chrome event"] --> B["thin wrapper"]
    B --> C["pure logic<br/>(unit tested)"]
    B --> D["chrome.storage<br/>(faked in tests)"]

Most of the value comes from testing the middle box.

Dependency injection with a fake chrome

When a module needs chrome, pass it in rather than reading the global.

JavaScript
// settings.js
export function createSettings(chromeApi) {
  const DEFAULTS = { theme: "light", fontSize: 16 };
  return {
    async load() { return chromeApi.storage.sync.get(DEFAULTS); },
    async save(patch) { await chromeApi.storage.sync.set(patch); }
  };
}

// in production
export const settings = createSettings(chrome);

A test hands in a fake:

JavaScript
function fakeChrome() {
  const data = {};
  return { storage: { sync: {
    async get(defaults) { return { ...defaults, ...data }; },
    async set(patch) { Object.assign(data, patch); }
  } } };
}
Mini test runner with a fake chrome

Using Vitest or Jest for real

In a project with a build tool, install a test runner and put tests next to the code. Both are read-only here because they need Node and a package manager, but the shape is the same as the stand-in above:

JavaScript
// settings.test.js (Vitest)
import { describe, it, expect } from "vitest";
import { createSettings } from "./settings.js";

describe("settings", () => {
  it("returns defaults", async () => {
    const settings = createSettings(fakeChrome());
    expect(await settings.load()).toEqual({ theme: "light", fontSize: 16 });
  });
});

Run with npx vitest. Test the failure paths as well: a storage call that rejects, a missing key, a message with the wrong shape. See Secure messaging for the validators worth covering.

Faking events and messages

A listener is just a function. Extract it, call it directly, and pass fakes for sender and sendResponse:

JavaScript
export function onMessage(message, sender, sendResponse) {
  if (message.type === "ping") sendResponse({ pong: true });
}

it("answers ping", () => {
  let reply;
  onMessage({ type: "ping" }, {}, (r) => (reply = r));
  expect(reply).toEqual({ pong: true });
});

For larger suites, the community package sinon-chrome and jest-chrome provide ready-made chrome mocks, and Vitest's vi.stubGlobal("chrome", fake) installs a fake globally. A hand-written fake with only the functions you use is usually easier to read and keeps tests honest.

What unit tests cannot tell you

A fake does not know Chrome's real quirks: quota errors, the port-closed rule, worker shutdown. Keep the fakes simple, and cover real behaviour with a few end-to-end tests in a real browser (next lesson).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main design habit that makes extension code testable?

    Pure functions need no browser. Thin wrappers around chrome are too small to need heavy testing.
  2. 2. How does a module get a fake chrome in a test?

    Pass the API in, or use a stub such as vi.stubGlobal, so the module never touches the real object.
  3. 3. Which behaviour is a fake chrome least able to prove?

    Real-browser quirks need real-browser tests.
  4. 4. How do you test an onMessage listener?

    Listeners are ordinary functions, so call them directly with test doubles.

Summary

  • Separate pure logic from chrome calls; test the pure part.
  • Inject chrome or stub it globally with a small hand-written fake.
  • Extract listeners into functions and call them with fake arguments.
  • Remember what fakes miss, and add a few real-browser tests.

Next: End-to-End Testing in a Real Browser