acvetkov / sinon-chrome

Testing chrome extensions with Node.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

freaktechnik opened this issue · comments

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