2014-03-18 52 views
3

我正在使用AngularJS開發Chrome應用程序。正如我的應用程序使用chrome.storage我寫的包裝:測試Chrome存儲API封裝器

angular.module('myApp').factory('chromeStorageApi', function($window){ 
    if(typeof $window.chrome.storage == 'undefined') 
    return false; 

    return{ 
     set:function(obj, callback){ 
      $window.chrome.storage.local.set(obj, callback) 
      return true; 
     }, 
     ............................. 
    } 
} 

我違反TDD方法,現在我想測試我的包裝。但是我所有的嘗試都沒有成功。我試圖檢查,例如,$window.chrome.storage.local.set()chromeStorageApi.set()具有相同的參數,但我無法找到一種方法,我可以模擬$window.chrome.storage.local

更新:

我的單元測試的最後一個版本:

describe('chromeStorageApi', function(){ 

    beforeEach(module('myApp')); 

    it('should be able to set data to the storage', inject(function(chromeStorageApi, $window){ 
     spyOn($window.chrome.storage.local, 'set') 
     chromeStorageApi.set({'key':'value'}, function(){ }()); 
     expect($window.chrome.storage.local.set).toHaveBeenCalled(); 
     expect($window.chrome.storage.local.set).toHaveBeenCalledWith({'key':'value'}, function(){ }()); 

    })); 
}); 

但我得到一個錯誤:

TypeError: 'undefined' is not an object (evaluating '$window.chrome.storage')

回答

2

我做了測試工作對我來說。這裏有:

describe('chromeStorageApi', function(){ 
    var mockWindow, chromeStorageApi; 

    beforeEach(module('myApp')); 

    beforeEach(function(){ 
     mockWindow = { 
      chrome:{ 
       storage:{ 
        local: sinon.stub({ 
         set: function(){ }, 
         get: function(){ }, 
         remove: function(){ }, 
         clear: function(){ } 
        }) 
       } 
      }, 
      addEventListener: function(){ } 
     } 
     module(function($provide){ 
      $provide.value('$window', mockWindow); 
     }) 
    }) 

    beforeEach(inject(function(_chromeStorageApi_){ 
     chromeStorageApi =_chromeStorageApi_; 
    })) 

    it('should be able to set data to the storage', function(){ 
     chromeStorageApi.set({'key':'value'}, function(){ }()); 
     expect(mockWindow.chrome.storage.local.set).toHaveBeenCalled(); 
     expect(mockWindow.chrome.storage.local.set).toHaveBeenCalledWith({'key':'value'}, function(){ }()); 

    }); 

    it('should be able to get data from the storage', function(){ 
     chromeStorageApi.get('key', function(){ }); 
     expect(mockWindow.chrome.storage.local.get).toHaveBeenCalled(); 
     expect(mockWindow.chrome.storage.local.get).toHaveBeenCalledWith('key'); 
    }) 
}) 

我使用sinonJS來創建方法存根。我希望這會對某人有所幫助。