|
1 | 1 | import { renderHook, act } from "@testing-library/react-hooks" |
2 | 2 | import axios from "axios" |
3 | 3 |
|
4 | | -import useDeviceLocation from "@app/hooks/use-device-location" |
| 4 | +import useDeviceLocation, { useIpCountryCode } from "@app/hooks/use-device-location" |
5 | 5 |
|
6 | 6 | const mockLogError = jest.fn() |
7 | 7 | const mockUpdateCountryCode = jest.fn() |
@@ -62,6 +62,7 @@ describe("useDeviceLocation", () => { |
62 | 62 | expect(result.current.loading).toBe(false) |
63 | 63 | expect(result.current.countryCode).toBe("DE") |
64 | 64 | expect(result.current.detectionFailed).toBe(false) |
| 65 | + expect(result.current.source).toBe("phone") |
65 | 66 | expect(mockedAxios.get).not.toHaveBeenCalled() |
66 | 67 | }) |
67 | 68 |
|
@@ -123,6 +124,7 @@ describe("useDeviceLocation", () => { |
123 | 124 | expect(result.current.loading).toBe(false) |
124 | 125 | expect(result.current.countryCode).toBe("PL") |
125 | 126 | expect(result.current.detectionFailed).toBe(false) |
| 127 | + expect(result.current.source).toBe("ip") |
126 | 128 | expect(mockedAxios.get).toHaveBeenCalled() |
127 | 129 | }) |
128 | 130 |
|
@@ -256,3 +258,39 @@ describe("useDeviceLocation", () => { |
256 | 258 | expect(mockLogError).toHaveBeenCalled() |
257 | 259 | }) |
258 | 260 | }) |
| 261 | + |
| 262 | +describe("useIpCountryCode", () => { |
| 263 | + beforeEach(() => { |
| 264 | + jest.clearAllMocks() |
| 265 | + }) |
| 266 | + |
| 267 | + it("does not call ipapi while disabled", () => { |
| 268 | + const { result } = renderHook(() => useIpCountryCode(false)) |
| 269 | + |
| 270 | + expect(mockedAxios.get).not.toHaveBeenCalled() |
| 271 | + expect(result.current).toBeUndefined() |
| 272 | + }) |
| 273 | + |
| 274 | + it("resolves the country from ipapi when enabled", async () => { |
| 275 | + // eslint-disable-next-line camelcase |
| 276 | + mockedAxios.get.mockResolvedValue({ data: { country_code: "HK" } }) |
| 277 | + |
| 278 | + const { result } = renderHook(() => useIpCountryCode(true)) |
| 279 | + |
| 280 | + await act(async () => {}) |
| 281 | + |
| 282 | + expect(mockedAxios.get).toHaveBeenCalled() |
| 283 | + expect(result.current).toBe("HK") |
| 284 | + }) |
| 285 | + |
| 286 | + it("stays undefined when ipapi fails", async () => { |
| 287 | + mockedAxios.get.mockRejectedValue(new Error("403 Forbidden")) |
| 288 | + |
| 289 | + const { result } = renderHook(() => useIpCountryCode(true)) |
| 290 | + |
| 291 | + await act(async () => {}) |
| 292 | + |
| 293 | + expect(result.current).toBeUndefined() |
| 294 | + expect(mockLogError).toHaveBeenCalled() |
| 295 | + }) |
| 296 | +}) |
0 commit comments