Refactor example app and add location tracking functionality with tests
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
require('react-test-renderer');
|
||||
const { renderHook, act } = require('@testing-library/react-hooks');
|
||||
const { useLocationTracking } = require('../useLocationTracking');
|
||||
|
||||
describe('useLocationTracking', () => {
|
||||
let origGeo;
|
||||
|
||||
beforeEach(() => {
|
||||
origGeo = global.navigator && global.navigator.geolocation;
|
||||
global.navigator = global.navigator || {};
|
||||
global.navigator.geolocation = {
|
||||
watchPosition: jest.fn((success) => {
|
||||
// Immediately call with a sample position
|
||||
success({ coords: { latitude: 10, longitude: 20 } });
|
||||
// Return a fake id
|
||||
return 42;
|
||||
}),
|
||||
clearWatch: jest.fn()
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (origGeo) global.navigator.geolocation = origGeo;
|
||||
else delete global.navigator.geolocation;
|
||||
jest.resetAllMocks();
|
||||
});
|
||||
|
||||
it('starts and stops tracking and collects path', () => {
|
||||
const { result } = renderHook(() => useLocationTracking());
|
||||
|
||||
expect(result.current.isTracking).toBe(false);
|
||||
act(() => result.current.startTracking());
|
||||
expect(result.current.isTracking).toBe(true);
|
||||
expect(result.current.path.length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
act(() => result.current.stopTracking());
|
||||
expect(result.current.isTracking).toBe(false);
|
||||
expect(global.navigator.geolocation.clearWatch).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears path', () => {
|
||||
const { result } = renderHook(() => useLocationTracking());
|
||||
act(() => result.current.startTracking());
|
||||
expect(result.current.path.length).toBeGreaterThanOrEqual(1);
|
||||
act(() => result.current.clear());
|
||||
expect(result.current.path.length).toBe(0);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user