I have used localstorage in my application. based on the comments from my reviewer, Instead of using the localstorage directly, I created a reference of localstorage and used in my application. It works well. but couldn't (I don't know how to) mock the referenced localstorage.
Here's my code:
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(){
...
}
}
When i run the test case. I'm getting error like
TypeError: Cannot read property 'getItem' of undefined
I know that I mocked the getLocalStorage() but i don't know how to mock the setItem and getItem which is inside the getLocalStorage(). Any leads would be helpful. Thanks.