Skip to content

[URH-48] useGeolocation 신규 #45

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 1 commit into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions src/hooks/useGeolocation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { renderHook, waitFor } from '@testing-library/react';
import useGeolocation from './useGeolocation';

const mockOptions = {
enableHighAccuracy: false,
timeout: 5000,
maximumAge: 0,
};

const mockError: GeolocationPositionError = {
code: 1,
message: '사용자가 위치 정보를 거부했습니다.',
PERMISSION_DENIED: 1,
POSITION_UNAVAILABLE: 2,
TIMEOUT: 3,
};

beforeEach(() => {
const mockGeolocation = {
watchPosition: jest.fn().mockImplementation((success) => {
success({
coords: {
latitude: 35,
longitude: 139,
altitude: 0,
accuracy: 100,
altitudeAccuracy: null,
heading: null,
speed: null,
},
timestamp: Date.now(),
});
return 1;
}),
clearWatch: jest.fn(),
};

Object.defineProperty(global.navigator, 'geolocation', {
value: mockGeolocation,
writable: true,
});
});

afterEach(() => {
jest.clearAllMocks();
});

describe('useGeolocation hook', () => {
it('성공 후 위치 정보를 반환해야 함', async () => {
const { result } = renderHook(() => useGeolocation(mockOptions));

waitFor(() => {
expect(result.current.loading).toBe(false);
expect(result.current.error).toBe(null);
expect(result.current.latitude).toBe(35);
expect(result.current.longitude).toBe(139);
});
});

it('오류를 처리해야 한다', async () => {
global.navigator.geolocation.watchPosition = jest.fn((_, errorCallback) => {
if (errorCallback) {
errorCallback(mockError);
}
return 1;
});

const { result } = renderHook(() =>
useGeolocation({
enableHighAccuracy: false,
timeout: 5000,
maximumAge: 0,
})
);

await waitFor(() => {
expect(result.current.loading).toBe(false);
expect(result.current.error).not.toBe(null);
expect(result.current.latitude).toBeUndefined();
expect(result.current.longitude).toBeUndefined();
});
});
});
100 changes: 100 additions & 0 deletions src/hooks/useGeolocation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { useEffect, useState, useRef } from 'react';

interface UseGeolocationReturnType extends Partial<GeolocationCoordinates> {
loading: boolean;
error: GeolocationPositionError | null;
timestamp: EpochTimeStamp | undefined;
}

/**
* 사용자의 위치 정보를 가져오는 커스텀 훅
*
* @param {PositionOptions} options - 위치 정보를 가져오는 옵션
* @param {boolean} options.enableHighAccuracy - 위치 정보를 높은 정확도로 수집할지 여부를 지정 (기본값은 false)
* @param {number} options.timeout - 위치 정보를 가져오기 위해 대기할 최대 시간 (밀리초 단위)
* @param {number} options.maximumAge - 위치 정보를 캐싱할 최대 시간 (밀리초 단위)

* @returns {UseGeolocationReturnType} 위치 정보와 상태를 포함하는 객체를 반환
* @returns {boolean} UseGeolocationReturnType.loading - 위치 정보를 가져오는 중인지 여부
* @returns {GeolocationPositionError | null} UseGeolocationReturnType.error - 위치 정보를 가져오는 중에 발생한 에러
* @returns {EpochTimeStamp | undefined} UseGeolocationReturnType.timestamp - 위치 정보의 타임스탬프
* @returns {number | undefined} UseGeolocationReturnType.latitude - 위도 정보
* @returns {number | undefined} UseGeolocationReturnType.longitude - 경도 정보
* @returns {number | undefined} UseGeolocationReturnType.altitude - 고도 정보
* @returns {number | undefined} UseGeolocationReturnType.accuracy - 위치 정보의 정확도
* @returns {number | undefined} UseGeolocationReturnType.altitudeAccuracy - 고도 정보의 정확도
* @returns {number | undefined} UseGeolocationReturnType.heading - 방향 정보
* @returns {number | undefined} UseGeolocationReturnType.speed - 속도 정보
*/
const useGeolocation = (
options: PositionOptions = {}
): UseGeolocationReturnType => {
const isMounted = useRef(true);

const [loading, setLoading] = useState(true);
const [error, setError] = useState<GeolocationPositionError | null>(null);
const [position, setPosition] = useState<GeolocationPosition | null>(null);

const { enableHighAccuracy, timeout, maximumAge } = options;

useEffect(() => {
const handleSuccess = (position: GeolocationPosition) => {
if (isMounted.current) {
setPosition(position);
setLoading(false);
}
};

const handleError = (err: GeolocationPositionError) => {
if (isMounted.current) {
setError(err);
setLoading(false);
}
};

const handleReset = () => {
setLoading(true);
setError(null);
setPosition(null);
};

const watchId = navigator.geolocation.watchPosition(
handleSuccess,
handleError,
options
);

return () => {
handleReset();
isMounted.current = false;
navigator.geolocation.clearWatch(watchId);
};
}, [enableHighAccuracy, timeout, maximumAge]);

const {
latitude,
longitude,
altitude,
accuracy,
altitudeAccuracy,
heading,
speed,
} = position?.coords || {};

const timestamp = position?.timestamp ?? undefined;

return {
latitude,
longitude,
altitude,
accuracy,
altitudeAccuracy,
heading,
speed,
timestamp,
error,
loading,
};
};

export default useGeolocation;