import { ReloadHandler, ReloadHandlerOptions } from '../reload-handler'; describe(`[ajax-handlers] ${ReloadHandler.name}`, () => { const MINUTE = 60 * 1000; const originalLocation = window.location; let options: ReloadHandlerOptions; let handler: ReloadHandler | undefined; beforeAll(() => { Object.defineProperty(window, 'location', { configurable: true, value: { ...originalLocation, reload: jest.fn() }, }); }); afterAll(() => { Object.defineProperty(window, 'location', { configurable: true, value: originalLocation, }); }); beforeEach(() => { jest.useFakeTimers(); jest.clearAllMocks(); sessionStorage.clear(); localStorage.clear(); options = { id: 'test' }; handler = undefined; }); afterEach(() => { jest.useRealTimers(); }); const subject = () => { handler ??= new ReloadHandler(options); handler.reload(); }; function setOptions(props: Partial) { Object.assign(options, props); handler = undefined; } function mockResetSession() { sessionStorage.clear(); handler = undefined; } function itReloadsWindow() { test('reloads window', () => { subject(); expect(window.location.reload).toHaveBeenCalled(); }); } function itDoesNotReloadWindow() { test('does not reload window', () => { subject(); expect(window.location.reload).not.toHaveBeenCalled(); }); } function itRespectsCoolDownInterval(coolDownInterval: number) { describe('when called again', () => { beforeEach(() => { subject(); jest.clearAllMocks(); }); describe('during cool down interval', () => { beforeEach(() => jest.setSystemTime(Date.now() + coolDownInterval)); itDoesNotReloadWindow(); }); describe('after cool down interval', () => { beforeEach(() => jest.setSystemTime(Date.now() + coolDownInterval + 1)); itReloadsWindow(); }); }); } itReloadsWindow(); itRespectsCoolDownInterval(5 * MINUTE); describe('when called again', () => { beforeEach(() => { subject(); jest.clearAllMocks(); }); describe('after reset', () => { beforeEach(() => handler!.reset()); itReloadsWindow(); }); describe('after session expires', () => { beforeEach(() => mockResetSession()); itReloadsWindow(); }); }); describe('with custom handler', () => { const customHandler = jest.fn(); beforeEach(() => setOptions({ handler: customHandler })); itDoesNotReloadWindow(); test('calls custom handler', () => { subject(); expect(customHandler).toHaveBeenCalled(); }); }); describe('with custom cool down interval', () => { const customInterval = 60 * MINUTE; beforeEach(() => setOptions({ coolDownInterval: customInterval })); itRespectsCoolDownInterval(customInterval); }); describe('when configured to use localStorage', () => { beforeEach(() => setOptions({ storage: 'local' })); describe('when called again', () => { beforeEach(() => { subject(); jest.clearAllMocks(); }); describe('after session expires', () => { beforeEach(() => mockResetSession()); itDoesNotReloadWindow(); }); }); }); });