Created
June 26, 2024 06:46
-
-
Save warrenlalata/f3a8378f7e4142fbfcfadce592986aad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { TestBed } from '@angular/core/testing'; | |
import { ReloadService } from './reload.service'; | |
window.onbeforeunload = jasmine.createSpy(); | |
describe('ReloadService', () => { | |
let service: ReloadService; | |
let mockSessionStorage: { [key: string]: string } = {}; | |
beforeEach(() => { | |
mockSessionStorage = {}; | |
const mock = { | |
getItem: (key: string): string | null => mockSessionStorage[key] || null, | |
setItem: (key: string, value: string): void => { | |
mockSessionStorage[key] = value; | |
}, | |
removeItem: (key: string): void => { | |
delete mockSessionStorage[key]; | |
}, | |
clear: (): void => { | |
mockSessionStorage = {}; | |
}, | |
}; | |
spyOn(sessionStorage, 'getItem').and.callFake(mock.getItem); | |
spyOn(sessionStorage, 'setItem').and.callFake(mock.setItem); | |
spyOn(sessionStorage, 'removeItem').and.callFake(mock.removeItem); | |
spyOn(sessionStorage, 'clear').and.callFake(mock.clear); | |
TestBed.configureTestingModule({ | |
providers: [ReloadService], | |
}); | |
service = TestBed.inject(ReloadService); | |
spyOn(service, 'performReload').and.callFake(() => {}); | |
}); | |
it('should set sessionStorage and reload the page if not reloaded before', () => { | |
service.reload(); | |
expect(sessionStorage.setItem).toHaveBeenCalledWith( | |
'isPageReloaded', | |
'true' | |
); | |
expect(service.performReload).toHaveBeenCalled(); | |
}); | |
it('should not reload the page if already reloaded', () => { | |
sessionStorage.setItem('isPageReloaded', 'true'); | |
service.reload(); | |
expect(service.performReload).not.toHaveBeenCalled(); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
@Injectable({ | |
providedIn: 'root', | |
}) | |
export class ReloadService { | |
private storageKey = 'isPageReloaded'; | |
reload(): void { | |
if (!sessionStorage.getItem(this.storageKey)) { | |
sessionStorage.setItem(this.storageKey, 'true'); | |
this.performReload(); | |
} | |
} | |
performReload(): void { | |
location.reload(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment