All Projects → acvetkov → Sinon Chrome

acvetkov / Sinon Chrome

Licence: isc
Testing chrome extensions with Node.js

Programming Languages

javascript
184084 projects - #8 most used programming language

Labels

Projects that are alternatives of or similar to Sinon Chrome

Upnext
Chrome Extension for streaming music from SoundCloud & YouTube
Stars: ✭ 320 (-16.88%)
Mutual labels:  chrome
Bilibili Helper O
哔哩哔哩 (bilibili.com) 辅助工具,可以替换播放器、推送通知并进行一些快捷操作
Stars: ✭ 3,717 (+865.45%)
Mutual labels:  chrome
Epub Press Clients
📦 Clients for building books with EpubPress.
Stars: ✭ 370 (-3.9%)
Mutual labels:  chrome
Melonjs
a fresh & lightweight javascript game engine
Stars: ✭ 3,721 (+866.49%)
Mutual labels:  chrome
Surfingkeys
Map your keys for web surfing, expand your browser with javascript and keyboard.
Stars: ✭ 3,787 (+883.64%)
Mutual labels:  chrome
Extanalysis
Browser Extension Analysis Framework - Scan, Analyze Chrome, firefox and Brave extensions for vulnerabilities and intels
Stars: ✭ 351 (-8.83%)
Mutual labels:  chrome
React Scope
Visualize your React components as you interact with your application.
Stars: ✭ 316 (-17.92%)
Mutual labels:  chrome
Android Customtabs
Chrome CustomTabs for Android demystified. Simplifies development and provides higher level classes including fallback in case Chrome isn't available on device.
Stars: ✭ 378 (-1.82%)
Mutual labels:  chrome
Headereditor
Manage browser's requests, include modify the request headers and response headers, redirect requests, cancel requests
Stars: ✭ 338 (-12.21%)
Mutual labels:  chrome
Reason Tools
Adds Reason to the browser
Stars: ✭ 366 (-4.94%)
Mutual labels:  chrome
Copy As Markdown
Copying Link, Image and Tab(s) as Markdown Much Easier.
Stars: ✭ 332 (-13.77%)
Mutual labels:  chrome
Leethub
Automatically sync your leetcode solutions to your github account - top 5 trending GitHub repository
Stars: ✭ 316 (-17.92%)
Mutual labels:  chrome
History Master
📈📉📊A Firefox/Chrome extension to visualize browsing history, sync among different browsers!
Stars: ✭ 356 (-7.53%)
Mutual labels:  chrome
Chrome Headless Browser Docker
Continuously building Chrome Docker image for Linux.
Stars: ✭ 323 (-16.1%)
Mutual labels:  chrome
Undetected Chromedriver
Custom Selenium Chromedriver | Zero-Config | Passes ALL bot mitigation systems (like Distil / Imperva/ Datadadome / CloudFlare IUAM)
Stars: ✭ 365 (-5.19%)
Mutual labels:  chrome
Upme Plus
Smart Automation inside your browser for free. Start earning and double your followers
Stars: ✭ 318 (-17.4%)
Mutual labels:  chrome
Chrome Charset
An extension used to modify the page default encoding for Chromium 55+ based browsers.
Stars: ✭ 346 (-10.13%)
Mutual labels:  chrome
Nightmare
A high-level browser automation library.
Stars: ✭ 19,067 (+4852.47%)
Mutual labels:  chrome
T Rec Rs
Blazingly fast terminal recorder that generates animated gif images for the web written in rust
Stars: ✭ 361 (-6.23%)
Mutual labels:  chrome
Webextension Toolbox
Small CLI toolbox for cross-browser WebExtension development
Stars: ✭ 365 (-5.19%)
Mutual labels:  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="/path/to/sinon-chrome.min.js">

or

<script src="/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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].