Reputation: 1694
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.
Upvotes: 3
Views: 8439
Reputation: 17514
Its better to use useClass
to create a stub
which can reused whenever you are using LocalStorageRef
in other components:
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;
}
}
and then use it in component.spec.ts as:
TestBed.configureTestingModule(
{
imports: [blahblah],
providers: [{provide:LocalStorageRef, useClass: LocalStorageRefStub }],
// and other properties......
}
)
Upvotes: 3
Reputation: 1694
Finally, I found the solution on my own. The problem is I'm mocking the getLocalStorage
but not the getItem and setItem
. So I created two spies and mocked getItem
and setItem
as given below. and It worked !!!
code:
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);
Hope this helps someone.
Upvotes: 1