0

我目前正在編寫谷歌瀏覽器擴展程序並使用Jasmine 1.3.0進行測試。該擴展是一個相當簡單的字典擴展,它接受用戶雙擊進行高亮顯示,將其傳遞到背景,並使某些字典調用以彈出形式顯示。現在我試圖測試背景實際上是否接收使用requireJS(http://requirejs.org/)從內容腳本傳遞的消息。我的第一個測試,即addListener被調用,通過,但隨後的測試失敗。這裏是background_spec.js:茉莉間諜返回空最mostRecentCall對象

describe("background message passing", function() { 

    beforeEach(function() { 
    chrome = { 
     runtime : { 
     onMessage : { 
      addListener : function() {} 
     } 
     } 
    } 
    spyOn(chrome.runtime.onMessage, 'addListener').andCallThrough(); 
    }); 

    it("should add a listener", function() { 
    runs(function() { 
     require(['background']); 
    }); 

    waits(100); 

    runs(function() { 
     expect(chrome.runtime.onMessage.addListener).toHaveBeenCalled(); 
    }); 
    }); 

    it("should call the listener with a function", function() { 
    runs(function() { 
     require(['background']); 
    }); 

    waits(100); 

    runs(function() { 
     expect(chrome.runtime.onMessage.addListener).toHaveBeenCalledWith(
     jasmine.any(Function)); 
    }); 
    }); 

    it("should save the input", function() { 
    runs(function() { 
     require(['background']); 
    }); 
    waits(100); 

    runs(function() { 
     var word; 
     listener = chrome.runtime.onMessage.addListener.mostRecentCall.args[0]; 
     expect(listener).toBeDefined(); 
/* 
     listener({input: "foo"}, {}, function(){}); 
     expect(word).toBeDefined(); 
     expect(word).toEqual("foo"); 
*/ 
    }); 
    }); 

}); 

第二個規格,在那裏我稱之爲haveBeenCalledWith說,addListener沒有被調用。第三個規範報告mostRecentCall.args未定義,並且它不能訪問未定義的屬性0。 (進一步調試透露,mostRecentCall返回一個空的對象。)

這裏的background.js,好措施:

var word; 
chrome.runtime.onMessage.addListener(
    function(msg, sender, sendResponse) { 
    if (msg.input) { 
     word = msg.input; 
     sendResponse({success: "Message received"}); 
    } 
}); 

如果有人可以看到我的錯誤是什麼,我會很感激的。我對Jasmine和JJ都很陌生,但我已經沒有想法去嘗試了。

+0

你可以嘗試改變測試的順序。如果第一個測試總是成功並且其他測試失敗,那麼它必須是requirejs第一次加載'background.js',然後使用已經加載的實例。 – gkalpak

+0

這很有趣。你是對的 - 第一個測試總是通過,而其他測試失敗。你知道這個問題的簡單解決方法嗎? –

+0

我對RequireJS並不是很熟悉,所以我不能提出一個合適的解決方案。但是,將RequireJS排除在外可能會有所幫助:) – gkalpak

回答

0

我使用茉莉花2.0.0,只有我做的事情是添加var到Chrome瀏覽器對象:

var chrome ; 
    beforeEach(function(){ 
     chrome = { 
      runtime : { 
       onMessage : { 
        addListener : function() {} 
       } 
      } 
     } 
     spyOn(chrome.runtime.onMessage, 'addListener').andCallThrough(); 
    }); 
+0

我試過這個解決方案,但它使所有規格都失敗。 –

+0

我剛剛加倍檢查,我無法找到它不工作的原因。 – Dalorzo