如何在Jasmine中单元测试使用window.localStorage的函数

时间:2016-05-08 23:35:33

标签: unit-testing jasmine local-storage

如何对使用window.localStorage的函数进行单元测试。以下是检查和创建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")   
}; 

1 个答案:

答案 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);   
    });   

});