[英]Error “Function expected” when mocking localStorage.getItem
I'm trying to mock calls to localStorage.getItem, but getting error "Function expected". 我正在尝试模拟对localStorage.getItem的调用,但收到错误“预期功能”。 Here is my test code: 这是我的测试代码:
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);
});
});
});
Service under test: 被测服务:
(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';
}
})();
When I run tests, my mocked function returnFakeToken hadn't even been called and I got error (lines of code where error occured are marked with comments): 当我运行测试时,我的模拟函数returnFakeToken甚至都没有被调用,并且出现错误(发生错误的代码行带有注释):
TypeError: Function expected TypeError:预期功能
What am I doing wrong? 我究竟做错了什么?
Thanks! 谢谢!
You don't need to spy on localStorage
. 您无需监视localStorage
。 It is a function that is built into the browser as part of the HTML5 standard. 此功能是HTML5标准中内置于浏览器的功能。 What you should be testing is that your service returns the expected value. 您应该测试的是您的服务返回了预期值。 Also, you may need to mock out localStorage
if you are testing in PhantomJS. 此外,如果要在PhantomJS中进行测试,则可能需要模拟localStorage
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.