模拟 localStorage.getItem 时出错 "Function expected"

Error "Function expected" when mocking localStorage.getItem

我正在尝试模拟对 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: Function expected

我做错了什么?

谢谢!

你不需要监视 localStorage。它是作为 HTML5 标准的一部分内置于浏览器中的功能。您应该测试的是您的服务 returns 预期值。此外,如果您在 PhantomJS 中进行测试,则可能需要模拟 localStorage