我正在尝试模拟对localStorage.getItem的调用,但收到错误“Function expected”。这是我的测试代码:
describe("AuthService Tests", function() {
var authSvc, httpBackend, scope;
var fakeItem = "{\"access_token\":\"giant_access_token\",\"token_type\":\"bearer\",\"expires_in\":1209599,\".issued\":\"Thu, 11 Feb 2016 13:22:45 GMT\",\".expires\":\"Thu, 25 Feb 2016 13:22:45 GMT\",\"accountType\":\"Administrator\",\"certifiedForAccess\":true}";
var returnFakeToken = function(key) { return fakeItem; }
beforeEach(module('app'));
beforeEach(inject(function (_AuthService_, $q, $rootScope, $httpBackend, $state, _config_, _messages_) {
scope = $rootScope.$new();
spyOn(localStorage, 'getItem').and.callFake(returnFakeToken);
authSvc = _AuthService_;
httpBackend = $httpBackend;
}));
describe('Test suite 1', function () {
it('should return true if user is Administrator', function () {
var result = authSvc.isAdministrator(); // error here
expect(result).toBe(true);
});
});
});
受测试服务:
(function () {
'use strict';
angular
.module('app.services')
.factory('AuthService', AuthService);
AuthService.$inject = ['$q', '$rootScope', '$http', '$state', 'config', 'messages'];
function AuthService($q, $rootScope, $http, $state, config, messages) {
var userIdKey = 'userId';
var tokenKey = 'tokenKey';
var userAuthKey = 'userAuth';
var svc = {
isAdministrator: isAdministrator
};
return svc;
function isAdministrator() {
var item = localStorage.getItem(tokenKey); // eror here
var jsonparse = JSON.parse(item);
return jsonparse.accountType == 'Administrator';
}
})();
当我运行测试时,我的模拟函数 returnFakeToken 甚至没有被调用,我得到了错误(发生错误的代码行标有注释):
TypeError:预期的功能
我做错了什么?
谢谢!
答案 0 :(得分:-1)
你不需要监视localStorage
。它是作为HTML5标准的一部分内置在浏览器中的函数。您应该测试的是您的服务返回预期值。此外,如果您在PhantomJS中进行测试,则可能需要模拟localStorage
。