npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@cultivateinc/sinon-chrome

v3.1.0

Published

Mock of chrome extensions API for unit testing under nodejs

Downloads

32

Readme

sinon-chrome

Forked from acvetkov/sinon-chrome.

npm i -D @cultivateinc/sinon-chrome

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.

Usage

For mock extensions Api

const chrome = require('@cultivateinc/sinon-chrome');

// or

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

For mock apps Api

const chrome = require('@cultivateinc/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('@cultivateinc/sinon-chrome/extensions');
const CookiePlugin = require('@cultivateinc/sinon-chrome/plugins').CookiePlugin;

chrome.registerPlugin(new CookiePlugin());

Extension namespaces

Apps namespaces

Webextensions API

Useful resources

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