2013-08-02 34 views
0

我使用AngularJS構建一個應用程序,我現在正在開發測試案例我的應用程序。假設我有這樣的服務;我可以編寫測試用例使用茉莉花間諜AngularJS服務?

var app = angular.module('MyApp') 
app.factory('SessionService', function() { 

    return { 
     get: function (key) { 
      return sessionStorage.getItem(key); 
     }, 
     set: function (key, val) { 
      return sessionStorage.setItem(key, val); 
     }, 
     unset: function (key) { 
      return sessionStorage.removeItem(key); 
     } 
    }; 
}); 

我可以爲我的服務編寫測試用例嗎?

beforeEach(module('MyApp')); 
    describe('Testing Service : SessionService', function (SessionService) { 
     var session, fetchedSession, removeSession, setSession; 
     beforeEach(function() { 
      SessionService = { 
       get: function (key) { 
        return sessionStorage.getItem(key); 
       }, 
       set: function (key, val) { 
        return sessionStorage.setItem(key, val); 
       }, 
       unset: function (key) { 
        return sessionStorage.removeItem(key); 
       } 
      }; 
      spyOn(SessionService, 'get').andCallThrough(); 
      spyOn(SessionService, 'set').andCallThrough(); 
      spyOn(SessionService, 'unset').andCallThrough(); 
      setSession  = SessionService.set('authenticated', true); 
      fetchedSession = SessionService.get('authenticated'); 
      removeSession = SessionService.unset('authenticated'); 
     }); 
     describe('SessionService', function() { 
      it('tracks that the spy was called', function() { 
       expect(SessionService.get).toHaveBeenCalled(); 
      }); 
      it('tracks all the arguments used to call the get function', function() { 
       expect(SessionService.get).toHaveBeenCalledWith('authenticated'); 
      }); 
      //Rest of the Test Cases 
     }); 
    }); 

我正在使用Jasmine的間諜方法來開發這個測試用例。這很好還是我錯了?

+0

您可以檢查以下網址: http://stackoverflow.com/問題/ 14773269/injectioning-a-mock-into-an-angularjs-service –

回答

1

它看起來不錯。但我想你會遇到這樣的問題:

get: function (key) { 
     return sessionStorage.getItem(key); 
}, 

你不是在嘲笑sessionStorage。所以我想嘗試調用getItem()從該對象時,你會得到一個錯誤。看來你不感興趣,在你的測試這些調用的返回值。你只檢查他們是否被調用了正確的屬性。像這裏:

it('tracks that the spy was called', function() { 
    expect(SessionService.get).toHaveBeenCalled(); 
}); 

你爲什麼不改變你的SessionService的嘲諷返回任何東西?就像這樣:

get: function (key) { 
     return true; 
}, 

如果你想測試你的getItem/setItem /的removeItem你可以在另一個測試案例做

+0

那麼我需要改變的地方呢?在測試用例中還是在我的服務中? – BKM

+0

在測試用例。你的服務做它需要做的事情。但是你的測試用例不需要調用其他方法中的所有方法。如果你的測試不依賴於它的返回值,那麼你可以假冒爲「真」或空字符串(因爲在這裏似乎是這種情況) –