angular - 在 Angular 7 中模拟本地存储
问题描述
我在我的应用程序中使用了本地存储。根据审阅者的评论,我没有直接使用 localstorage,而是创建了 localstorage 的引用并在我的应用程序中使用。它运作良好。但不能(我不知道如何)模拟引用的本地存储。
这是我的代码:
本地存储 ref.service.ts:
@Injectable()
export class LocalStorageRef {
public getLocalStorage(): Storage {
return localStorage;
}
}
app.component.ts:
import { LocalStorageRef } from './shared/local-storage-ref.service';
...
export class AppComponent implements OnInit {
...
constructor(public ref: LocaStorageRef){
}
...
someFunction(){
...
this.ref.localStorageRef.getLocalStorage().setItem('somekey','sometext');
...
val = this.ref.localStorageRef.getLocalStorage().setItem('somekey');
...
}
}
规格:
import { LocalStorageRef } from './shared/local-storage-ref.service';
...
describe('#AppComponent', () => {
...
let mockLocalStorageRef: jasmine.SpyObj<LocalStorageRef>;
...
beforeEach(async(() => {
...
mockLocalStorageRef = jasmine.createSpyObj('LocalStorageRef', ['getLocalStorage']);
mockLocalStorageRef.getLocalStorage.and.callThrough();
...
}
it(){
...
}
}
当我运行测试用例时。我收到类似的错误
TypeError: Cannot read property 'getItem' of undefined
我知道我嘲笑了,getLocalStorage()
但我不知道如何setItem and getItem
嘲笑getLocalStorage()
. 任何线索都会有所帮助。谢谢。
解决方案
最好使用useClass
创建一个stub
可以在您LocalStorageRef
在其他组件中使用时重用的:
LocalStorageRefStub
export class LocalStorageRefStub {
const mockLocalStorage = {
getItem: (key: string): string => {
return key in store ? store[key] : null;
},
setItem: (key: string, value: string) => {
store[key] = `${value}`;
}
};
public getLocalStorage(){
return mockLocalStorage;
}
}
然后在component.spec.ts中使用它:
TestBed.configureTestingModule(
{
imports: [blahblah],
providers: [{provide:LocalStorageRef, useClass: LocalStorageRefStub }],
// and other properties......
}
)
推荐阅读
- keras - 在每一层可视化 Keras CNN 最终训练的过滤器
- android - 如何将当前位置添加到我的地图活动中?
- java - Java ArchUnit:检测 getMethodCallsFromSelf 方法上的注释
- dart - 引发了另一个异常:FormatException: Invalid character (at character 6)
- php - 如何从数组中删除 nbsp 元素
- reactjs - 将 React 应用程序的生产版本部署到 Google App Engine:Service Worker 注册失败
- python - 将 PyCall PyObject 十进制转换为 Julia 浮点数
- hyperledger-fabric - Hyperledger Fabric 1.4:如何发出和订阅事件?
- android - 通过蓝牙发送文件到配对设备
- android - FFmpeg 无法将帧注入过滤器网络:内存不足