我正在使用 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 的 spy 方法来开发这个测试用例。很好还是我错了?