Can't mock 'webextension-polyfill' for jest unit tests

Viewed 14

I am writing a browser extension for Firefox and Chrome. I use the browser.* commands and Mozilla's 'webextension-polyfill' module to make browser work in chrome. I have a file called browser.ts that contains a single line:

export const browser = require('webextension-polyfill');

which then gets used in each file like so

import {browser} from '../path/to/browser.ts'.

I want to make it so I can write unit tests, but the line require('webextension-polyfill') is causing me a headache as any test with browser throws This script should only be loaded in a browser extension and references the previous require statement.

I have tried using rewire, proxyquire, and jest mocks to avoid the require statement from being called in the unit tests, but I am not able to override it successfully. The only way I have been able to avoid this error is with a try-catch and returning a mock object on the exception, but that seems hacky and messy.

What is the best way to get around this and fix it? I see packages like mockzilla which look helpful for mocking, but I think I would use them after I can first use the require line for webextension-polyfill.

0 Answers
Related