还要考虑在对象的构造函数中注入依赖项的选项。
var SomeObject(storage) {
this.storge = storage || window.localStorage;
// ...
}
SomeObject.prototype.doSomeStorageRelatedStuff = function() {
var myValue = this.storage.getItem('myKey');
// ...
}
// In src
var myObj = new SomeObject();
// In test
var myObj = new SomeObject(mockStorage)
根据模拟和单元测试,我喜欢避免测试存储实现。例如,在设置项目等后检查存储长度是否增加没有意义。
由于替换真实 localStorage 对象上的方法显然不可靠,因此请使用“哑”模拟存储并根据需要存根各个方法,例如:
var mockStorage = {
setItem: function() {},
removeItem: function() {},
key: function() {},
getItem: function() {},
removeItem: function() {},
length: 0
};
// Then in test that needs to know if and how setItem was called
sinon.stub(mockStorage, 'setItem');
var myObj = new SomeObject(mockStorage);
myObj.doSomeStorageRelatedStuff();
expect(mockStorage.setItem).toHaveBeenCalledWith('myKey');