diff --git a/src/context/provider.tsx b/src/context/provider.tsx index fbbb57a..51e638b 100644 --- a/src/context/provider.tsx +++ b/src/context/provider.tsx @@ -9,6 +9,7 @@ export type SettingsValue = Pick; type SettingsProviderOptions = { updateIntervalMs?: number; onGetSettingsFail?: 'keep-last' | 'reset'; + autoUpdate?: boolean; }; interface Props { @@ -23,7 +24,7 @@ const initialValue = { flags: {}, settings: {} }; export function SettingsProvider({ children, getSettings, - options: { onGetSettingsFail = 'keep-last', updateIntervalMs = tenMinInMs } = {}, + options: { onGetSettingsFail = 'keep-last', updateIntervalMs = tenMinInMs, autoUpdate = true } = {}, }: Props): ReactElement { const [isLoading, setLoading] = useState(false); const [value, setValue] = useState(initialValue); @@ -46,11 +47,15 @@ export function SettingsProvider({ } load(); - - const intervalId = window.setInterval(load, updateIntervalMs); + let intervalId: number | null = null; + if (autoUpdate) { + intervalId = window.setInterval(load, updateIntervalMs); + } return function cleanup() { - window.clearInterval(intervalId); + if (intervalId) { + window.clearInterval(intervalId); + } }; }, []); diff --git a/tests/context/provider.spec.tsx b/tests/context/provider.spec.tsx index bca3f5c..9e3a71b 100644 --- a/tests/context/provider.spec.tsx +++ b/tests/context/provider.spec.tsx @@ -118,4 +118,33 @@ describe('SettingsProvider', () => { expect(getRendered()).toStrictEqual({ flags: {}, settings: {}, isLoading: false }); }); }); + + describe('test updateIntervalMs', () => { + beforeEach(jest.useFakeTimers); + afterEach(jest.useRealTimers); + + it('calls get settings after delay', async () => { + const getSettings = jest.fn().mockResolvedValueOnce(settings).mockRejectedValueOnce({}) as Props['getSettings']; + const options = { updateIntervalMs: 10000 } as Props['options']; + setup({ getSettings, options }); + + await waitFor(() => expect(getSettings).toHaveBeenCalledTimes(1)); + act(() => { + jest.advanceTimersByTime(10000); + }); + await waitFor(() => expect(getSettings).toHaveBeenCalledTimes(2)); + }); + + it('does no call get settings after delay if deactivated', async () => { + const getSettings = jest.fn().mockResolvedValueOnce(settings).mockRejectedValueOnce({}) as Props['getSettings']; + const options = { updateIntervalMs: 10000, autoUpdate: false } as Props['options']; + setup({ getSettings, options }); + + await waitFor(() => expect(getSettings).toHaveBeenCalledTimes(1)); + act(() => { + jest.advanceTimersByTime(10000); + }); + await waitFor(() => expect(getSettings).toHaveBeenCalledTimes(1)); + }); + }); });