2016-05-08 70 views
1

如何對使用window.localStorage的函數進行單元測試。下面是檢查和創建localStorage的變量有兩個功能:如何單元測試在Jasmine中使用window.localStorage的函數

// checks if Initial localStorage variable is true 
// returns boolean 
var isInitial = function() { 

    var doc = window.localStorage.getItem("Initial"); 
    console.log("intial: " + doc); 
    if(doc !== "true"){ 
     return true; 
    } 
    else{ 
     return false; 
    } 
}; 

// create InitialSync localStorage item and sets it to true 
// void 
var createInitial = function() { 
    console.log("creating Initial"); 
    window.localStorage.setItem("Initial","true") 
}; 
+0

那麼,什麼是問題? –

+0

重寫了這個問題 –

回答

0

下面是我單位測試了:

describe('isInitial function', function() { 

    // clear localStorage before each spec 
    beforeEach(function() { 
     window.localStorage.clear(); 
    }) 

    // isInitial should return true because 
    // there is no localStorage variable set 
    it('should return true', function() { 
     var initial = SyncService.isInitial(); 
     expect(initial).toBe(true); 
    }); 

    // after creating the Initial variable using createInitial() 
    // we can test both functions 
    it('should call createInitial and isInitial should be true', function() { 
     SyncService.createInitial(); 
     var initial = SyncService.isInitial(); 
     console.log("initial: " + initial); 
     expect(initial).toBe(false); 
    }); 

}); 
相關問題