diff --git a/assets/js/hooks/useMonitorInternetConnection.js b/assets/js/hooks/useMonitorInternetConnection.js index 55f5942ae93..57d234f6d6e 100644 --- a/assets/js/hooks/useMonitorInternetConnection.js +++ b/assets/js/hooks/useMonitorInternetConnection.js @@ -53,18 +53,16 @@ export function useMonitorInternetConnection() { } try { - const connectionCheckResponse = await apiFetch( { - path: '/google-site-kit/v1/', - } ); - - // We are only interested if the request was successful, to - // confirm online status. - const canReachConnectionCheck = !! connectionCheckResponse; - - setIsOnline( canReachConnectionCheck ); + await apiFetch( { path: '/google-site-kit/v1/' } ); } catch ( err ) { - setIsOnline( false ); + if ( err?.code === 'fetch_error' ) { + setIsOnline( false ); + return; + } } + // If the request succeeded or failed for any other reason, + // we should still be online. + setIsOnline( true ); }, [ setIsOnline ] ); useLifecycles( diff --git a/assets/js/hooks/useMonitorInternetConnection.test.js b/assets/js/hooks/useMonitorInternetConnection.test.js index 51474bc3ded..9d2006e94a8 100644 --- a/assets/js/hooks/useMonitorInternetConnection.test.js +++ b/assets/js/hooks/useMonitorInternetConnection.test.js @@ -177,4 +177,21 @@ describe( 'useMonitorInternetConnection', () => { expect( fetchMock ).toHaveFetchedTimes( 1 ); } ); + + it( 'should set offline status when a fetch_error occurs', async () => { + fetchMock.getOnce( connectionCheckEndpoint, { + throws: { code: 'fetch_error' }, + } ); + + renderHook( () => useMonitorInternetConnection(), { registry } ); + mockOnlineStatus( true ); + + await act( async () => { + global.window.dispatchEvent( new Event( 'online' ) ); + await waitForTimeouts( 100 ); + } ); + + expect( store.getState().isOnline ).toBe( false ); + expect( fetchMock ).toHaveFetched( connectionCheckEndpoint ); + } ); } );