acvetkov / sinon-chrome

Testing chrome extensions with Node.js
ISC License
435 stars 46 forks source link

Easier testing with browser.runtime.connect/browser.runtime.connectNative #50

Open freaktechnik opened 7 years ago

freaktechnik commented 7 years ago

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.

ddehghan commented 5 years ago

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());