我正在使用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的间谍方法来开发此测试用例。很好还是我错了?
看起来很好。但是我认为您会遇到一些问题:
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,则可以在另一个测试用例中执行此操作
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句