Introducing mockzilla and mockzilla-webextension for easy web-extension testing with jest

Background:

I’m currently in the process of heavily rewriting my web-extension forget-me-not.

I already have over 300 tests in place, but more are expected to come, and my old approach of creating a simulation of a browser was not something I wanted to keep maintaining, especially since that approach made it hard to cover all the different browser targets.

When I was in london last year to meet with Mozilla and other extension developers, I received a lot of questions on how I test my web-extensions. Back then I had to tell them, that most of the stuff I do is custom-tailored to my extensions need.

Trying to Find a Better Solution

I lately switched most of my other TypeScript projects to tests with jest, so I thought it might be a good idea to use jest for forget-me-not as well.

With jest you can mock entire npm packages. But it’s not very comfortable to use for a deeply nested API like browser.

Some time ago I had a deeper look at the js Proxy class and it seemed like a good choice to dynamically create mocks on the fly.

With the addition of the types from the webextension-polyfill-ts project and some TypeScript-Fu, I was able to create a deep-mocking library, which makes mocking quite simple.

Resulting Projects

mockzilla is the first project that came out of this. This project is generic and has no ties to web-extensions. So you can use this for any API you want!

mockzilla-webextension makes use of mockzilla to provide a global mockBrowser object (to declare expectations) and automatically provide a global browser mock instance as well (which your logic will use). It also provides a helper to make mocking and testing events easier.

Feedback

While I’m still in the process of finding out how I want my tests to work, I would like to gather some feedback from you to see if you have any additions or criticism on some of the approaches.

Additionally it would be awesome if there are developers who would be willing to contribute to these projects.

Cheers

4 Likes