diff --git a/__tests__/components/FindHelpEntry.test.tsx b/__tests__/components/FindHelpEntry.test.tsx index ce5967cc..c20d8d67 100644 --- a/__tests__/components/FindHelpEntry.test.tsx +++ b/__tests__/components/FindHelpEntry.test.tsx @@ -63,5 +63,36 @@ describe('FindHelpEntry', () => { await waitFor(() => { expect(alertSpy).toHaveBeenCalledWith(expect.stringMatching(/something went wrong/i)); }); - }); }); + + it('uses browser geolocation when available', async () => { + const mockGetCurrentPosition = jest.fn((success) => { + success({ coords: { latitude: 10, longitude: 20 } }); + }); + Object.defineProperty(global.navigator, 'geolocation', { + value: { getCurrentPosition: mockGetCurrentPosition }, + configurable: true, + }); + + renderWithProvider(); + + await waitFor(() => { + expect(mockGetCurrentPosition).toHaveBeenCalled(); + expect(screen.getByText(/location set/i)).toBeInTheDocument(); + }); + }); + + it('shows postcode form when geolocation fails', async () => { + const mockGetCurrentPosition = jest.fn((_s, error) => error()); + Object.defineProperty(global.navigator, 'geolocation', { + value: { getCurrentPosition: mockGetCurrentPosition }, + configurable: true, + }); + + renderWithProvider(); + + await waitFor(() => { + expect(screen.getByLabelText(/enter your postcode/i)).toBeInTheDocument(); + }); + }); +}); \ No newline at end of file diff --git a/__tests__/contexts/LocationContext.test.tsx b/__tests__/contexts/LocationContext.test.tsx new file mode 100644 index 00000000..d7c79ac7 --- /dev/null +++ b/__tests__/contexts/LocationContext.test.tsx @@ -0,0 +1,54 @@ +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import React from 'react'; +import { LocationProvider, useLocation } from '@/contexts/LocationContext'; + +function Consumer() { + const { location, setLocation, requestLocation } = useLocation(); + return ( +
+ {location ? JSON.stringify(location) : 'null'} + + +
+ ); +} + +describe('LocationContext', () => { + it('throws if useLocation is used outside provider', () => { + jest.spyOn(console, 'error').mockImplementation(() => {}); + expect(() => render()).toThrow('useLocation must be used within a LocationProvider'); + (console.error as jest.Mock).mockRestore(); + }); + + it('updates location via setLocation', () => { + render( + + + + ); + fireEvent.click(screen.getByText('set')); + expect(screen.getByTestId('loc').textContent).toBe('{"lat":1,"lng":2}'); + }); + + it('requests location using geolocation API', async () => { + const mockGetCurrentPosition = jest.fn((success) => { + success({ coords: { latitude: 3, longitude: 4 } }); + }); + Object.defineProperty(global.navigator, 'geolocation', { + value: { getCurrentPosition: mockGetCurrentPosition }, + configurable: true, + }); + + render( + + + + ); + + fireEvent.click(screen.getByText('request')); + + await waitFor(() => { + expect(screen.getByTestId('loc').textContent).toBe('{"lat":3,"lng":4}'); + }); + }); +});