How to test chrome extensions?

前端 未结 6 1160
别那么骄傲
别那么骄傲 2020-12-07 07:03

Is there a good way to do this? I\'m writing an extension that interacts with a website as a content script and saves data using localstorage. Are there any tools, framework

6条回答
  •  太阳男子
    2020-12-07 07:19

    Working on several chrome extensions I came up with sinon-chrome project that allows to run unit-tests using mocha, nodejs and phantomjs.

    Basically, it creates sinon mocks of all chrome.* API where you can put any predefined json responses.

    Next, you load your scripts using node's vm.runInNewContext for background page and phantomjs for render popup / options page.

    And finally, you assert that chrome api was called with needed arguments.

    Let's take an example:
    Assume we have simple chrome extension that displays number of opened tabs in button badge.

    background page:

    chrome.tabs.query({}, function(tabs) {
      chrome.browserAction.setBadgeText({text: String(tabs.length)});
    });
    

    To test it we need:

    1. mock chrome.tabs.query to return predefined response, e.g. two tabs.
    2. inject our mocked chrome.* api into some environment
    3. run our extension code in this environment
    4. assert that button badge equals to '2'

    The code snippet is following:

    const vm = require('vm');
    const fs = require('fs');
    const chrome = require('sinon-chrome');
    
    // 1. mock `chrome.tabs.query` to return predefined response 
    chrome.tabs.query.yields([
      {id: 1, title: 'Tab 1'}, 
      {id: 2, title: 'Tab 2'}
    ]);
    
    // 2. inject our mocked chrome.* api into some environment
    const context = {
      chrome: chrome
    };
    
    // 3. run our extension code in this environment
    const code = fs.readFileSync('src/background.js');
    vm.runInNewContext(code, context);
    
    // 4. assert that button badge equals to '2'
    sinon.assert.calledOnce(chrome.browserAction.setBadgeText);
    sinon.assert.calledWithMatch(chrome.browserAction.setBadgeText, {
      text: "2"
    });
    

    Now we can wrap it into mocha's describe..it functions and run from terminal:

    $ mocha
    
    background page
      ✓ should display opened tabs count in button badge
    
    1 passing (98ms)
    

    You can find full example here.

    Additionally, sinon-chrome allows to trigger any chrome event with predefined response, e.g.

    chrome.tab.onCreated.trigger({url: 'http://google.com'});
    

提交回复
热议问题