serv-inc
serv-inc

Reputation: 38247

Unit Test WebExtensions

How do you unit test web extensions?

For older Firefox extensions, the deprecated jpm tool had a jpm test command, which ran unit tests on methods exported from the .js files. Is this anyhow possible with web-ext? Or by hand? How about Google Chrome Extensions?

As an example, take the following background.js:

function redirect(requestDetails) {
    console.log("Redirecting: " + requestDetails.url);
    return { redirectUrl: requestDetails.uri + '&helloworld'};
}

chrome.webRequest.onBeforeRequest.addListener(
    redirect,
    {urls: ["<all_urls>"]}
);

How to test redirect()?

Update: https://github.com/google/gjstest might be used for this. I have not gotten around to using it, though.

Update: after the answer, it seems as though Mocha might work more easily than Jasmine.

Upvotes: 3

Views: 704

Answers (1)

serv-inc
serv-inc

Reputation: 38247

While gjstest looks promising, you need to recompile the v8-engine on everything except OS X, which might be too cumbersome for a general solution.

Jasmine is easy to set up.

  1. download from https://github.com/jasmine/jasmine/releases, f.ex. https://github.com/jasmine/jasmine/releases/download/v2.5.2/jasmine-standalone-2.5.2.zip
  2. unzip this zip file to separate directory, f.ex. addon-dir/test
  3. alter SpecRunner.html, replace

    <script src="src/Player.js"></script>
    <script src="src/Song.js"></script>
    

    with

    <script src="path/to/background.js"></script
    

    and replace

    <script src="spec/SpecHelper.js"></script>
    <script src="spec/PlayerSpec.js"></script>
    

    with

    <script src="spec/AddonSpec.js"></script>
    
  4. create the file spec/AddonSpec.js, with content

    describe("Addon", function() {
        it("should append hello world", function() {
            let details = {uri: "google.de/q=test"};
    
            expect(redirect(details)).toEqual(details.uri + "&helloworld");
        });
    });
    
  5. open the file SpecRunner.html in the browser of your choice.

Upvotes: 1

Related Questions