2016-02-12 116 views
0

“预期功能”错误我想模拟调用localStorage.getItem,但得到错误“函数预期”。这里是我的测试代码:当嘲笑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甚至没有被调用,我得到了错误的代码,其中(行错误发生时标有注释):

TypeError: Function expected

我在做什么错?

谢谢!

回答

-1

你不需要监视localStorage。它是作为HTML5标准的一部分内置于浏览器中的一项功能。你应该测试的是你的服务返回预期的价值。另外,如果您正在PhantomJS中测试,则可能需要剔除localStorage

+0

其实我不是在浏览器中运行测试,而是在cordva应用中,但是,是的,你是对的,没有必要模拟localStorage。谢谢! – AlenSv

+0

Cordova正在为你嘲笑浏览器。很酷,它这样做,呃? – MBielski