在angular 7中模拟本地存储

时间:2019-06-17 10:28:21

标签: angular unit-testing karma-jasmine

我在应用程序中使用了本地存储。基于我的审阅者的评论,我没有直接使用localstorage,而是创建了localstorage的引用并在我的应用程序中使用。它运作良好。但是无法(我不知道如何)模拟引用的本地存储。

这是我的代码:

local-storage-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');
...
}
}

Spec.ts:

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()。任何线索都将有所帮助。谢谢。

2 个答案:

答案 0 :(得分:1)

最后,我自己找到了解决方案。问题是我在嘲笑getLocalStorage,而不是getItem and setItem。因此,我创建了两个间谍并模拟了getItemsetItem,如下所示。而且有效!!!

代码:

const mockLocalStorage = {
  getItem: (key: string): string => {
    return key in store ? store[key] : null;
  },
  setItem: (key: string, value: string) => {
    store[key] = `${value}`;
  }
};
...
localStorageRefServiceSpy = jasmine.createSpyObj('LocalStorageRef', ['getLocalStorage']);
getLocalStorageSpy = jasmine.createSpyObj('LocalStorageRef.getLocalStorage', ['getItem', 'setItem']);
localStorageRefServiceSpy.getLocalStorage.and.returnValue(getLocalStorageSpy);
getLocalStorageSpy.getItem.and.callFake(mockLocalStorage.getItem);
getLocalStorageSpy.setItem.and.callFake(mockLocalStorage.setItem);

希望这对某人有帮助。

答案 1 :(得分:1)

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