2016-05-08 37 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); 
    }); 

}); 
相关问题