Welcome What's new in Chrome extensions API reference Samples
Welcome What's new in Chrome extensions API reference Samples

Unit testing Chrome Extensions

Published on

Unit testing allows small sections of code to be tested in isolation from the rest of your extension, and outside of the browser. For example, you could write a unit test to ensure that a helper method correctly writes a value to storage.

Code written without using extension APIs can be tested as normal, using a framework such as Jest. To make code easier to test this way, consider using techniques such as dependency injection which can help to remove dependencies on the chrome namespace in your lower level implementation.

If you need to test code which includes extension APIs, consider using mocks.

Example: Using mocks with Jest

Create a jest.config.js file, which declares a setup file that will run before all tests:


module.exports = {
setupFiles: ['<rootDir>/mock-extension-apis.js']

In mock-extension-apis.js, add implementations for the specific functions you expect to call:


global.chrome = {
tabs: {
query: async () => { throw new Error("Unimplemented.") };

Then, use jest.spy to mock a return value in a test:

test("getActiveTabId returns active tab ID", async () => {
jest.spyOn(chrome.tabs, "query").mockResolvedValue([{
id: 3,
active: true,
currentWindow: true
expect(await getActiveTabId()).toBe(3);

Next steps

To ensure your extension functions as expected, we recommend adding end-to-end tests. See Testing Chrome Extensions with Puppeteer for a complete tutorial.

Published on Improve article

This site uses cookies to deliver and enhance the quality of its services and to analyze traffic. If you agree, cookies are also used to serve advertising and to personalize the content and advertisements that you see. Learn more about our use of cookies.