2016-02-12 64 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