单元测试 WebExtensions

Unit Test WebExtensions

如何对网络扩展进行单元测试?

对于较旧的 Firefox 扩展,已弃用的 jpm 工具有一个 jpm test 命令,该命令 运行 对从 .js 文件导出的方法进行单元测试。 web-ext 有可能吗?还是用手? Google Chrome 扩展怎么样?

举个例子background.js:

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

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

如何测试redirect()

更新https://github.com/google/gjstest 可能用于此。不过,我还没有开始使用它。

更新: 回答后,似乎 Mocha 可能比 Jasmine 更容易工作。

虽然 gjstest 看起来很有前途,但您需要在除 OS X 之外的所有内容上重新编译 v8 引擎,这对于通用解决方案来说可能太麻烦了。

Jasmine 很容易设置。

  1. 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. 下载
  3. 将此 zip 文件解压缩到单独的目录,f.ex。 addon-dir/test
  4. 改变SpecRunner.html,替换

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

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

    并替换

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

    <script src="spec/AddonSpec.js"></script>
    
  5. 创建文件 spec/AddonSpec.js,内容为

    describe("Addon", function() {
        it("should append hello world", function() {
            let details = {uri: "google.de/q=test"};
    
            expect(redirect(details)).toEqual(details.uri + "&helloworld");
        });
    });
    
  6. 在您选择的浏览器中打开文件 SpecRunner.html