【问题标题】:Error "Function expected" when mocking localStorage.getItem模拟 localStorage.getItem 时出现“预期功能”错误
【发布时间】:2016-02-12 10:30:26
【问题描述】:

我正在尝试模拟对 localStorage.getItem 的调用,但出现“预期功能”错误。这是我的测试代码:

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 甚至没有被调用并且我得到了错误(发生错误的代码行用 cmets 标记):

TypeError:预期功能

我做错了什么?

谢谢!

【问题讨论】:

    标签: angularjs unit-testing mocking jasmine


    【解决方案1】:

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

    【讨论】:

    • 实际上我不是在浏览器中运行测试,而是在 cordva 应用程序中运行测试,但是,是的,你是对的,没有必要模拟 localStorage。谢谢!
    • Cordova 正在为您模拟浏览器。很酷,它这样做,嗯?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 2020-10-08
    • 1970-01-01
    相关资源
    最近更新 更多