我使用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的間諜方法來開發這個測試用例。這很好還是我錯了?
您可以檢查以下網址: http://stackoverflow.com/問題/ 14773269/injectioning-a-mock-into-an-angularjs-service –