首页 > 解决方案 > 在 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(). 任何线索都会有所帮助。谢谢。

标签: angularunit-testingkarma-jasmine

解决方案


最好使用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......
   }
   )



推荐阅读