-
Notifications
You must be signed in to change notification settings - Fork 0
[URH-58] useOnlineStatus 신규 #47
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
import { act, renderHook } from '@testing-library/react'; | ||
import useOnlineStatus from './useOnlineStatus'; | ||
|
||
let windowSpy: jest.SpyInstance; | ||
let onlineCallback: jest.Mock; | ||
let offlineCallback: jest.Mock; | ||
|
||
describe('useOnlineStatus', () => { | ||
beforeEach(() => { | ||
windowSpy = jest.spyOn(global, 'window', 'get'); | ||
onlineCallback = jest.fn(); | ||
offlineCallback = jest.fn(); | ||
}); | ||
|
||
afterEach(() => { | ||
windowSpy.mockRestore(); | ||
}); | ||
|
||
test('온라인 상태라면 isOnline은 true이다.', () => { | ||
jest.spyOn(navigator, 'onLine', 'get').mockReturnValueOnce(true); | ||
|
||
const { result } = renderHook(() => useOnlineStatus()); | ||
|
||
expect(result.current.isOnline).toBe(true); | ||
}); | ||
|
||
test('오프라인 상태에서 isOnline은 false이다.', () => { | ||
jest.spyOn(navigator, 'onLine', 'get').mockReturnValueOnce(false); | ||
|
||
const { result } = renderHook(() => useOnlineStatus()); | ||
|
||
expect(result.current.isOnline).toBe(false); | ||
}); | ||
|
||
test('네트워크 상태가 변경되면 isOnline 상태가 갱신된다.', () => { | ||
const { result } = renderHook(() => useOnlineStatus()); | ||
|
||
act(() => { | ||
window.dispatchEvent(new Event('offline')); | ||
}); | ||
|
||
expect(result.current.isOnline).toBe(false); | ||
|
||
act(() => { | ||
window.dispatchEvent(new Event('online')); | ||
}); | ||
|
||
expect(result.current.isOnline).toBe(true); | ||
}); | ||
|
||
test('콜백 함수가 호출되는지 확인', () => { | ||
renderHook(() => useOnlineStatus({ onlineCallback, offlineCallback })); | ||
act(() => { | ||
window.dispatchEvent(new Event('offline')); | ||
}); | ||
|
||
expect(offlineCallback).toHaveBeenCalledTimes(1); | ||
|
||
act(() => { | ||
window.dispatchEvent(new Event('online')); | ||
}); | ||
expect(onlineCallback).toHaveBeenCalledTimes(1); | ||
}); | ||
|
||
test('언마운트 시 이벤트 리스너가 제거된다.', () => { | ||
const { unmount } = renderHook(() => | ||
useOnlineStatus({ onlineCallback, offlineCallback }) | ||
); | ||
|
||
unmount(); | ||
|
||
act(() => { | ||
window.dispatchEvent(new Event('offline')); | ||
}); | ||
expect(offlineCallback).toHaveBeenCalledTimes(0); | ||
|
||
act(() => { | ||
window.dispatchEvent(new Event('online')); | ||
}); | ||
expect(onlineCallback).toHaveBeenCalledTimes(0); | ||
}); | ||
}); |
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
import { useEffect, useState } from 'react'; | ||
import { Fn } from '../types'; | ||
import { hasNavigator } from '../utils'; | ||
|
||
interface useOnlineStatusProps { | ||
onlineCallback?: Fn; | ||
offlineCallback?: Fn; | ||
} | ||
|
||
interface UseOnlineStatusReturns { | ||
isOnline: boolean; | ||
} | ||
|
||
/** | ||
* 온라인/오프라인 네트워크 상태를 판별하는 훅. | ||
* | ||
* @param {Object} props - 훅에 전달되는 옵션 객체 | ||
* @param {Fn} [props.onlineCallback] - 브라우저가 온라인 상태가 될 때 실행할 콜백 함수 | ||
* @param {Fn} [props.offlineCallback] - 브라우저가 오프라인 상태가 될 때 실행할 콜백 함수 | ||
* | ||
* @returns {{ isOnline: boolean }} - 현재 온라인 상태를 나타내는 객체 | ||
* | ||
* @description | ||
* 브라우저의 온라인/오프라인 상태를 추적하는 훅입니다. | ||
* 온라인 상태가 변경될 때 실행할 콜백 함수를 선택적으로 지정할 수 있습니다. | ||
* 콜백 함수들은 `useCallback`을 사용하여 메모이제이션 할 것을 권장합니다. | ||
* 이를 통해 의도하지 않은 재생성을 방지하고 성능을 최적화할 수 있습니다. | ||
*/ | ||
|
||
const useOnlineStatus = ({ | ||
onlineCallback = () => {}, | ||
offlineCallback = () => {}, | ||
}: useOnlineStatusProps = {}): UseOnlineStatusReturns => { | ||
const [isOnline, setIsOnline] = useState(() => | ||
hasNavigator() ? navigator.onLine : false | ||
); | ||
|
||
useEffect(() => { | ||
if (!hasNavigator()) { | ||
console.error('navigator is not supported in this environment.'); | ||
return; | ||
} | ||
|
||
const handleOnline = () => { | ||
setIsOnline(true); | ||
onlineCallback(); | ||
}; | ||
|
||
const handleOffline = () => { | ||
setIsOnline(false); | ||
offlineCallback(); | ||
}; | ||
|
||
window.addEventListener('online', handleOnline); | ||
window.addEventListener('offline', handleOffline); | ||
|
||
return () => { | ||
window.removeEventListener('online', handleOnline); | ||
window.removeEventListener('offline', handleOffline); | ||
}; | ||
}, [onlineCallback, offlineCallback]); | ||
|
||
return { | ||
isOnline, | ||
}; | ||
}; | ||
|
||
export default useOnlineStatus; |
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
export { delayExecution, type CancelToken } from './delayExecution'; | ||
export { throttle } from './throttle'; | ||
export { isClient } from './isClient'; | ||
export { isClient, hasNavigator } from './isClient'; | ||
export { isTouchDevice } from './isTouchDevice'; |
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,5 @@ | ||
export const isClient = typeof window !== 'undefined'; | ||
|
||
export const hasNavigator = () => { | ||
return isClient && typeof navigator !== 'undefined'; | ||
}; |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.