|
| 1 | +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; |
| 2 | +import React from 'react'; |
| 3 | +import { LocationProvider, useLocation } from '@/contexts/LocationContext'; |
| 4 | + |
| 5 | +function Consumer() { |
| 6 | + const { location, setLocation, requestLocation } = useLocation(); |
| 7 | + return ( |
| 8 | + <div> |
| 9 | + <span data-testid="loc">{location ? JSON.stringify(location) : 'null'}</span> |
| 10 | + <button onClick={() => setLocation({ lat: 1, lng: 2 })}>set</button> |
| 11 | + <button onClick={requestLocation}>request</button> |
| 12 | + </div> |
| 13 | + ); |
| 14 | +} |
| 15 | + |
| 16 | +describe('LocationContext', () => { |
| 17 | + it('throws if useLocation is used outside provider', () => { |
| 18 | + jest.spyOn(console, 'error').mockImplementation(() => {}); |
| 19 | + expect(() => render(<Consumer />)).toThrow('useLocation must be used within a LocationProvider'); |
| 20 | + (console.error as jest.Mock).mockRestore(); |
| 21 | + }); |
| 22 | + |
| 23 | + it('updates location via setLocation', () => { |
| 24 | + render( |
| 25 | + <LocationProvider> |
| 26 | + <Consumer /> |
| 27 | + </LocationProvider> |
| 28 | + ); |
| 29 | + fireEvent.click(screen.getByText('set')); |
| 30 | + expect(screen.getByTestId('loc').textContent).toBe('{"lat":1,"lng":2}'); |
| 31 | + }); |
| 32 | + |
| 33 | + it('requests location using geolocation API', async () => { |
| 34 | + const mockGetCurrentPosition = jest.fn((success) => { |
| 35 | + success({ coords: { latitude: 3, longitude: 4 } }); |
| 36 | + }); |
| 37 | + Object.defineProperty(global.navigator, 'geolocation', { |
| 38 | + value: { getCurrentPosition: mockGetCurrentPosition }, |
| 39 | + configurable: true, |
| 40 | + }); |
| 41 | + |
| 42 | + render( |
| 43 | + <LocationProvider> |
| 44 | + <Consumer /> |
| 45 | + </LocationProvider> |
| 46 | + ); |
| 47 | + |
| 48 | + fireEvent.click(screen.getByText('request')); |
| 49 | + |
| 50 | + await waitFor(() => { |
| 51 | + expect(screen.getByTestId('loc').textContent).toBe('{"lat":3,"lng":4}'); |
| 52 | + }); |
| 53 | + }); |
| 54 | +}); |
0 commit comments