Web Extensions
JavaScript in-memory replacement for Web Extensions API. This is in very early stages and I'm updating it as I need to test an extension I'm developing.
Background
Have you ever needed to create a testable browser extension but couldn't find an easy way to mock the browser API? This extension creates a fake browser instance that you can easily pass around in your tests.
Installation
$ yarn add web-extensions --dev
Usage
Require the Web Extensions implementation for the browser you're developing and pass it around. For example, if you're developing an extension for Google Chrome:
// Import the mock Chrome class // Create an instance of the mockconst chrome = // Use it like you were using the real APIchromebrowserAction
You can do the same if you're developing an extension for Edge, Firefox, Firefox for Android and Opera. Here is an example for Firefox:
// Import the mock browser class // Create an instance of the mockconst browser = // Use it like you were using the real APIbrowserbrowserAction
Testing
Inside your extension, the global variable chrome
/browser
is available globally. In tests, however,
it is undefined
. There are two ways to overcome this. You can architecture your extension to use dependency
injection, or you can mock the global variable if your testing framework has those capabilities.
Dependency Injection
Suppose that you have a class responsible for managing the extension's UI:
{ thisbrowserAction = chromebrowserAction } { thisbrowserAction }
In your code, you could easily instantiate that class with the global variable chrome
, because it is natively
available:
const ui = chrome // chrome is a global variable provided by Google Chromeui
To test that class, you would need to inject an instance of the mock to its constructor:
const mockChrome = const ui = mockChrome ui
Globals
Jest provides an API to resolve global variables. You can declare chrome
as a
mock:
// inside your test file const mockChrome = globalchrome = mockChrome
Assertions
Every API stores the internal data in a variable called mockData
. It can be used to perform assertions. For example,
suppose you're testing a function that sets the browser action's title.
const mockChrome = const ui = mockChrome
Contributing
Contributions are very welcome. I have implemented the mocks for what I needed, but feel free to look at the CHANGELOG and implement the remaining APIs.
- Fork it!
- Create your feature branch:
git checkout -b my-new-feature
- Commit your changes:
git commit -am 'Add some feature'
- Push to the branch:
git push origin my-new-feature
- Submit a pull request
Versioning
The project uses SemVer for versioning. For the versions available, see the tags on this repository.