Testing your web extension with integration tests

Testing your web extension with integration tests

<strong>It is often described how to do unit tests for web extensions but hardly said how to do integration tests. Here, I am presenting the method to embed a Jasmine HTML page inside a page of your web extension.</strong>

It is often described how to do unit tests for web extensions but hardly said how to do integration tests. Here, I am presenting the method to embed a Jasmine HTML page inside a page of your web extension.

The need of testing

Testing is a core strategy in software development. It helps the developer to keep knowledge about the app and guarantee the code and the features keep their engagement.

When I started the extension Sync Tab Groups, I first tested it manually. While it was working for the first weeks, I quickly felt I was losing time and getting less confident about each release. The day I released a critical bug was the signal.

Although pretty easy for testing React or Node, the web extension ecosystem is younger and less rich. The best approach, I found so far, is to mock the tests with sinon and run them in a DOM emulation (Jest for example).

I decline this solution for 2 reasons:

1. The library is not complete for Chrome and definitely lacks some Firefox specific features

2. Mocked tests are useful and fast but not as safe as the integration tests

Finally, by looking at the Jasmine library, I discovered I could embed my tests in an HTML page.

How to embed tests in a web extension page

In a web extension, the extension API is available on different parts

1. In your background task

2. On your extension pages

I started my small test library in the background task. I stopped immediately. Not only coding a library is tough but lacking a nice interface made it hard to iterate.

I quickly switched to the extension pages with the support of the Jasmine library. I downloaded all the HTML, JS and CSS files and added all my tests in “describe” and “it” blocks in the imported JS files.

In a later version, I will use Webpack to create the test page. On one side, I will build a single JavaScript file with all the tests inside. And on the other side, I will fetch the Jasmine assets directly from the “node_modules/” folder. I am going to write another article on how to build a web extension with Webpack soon.


How to design your tests

While the concept is simple, I iterated regularly in order to improve the testing experience.

Bind the web page to the background script

By default, the web extension doesn’t access the full web extension API. A solution is to require the background window where the core of the extension is running.

Be careful, the function is asynchronous, thus, you should wait before executing any tests. When I added the Chrome support on Sync Tab Groups, at first I forgot to wait. As a consequence, the tests were randomly failing.

const waitInit = async() => {
  const Background = await browser.runtime.getBackgroundPage();
  // Available everywhere
  window.Background = Background
}()

// Store the original start function from Jasmine const currentWindowOnload = window.onload;

// Overload the event to first get the background window.onload = async function() { await waitInit;

if (currentWindowOnload) { currentWindowOnload(); } };

Note: all the code available in the article is coming from the Sync Tab Groups repository.

Mock the timers

The window functions (“setTimeout”…) in the page are not the same than the ones in your background script. If you want to mock the time, you should modify the ones in the background object with the Jasmine mocked functions.

const TIME_OBJECTS = [
  "setTimeout",
  "setInterval",
  "clearTimeout",
  "clearInterval",
  "Date",
]

const savedTime = {}; function installFakeTime() { if (!Object.keys(savedTime).length) { // Call Jasmine to mock the timer functions in the current window object jasmine.clock().install(); jasmine.clock().mockDate(); savedTime = {}; // Replace the background objects with the mocked versions TIME_OBJECTS.forEach((time)=>{ savedTime[time] = window.Background[time]; window.Background[time] = window[time]; }); } }

function uninstallFakeTime() { if (Object.keys(savedTime).length) { jasmine.clock().uninstall(); Object.assign(window.Background, savedTime); savedTime = {}; } }

Improve the test experience

One of the first pain I got was caused by the tests starting automatically each time the page was loaded. A solution is to overwrite the filter with a string that won’t match any test title. The filter is overwritten dynamically in order to not have strange URLs.

My second pain was to list all the tests. By using the previous solution that stops the test execution, you set the enable parameter to false. If you set to empty the URL spec parameter, then all the tests are listed in light gray. If the spec parameter is not empty, the page will only list the test titles that matched it.

const queryString = new jasmine.QueryString({
  getWindowLocation: function() {
    return window.location;
  },
});

const specFilter = new jasmine.HtmlSpecFilter({ filterString: function() { if (getUrlParameterValueByName("enable") !== 'true') { // A fake string that matches no test return "@@@@@@@"; } else { // Normal behavior: "spec" value is a regex to filter the test names return queryString.getParam("spec") } }, });

const env = jasmine.getEnv(); env.specFilter = function(spec) { return specFilter.matches(spec.getFullName()); };

This small interface on top of the Jasmine page helps to control the tests. By clicking on the “Enable” button the tests are executed on the next page refresh. Whereas “See all tests” button disables the test execution (the enable parameter to false) and resets the filter (the spec parameter to the empty value).

// Enable button: execute or not the tests on page load
// If not, ALL the tests are displayed in light gray
// Use a trick that jasmine won't execute nothing if the URL spec parameter is empty
const enableButton = document.createElement("button");
enableButton.innerText = Utils.getParameterByName("enable") === 'true'
  ? "Disable"
  : "Enable";
enableButton.addEventListener("click", () => {
  if (Utils.getParameterByName("enable") === 'true') {
    // Set (add) a parameter "key" in the URL with the value
    // @example ("k", "val") => http://www.site.fr/?k=val
    // @source https://stackoverflow.com/a/487049/7186064 
    insertParam("enable", "false");
  } else {
    insertParam("enable", "true");
  }
})

// Add the buttons when the page is loaded document.addEventListener("DOMContentLoaded", () => { // I added this code in the body tag of the HTML page // <h3>Test page</h3> // <button><a href="?spec=">See all tests</a></button> document.body.insertBefore(enableButton, document.querySelector("button")); const div = document.createElement('div'); div.innerText = Filter: "${Utils.getParameterByName("spec")}"; document.body.insertBefore(div, enableButton); });

Automatically open the page

Extension pages have often strange and unpredictable URLs. On top of that, they close each time you reload your extension. A nice solution is to add a system to automatically open pages when the extension starts (in the development mode of course). The web extension API provides a function to open a page from a local path without knowing the extension id.

const DEV_TABS = [
  // tests pages
  "/tests/test-page/unit.html",
  "/tests/test-page/integration.html",
  // options
  "/options/option-page.html#settings",
  // test page with a specific test targeted in spec
  "/tests/test-page/integration.html?spec=Selector%20-%20",
]

// To execute when the extension is detected to be in developement mode function onDevelopmentInstall() { // Open the tabs DEV_TABS.forEach((url)=>{ browser.tabs.create({ active: false, url: browser.extension.getURL(url), }); });

// Add extra code you want to be done in Development }

It is easy to detect when the extension is under development thanks to the “temporary” property in Firefox. For Chrome, an alternative method based on the values of some fields is necessary as the “temporary” field is missing. Although it works, it shows a reality, Firefox works harder to make the extension developer life easier than with Chrome.

browser.runtime.onInstalled.addListener((details) => {
  if (details.reason === "install") {
    // Extension has been installed (first time only)
  } else if (
      (Utils.isFirefox() && details.temporary)
      || (Utils.isChrome() && details.reason === "update" 
           && (browser.runtime.getManifest()).version === details.previousVersion
         )
    ) {
    // Extension has been reloaded in development
  } else if (details.reason === "update"
      && (browser.runtime.getManifest()).version !== details.previousVersion) {
    // Extension has been updated to a new version
  }
});

Use mocked tabs

When I first did my tests, I was using a random pool of real URLs for the tabs in my groups. When the number of the tests increased significantly, the test suite was taking longer and my computer was over computing.

Actually, loading a tab in your browser is an expensive task because of the graphical resources and the scripts (tracking, page interactions…). On top of that, if they open by ten without letting time for your computer to finish, the navigation is getting horrible.

A new solution using a custom (empty) web extension page solves the issue. It has 2 advantages:

  1. The tab is lighter to load (no images, no JavaScript)
  2. It is local to the extension, thus there is no network time

For some tests you want to differentiate the pages to know if a specific page does something. As the extension can’t change the HTML content at opening, you could use an URL parameter set with a random number. Be careful, it might have number collision leading to random failing tests. A better solution would be to store the number to avoid using a number more than one.

Since the mock tabs don’t use the network, it allows to develop the extension without an internet connection. A great improvement to code even on the train!

/**

  • Return an url to a web extension page with a minimal body
  • The URL is personalized with a number set to the parameter test
  • */ function getFakeUrl(random=String(getRandom(0,999999999))) { return browser.extension.getURL("/tests/test-page/template/template.html")
      + "?test=" + random;
    }

/**

  • Return a light local tab in the web extension
  • with a personalized URL to recognize them
  • / function getFakeTab() { const random = String(getRandom(0,999999999)); // Return a minimalist tab return createTab({ url: getFakeUrl(random), title: random, favIconUrl: "", }) }

Create your toolbox to control the browser

As the tests are running inside the UI browser, it might get difficult to follow the current test execution for debugging. For example, you might wish to look at the test states to know if some tests have already failed or how close the tests are from the end.

Another problem exists if you test features that use more than one browser window. You want to visualize the test running in all the browser windows to check everything is going well while you are writing it.

<img src="https://cdn-images-1.medium.com/max/1600/1GCh8oXF3UNGKekTnjbaxVA.png">

It is easy to use some web extension functions to resize the browser windows to fit better in the screen. You could change manually the setting to fit a single or double screen configuration.

async function splitOnHalfScreen(windowId) {
try {
  return browser.windows.update(windowId, {
left: TestUtils.DOUBLE_MONITORS?window.screen.width:0,
top: 3,
width: Math.round(window.screen.width/2),
height: window.screen.height,
state: "normal",
}); } catch (e) { window.Background.LogManager.error(e, {args: arguments}, {logs: null}); } }

And some insoluble problems…

Whereas it is easy now to test a web extension with integration tests, some behaviors are still problematic

  • Some tests are failing in the Mac full screen mode (no idea why)
  • While the tests are running, you might not be able to use your computer as changing the focus could make the tests failing

Improvement ideas

I just want to share with you some improvements I never tried because I run out of time.

Headless Browser

A pain that still remain is that during the tests my computer is unavailable. I read some things about seleniumpuppeter and Firefox Headless mode. However, I never tried! Also, the Firefox “web-ext” tool could even be a solution to do continuous integration.

Remote testing

I studied another solution I was never able to implement. Mocha is a server for sharing your tests in the browser.

It works by opening a local server that gets connected by the browser in a tab. By continuously exchanging, the Mocha server is sending the tests are waiting for the responses.

The reason I gave up this solution, was due to the tab page was targeting the localhost and thus wasn’t an extension page. This involves you got access only to a limited part of the API (not to the background script).

Conclusion

By embedding the Jasmine test page into your web extension, you could use the agility of a test framework with the full power of the web extension API.

In my project Sync Tab Groups, I was able to ensure all my features were truly working on the new releases. Independently of knowing if the web extension in the browser was changing. I used to release many times a week when I was only working on this project without regression.

By the way, I am still looking for contributors to help me developing Sync Tab Groups. :)

Originally published by Eric Masseran at https://medium.com/@Morikko/testing-your-web-extension-with-integration-tests-f875f1f52ff9

Follow great articles on Twitter

Learn More

☞ The Web Developer Bootcamp

☞ Angular 7 (formerly Angular 2) - The Complete Guide

☞ Learn and Understand AngularJS

☞ The Complete JavaScript Course: Build a Real-World Project

☞ Become a JavaScript developer - Learn (React, Node,Angular)

☞ Build Responsive Real World Websites with HTML5 and CSS3

☞ Web Design for Beginners: Real World Coding in HTML & CSS

☞ React 16 - The Complete Guide (incl. React Router 4 & Redux)

☞ The Complete Node.js Developer Course (2nd Edition)

☞ MERN Stack Front To Back: Full Stack React, Redux & Node.js

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

For World Class Web Development Services in India visit RB Genie

Do you want excellent and world class web development services for your valuable projects? Contact **RB Genie **now, we have more than 8 years experienced team of web developers, which specializes in overall web design and website development...