How to test Chrome extensions with JavaScript?

Sometimes, we want to test Chrome extensions with JavaScript.

In this article, we’ll look at how to test Chrome extensions with JavaScript.

How to test Chrome extensions with JavaScript?

To test Chrome extensions with JavaScript, we can use sinon-chrome.

For instance, we write

const vm = require("vm");
const fs = require("fs");
const chrome = require("sinon-chrome");

chrome.tabs.query.yields([
  { id: 1, title: "Tab 1" },
  { id: 2, title: "Tab 2" },
]);

const context = {
  chrome,
};

const code = fs.readFileSync("src/background.js");
vm.runInNewContext(code, context);

sinon.assert.calledOnce(chrome.browserAction.setBadgeText);
sinon.assert.calledWithMatch(chrome.browserAction.setBadgeText, {
  text: "2",
});

to mock the open tabs with

chrome.tabs.query.yields([
  { id: 1, title: "Tab 1" },
  { id: 2, title: "Tab 2" },
]);

Then we inject the mocked chrome.* API into the environment with

const context = {
  chrome,
};

And then we run the extension with

const code = fs.readFileSync("src/background.js");
vm.runInNewContext(code, context);

Finally, we do the assertions with

sinon.assert.calledOnce(chrome.browserAction.setBadgeText);
sinon.assert.calledWithMatch(chrome.browserAction.setBadgeText, {
  text: "2",
});

Conclusion

To test Chrome extensions with JavaScript, we can use sinon-chrome.