Skip to content

Commit

Permalink
Merge pull request #9936 from google/infrastructure/9485-periodic-con…
Browse files Browse the repository at this point in the history
…nection-check
  • Loading branch information
aaemnnosttv authored Jan 6, 2025
2 parents c3a5f24 + 3cded87 commit 3704e47
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
18 changes: 8 additions & 10 deletions assets/js/hooks/useMonitorInternetConnection.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
17 changes: 17 additions & 0 deletions assets/js/hooks/useMonitorInternetConnection.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
} );
} );

0 comments on commit 3704e47

Please sign in to comment.