我有一个cookie的getter和setter服务:
angular.module('myApp.services').factory('CookieService', [function() {
var setCookie = function(cname, cval, exdays) {
exdays = typeof exdays !== 'undefined' ? exdays : 3;
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = 'expires=' + d.toGMTString();
document.cookie = cname + '=' + cval + '; ' + expires;
};
var getCookie = function(cname) {
var name = cname + '=',
ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if(c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return '';
};
return {
setCookie: setCookie,
getCookie: getCookie
};
}]);
我如何测试获取/设置cookie是否有效,因为我使用document.cookie
?
到目前为止,我尝试了这个:
(function() {
describe('CookiesService', function() {
beforeEach(module('myApp.services'));
var scope, CookieService, document;
beforeEach(inject(function($rootScope, $injector) {
scope = $rootScope.$new();
CookieService = $injector.get('CookieService');
document = {
cookie: 'foo=bar'
}
}));
it('should be set a cookie without expiration days', function() {
CookieService.setCookie('thisdoes', 'notwork');
expect(document.cookie).toBe('thisdoes=notwork');
});
});
}());
您需要在代码中到处使用$document而不是document,并像这样向您的测试类添加一个注入:
beforeEach(inject([
'CookiesService', '$document', function(_CookiesService_, _$document_) {
CookiesService = _CookiesService_;
$document = _$document_;
}
]));
这是一个显示工作测试的柱塞:http://plnkr.co/edit/GaO8wBMoBd8BGXaIkzf8?p=preview