如何测试在Chrome扩展中使用Jasmine打开新标签

How to test opening new tab with Jasmine in Chrome extension?

本文关键字:Jasmine 新标签 标签 扩展 何测试 测试 Chrome      更新时间:2023-09-26

我正在构建chrome扩展,我在让测试按我希望的方式运行时遇到了一些问题。我只需转到扩展url ending tests.html即可访问此页面。

假设我想测试以下非常简单的场景:新的选项卡在chrome中打开并加载,我的扩展检测到该事件,新的选项卡添加到我的应用程序中的选项卡阵列中。我把所有的Jasmine测试都放在一个单独的扩展页面上。

我尝试了以下几件事,但都失败了。

第一,尝试用一些Timeout(加载页面所需的)来调用Jasmine"expect"。

describe("Tab collection", function () {
    it("after opening new tab it should be in app.tabs", function () { 
        chrome.tabs.create({"url":"http://www.google.com"});
        setTimeout(function () {
            expect(app.tabs.length).toBe(1);
            console.log("app.tabs.length after timeout", app.tabs.length);
        },100);
    });

Console.log不记录任何内容,测试是绿色的,甚至很难,很明显它没有运行。

第二,尝试在chrome.tabs.create回调函数中运行"expect"。

    it("after opening new tab it shoule be in app.tabs", function () {
        chrome.tabs.create({"url":"http://www.google.com"}, function () {
            expect(app.tabs.length).toBe(1); //
            console.log("app.tabs.length in callback to chrome.tabs.create",app.tabs.length); 
        })
    });
});

Console.log记录0,但由于某些原因,测试通过。如果app.tabs.length为0,为什么会通过?

第三个场景涉及在打开新的chrome选项卡后运行我的所有测试

chrome.tabs.open({some_url},function (tab) {
    execJasmine()
    chrome.tabs.remove(tab['id'])
})

这是可行的,但非常不方便,我所有的测试现在都用这个打开的选项卡运行。它实际上不允许我测试东西。

第四,我试着用Jasmine BeforeEach 做这件事

beforeEach(function () {
    chrome.tabs.create(some_url);
}); 

这最接近正常,但现在测试失败,app.tabs.length为0,因为调用测试套件时尚未加载页面。

有人遇到类似的问题吗?如何测试描述的场景?

您的测试是同步的。您必须在it的回调中声明第二个参数才能使测试异步:

describe("Tab collection", function () {
    it("after opening new tab it should be in app.tabs", function(done) {
        //                                                        ^^^^
        chrome.tabs.create({"url":"http://www.google.com"}, function() {
            expect(app.tabs.length).toBe(1);
            console.log("app.tabs.length after timeout", app.tabs.length);
            done(); // <------
        });
    });
    // ...
});