acvetkov / sinon-chrome

Testing chrome extensions with Node.js
ISC License
439 stars 48 forks source link
chrome chrome-api chrome-events javascript sinon-chrome

Build Status npm version

Sinon-chrome

Sinon-chrome is helper tool for unit-testing chromium and Firefox extensions and apps. It mocks all extensions api with sinon stubs that allows you to run tests in Node.js without actual browser.

Schema support

API mocks are generated using official chromium extensions API (Firefox webextensions) schemas that ensures consistency with real API. Actual schemas are taken from Chrome 53 and Firefox 49.

How it works

Sinon-chrome mocks all chrome api, replaced methods by sinon stubs with some sugar. Chrome events replaced by classes with same behavior, so you can test your event handlers with manual triggering chrome events. All properties has values from chrome schema files.

Install

We recommend use sinon-chrome on Node.js platform.

npm install sinon-chrome --save-dev

But, if you want...

You can download sinon-chrome bundle from release page and include it on your page

<script src="https://github.com/acvetkov/sinon-chrome/raw/master/path/to/sinon-chrome.min.js">

or

<script src="https://github.com/acvetkov/sinon-chrome/raw/master/path/to/sinon-chrome-apps.min.js">

Usage

For mock extensions Api

const chrome = require('sinon-chrome');

// or

const chrome = require('sinon-chrome/extensions');

For mock apps Api

const chrome = require('sinon-chrome/apps'); // stable apps api

Examples

Let's write small navigation helper, which use chrome api methods.

export const navigationTarget = {
    NEW_WINDOW: 'new-window',
    NEW_TAB: 'new-tab',
    CURRENT_TAB: 'current-tab',
};

/**
 * Navigate user
 * @param {String} url
 * @param {String} [target]
 * @returns {*}
 */
export function navigate(url, target = navigationTarget.NEW_TAB) {
    switch (target) {
        case navigationTarget.NEW_WINDOW:
            return chrome.windows.create({url: url, focused: true, type: 'normal'});
        case navigationTarget.CURRENT_TAB:
            return chrome.tabs.update({url: url, active: true});
        default:
            return chrome.tabs.create({url: url, active: true});
    }
}

Test it

import chrome from '../src'; // from 'sinon-chrome'
import {assert} from 'chai';
import {navigate, navigationTarget} from './navigate';

describe('navigate.js', function () {

    const url = 'http://my-domain.com';

    before(function () {
        global.chrome = chrome;
    });

    it('should navigate to new window', function () {
        assert.ok(chrome.windows.create.notCalled, 'windows.create should not be called');
        navigate(url, navigationTarget.NEW_WINDOW);
        assert.ok(chrome.windows.create.calledOnce, 'windows.create should be called');
        assert.ok(
            chrome.windows.create.withArgs({url, focused: true, type: 'normal'}).calledOnce,
            'windows.create should be called with specified args'
        );
    });
});

You can run this example by command

npm run test-navigate

More tests in examples dir.

stubs api

With original sinon stubs api we add flush method, which reset stub behavior. Sinon stub has same method resetBehavior, but it has some issues.

Example

chrome.cookie.getAll.withArgs({name: 'my_cookie'}).yields([1, 2]);
chrome.cookie.getAll.withArgs({}).yields([3, 4]);

chrome.cookie.getAll({}, list => console.log(list)); // [3, 4]
chrome.cookie.getAll({name: 'my_cookie'}, list => console.log(list)); // [1, 2]
chrome.cookie.getAll.flush();
chrome.cookie.getAll({name: 'my_cookie'}, list => console.log(list)); // not called
chrome.cookie.getAll({}, list => console.log(list)); // not called

events

Let's write module, which depends on chrome events

export default class EventsModule {
    constructor() {
        this.observe();
    }

    observe() {
        chrome.tabs.onUpdated.addListener(tab => this.handleEvent(tab));
    }

    handleEvent(tab) {
        chrome.runtime.sendMessage(tab.url);
    }
}

And test it

import chrome from '../src'; // from 'sinon-chrome'
import {assert} from 'chai';
import EventsModule from './events';

describe('events.js', function () {

    before(function () {
        global.chrome = chrome;
        this.events = new EventsModule();
    });

    beforeEach(function () {
        chrome.runtime.sendMessage.flush();
    });

    it('should subscribe on chrome.tabs.onUpdated', function () {
        assert.ok(chrome.tabs.onUpdated.addListener.calledOnce);
    });

    it('should send correct url on tabs updated event', function () {
        assert.ok(chrome.runtime.sendMessage.notCalled);
        chrome.tabs.onUpdated.dispatch({url: 'my-url'});
        assert.ok(chrome.runtime.sendMessage.calledOnce);
        assert.ok(chrome.runtime.sendMessage.withArgs('my-url').calledOnce);
    });

    after(function () {
        chrome.flush();
        delete global.chrome;
    });
});

You can run this test via

npm run test-events

properties

You can set property values. chrome.flush reset properties to default values (null or specified by schema). Let's create module, which wraps chrome api with Promise. If chrome.runtime.lastError is set, promise will be rejected.

export const api = {
    tabs: {
        /**
         * Wrapper for chrome.tabs.query
         * @param {Object} criteria
         * @returns {Promise}
         */
        query(criteria) {
            return new Promise((resolve, reject) => {
                chrome.tabs.query(criteria, tabs => {
                    if (chrome.runtime.lastError) {
                        reject(chrome.runtime.lastError);
                    } else {
                        resolve(tabs);
                    }
                });
            });
        }
    }
};

And our tests

import chrome from '../src'; // from 'sinon-chrome'
import chai from 'chai';
import {api} from './then-chrome';
import chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);
const assert = chai.assert;

describe('then-chrome.js', function () {

    before(function () {
        global.chrome = chrome;
    });

    beforeEach(function () {
        chrome.flush();
    });

    it('should reject promise', function () {
        chrome.tabs.query.yields([1, 2]);
        chrome.runtime.lastError = {message: 'Error'};
        return assert.isRejected(api.tabs.query({}));
    });

    it('should resolve promise', function () {
        chrome.runtime.lastError = null;
        chrome.tabs.query.yields([1, 2]);
        return assert.eventually.deepEqual(api.tabs.query({}), [1, 2]);
    });

    after(function () {
        chrome.flush();
        delete global.chrome;
    });
});

You can run this test via

npm run test-then

Plugins

Sinon chrome module supports plugins, that emulates browser behavior. More info on example page.

const chrome = require('sinon-chrome/extensions');
const CookiePlugin = require('sinon-chrome/plugins').CookiePlugin;

chrome.registerPlugin(new CookiePlugin());

Extension namespaces

Apps namespaces

Webextensions API

Any questions?

Feel free to open issue.

Useful resources

Awesome Browser Extensions And Apps - a curated list of awesome resources for building browser extensions and apps.