sinon-chrome
sinon-chrome copied to clipboard
Easier testing with browser.runtime.connect/browser.runtime.connectNative
The stubs currently don't return any value by default, which is fine in general, but connect/connectNative return a Port instance. It'd be nice if there was an easy way to get a prepared Port object, since this package already has much of the infrastructure for the events.
After a lot of waisting time i managed to get this work. Put that in your test.ts in an angular app. Or some other setup environment file if you are using a different framework.
import * as chrome from 'sinon-chrome';
(window as any).global.chrome = chrome;
/*
Mock-implementation of chrome.runtime messaging API
*/
const Messager = () => {
const _listeners = [];
return {
onMessage: {
addListener: cb => _listeners.push(cb)
},
onDisconnect: {
addListener: cb => {}
},
postMessage: data => {
_listeners.forEach(cb => cb.call(this, data));
}
};
};
chrome.runtime.connect.returns(Messager());