Skip to content

Colota - Android GPS Location tracker

Add unit tests for logger, theme, error boundary, server connection, settings UI

Max Dietrichcf7f652ad3e1
diff --git a/apps/docs/docs/contributing.md b/apps/docs/docs/contributing.md
index 0e475836..f7abfd2f 100644
--- a/apps/docs/docs/contributing.md
+++ b/apps/docs/docs/contributing.md
@@ -16,8 +16,9 @@ sidebar_position: 8
1. Fork the repository
2. Create a feature branch: `git checkout -b feature/batch-export`
3. Make your changes with clear commit messages
-4. Test on a real device
-5. Open a Pull Request
+4. Add or update tests for new/changed functions, hooks, and components
+5. Test on a real device
+6. Open a Pull Request
See the [Development Guide](/docs/development/architecture) for architecture details and [Local Setup](/docs/development/local-setup) for building from source.
@@ -26,7 +27,7 @@ See the [Development Guide](/docs/development/architecture) for architecture det
- **TypeScript / React Native** for the UI layer
- **Kotlin** for native Android modules
- Follow existing patterns in the codebase
-- Use `logger` instead of `console.log` — import from `src/services/logger`
+- Use `logger` instead of `console.log` — import from `src/utils/logger`
- Run before submitting:
```bash
npm run lint -w @colota/mobile
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index 753d2fd3..4888e935 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -127,7 +127,15 @@ Wraps Android's `EncryptedSharedPreferences` for AES-256-GCM encrypted credentia
| `NativeLocationService` | TypeScript bridge to the native `LocationServiceModule` with typed methods for all native operations |
| `LocationServicePermission` | Sequential Android permission requests (fine location → background location → notifications → battery exemption) |
| `SettingsService` | Bridges UI state to native SQLite with type conversion (seconds↔ms, objects↔JSON) |
+
+### Utils
+
+| Utility | Purpose |
+| --- | --- |
| `logger` | Environment-aware logging — suppresses debug/info in production via `__DEV__`, always logs warn/error |
+| `exportConverters` | Converts location data to CSV, GeoJSON, GPX, and KML export formats |
+| `queueStatus` | Maps sync queue size to color indicators for the dashboard |
+| `settingsValidation` | URL validation and security checks for endpoint configuration |
### Hooks
diff --git a/apps/mobile/src/components/features/dashboard/CoordinateDisplay.tsx b/apps/mobile/src/components/features/dashboard/CoordinateDisplay.tsx
index 27767178..e88210dd 100644
--- a/apps/mobile/src/components/features/dashboard/CoordinateDisplay.tsx
+++ b/apps/mobile/src/components/features/dashboard/CoordinateDisplay.tsx
@@ -91,12 +91,6 @@ const styles = StyleSheet.create({
flexDirection: "row",
gap: 10
},
- coordCard: {
- flex: 1,
- padding: 12,
- borderRadius: 8,
- borderWidth: 1
- },
coordLabel: {
fontSize: 10,
...fonts.semiBold,
diff --git a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx b/apps/mobile/src/components/features/dashboard/DashboardMap.tsx
index 34108edd..7bd45f51 100644
--- a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx
+++ b/apps/mobile/src/components/features/dashboard/DashboardMap.tsx
@@ -15,12 +15,11 @@ import { useFocusEffect } from "@react-navigation/native"
import { STATS_REFRESH_IDLE } from "../../../constants"
import { MapCenterButton } from "../map/MapCenterButton"
import icon from "../../../assets/icons/icon.png"
-import { logger } from "../../../services/logger"
+import { logger } from "../../../utils/logger"
type Props = {
coords: LocationCoords | null
tracking: boolean
- isPaused: boolean
activeZoneName: string | null
}
diff --git a/apps/mobile/src/components/features/dashboard/__tests__/ServerConnection.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/ServerConnection.test.tsx
new file mode 100644
index 00000000..ffb6a3e2
--- /dev/null
+++ b/apps/mobile/src/components/features/dashboard/__tests__/ServerConnection.test.tsx
@@ -0,0 +1,216 @@
+import React from "react"
+import { render, waitFor } from "@testing-library/react-native"
+
+jest.mock("../../../../hooks/useTheme", () => ({
+ useTheme: () => ({
+ colors: {
+ success: "#22c55e",
+ error: "#ef4444",
+ warning: "#f59e0b",
+ textSecondary: "#6b7280",
+ textLight: "#9ca3af",
+ text: "#000",
+ card: "#fff",
+ border: "#e5e7eb"
+ }
+ })
+}))
+
+const mockSettings = {
+ isOfflineMode: false
+}
+jest.mock("../../../../contexts/TrackingProvider", () => ({
+ useTracking: () => ({
+ settings: mockSettings
+ })
+}))
+
+const mockIsNetworkAvailable = jest.fn().mockResolvedValue(true)
+const mockGetAuthHeaders = jest.fn().mockResolvedValue({})
+jest.mock("../../../../services/NativeLocationService", () => ({
+ isNetworkAvailable: (...args: any[]) => mockIsNetworkAvailable(...args),
+ getAuthHeaders: (...args: any[]) => mockGetAuthHeaders(...args)
+}))
+
+jest.mock("@react-navigation/native", () => ({
+ useFocusEffect: (cb: () => (() => void) | void) => {
+ const R = require("react")
+ R.useEffect(() => {
+ const cleanup = cb()
+ return typeof cleanup === "function" ? cleanup : undefined
+ }, [cb])
+ }
+}))
+
+const mockFetch = jest.fn()
+global.fetch = mockFetch as any
+
+import { ServerConnection } from "../ServerConnection"
+
+const mockNavigation = { navigate: jest.fn() }
+
+beforeEach(() => {
+ jest.clearAllMocks()
+ jest.useFakeTimers()
+ mockSettings.isOfflineMode = false
+ mockIsNetworkAvailable.mockResolvedValue(true)
+ mockGetAuthHeaders.mockResolvedValue({})
+})
+
+afterEach(() => {
+ jest.useRealTimers()
+})
+
+describe("ServerConnection", () => {
+ it("shows 'Checking' initially before server check completes", () => {
+ mockFetch.mockReturnValue(new Promise(() => {}))
+
+ const { getByText } = render(
+ <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ )
+
+ expect(getByText("Checking")).toBeTruthy()
+ })
+
+ it("shows 'Connected' when server responds OK", async () => {
+ mockFetch.mockResolvedValue({ ok: true, status: 200 })
+
+ const { getByText } = render(
+ <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ )
+
+ await waitFor(() => {
+ expect(getByText("Connected")).toBeTruthy()
+ })
+ })
+
+ it("shows 'Unreachable' when fetch throws", async () => {
+ mockFetch.mockRejectedValue(new Error("Network error"))
+
+ const { getByText } = render(
+ <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ )
+
+ await waitFor(() => {
+ expect(getByText("Unreachable")).toBeTruthy()
+ })
+ })
+
+ it("shows 'No endpoint' when endpoint is empty", async () => {
+ const { getByText } = render(<ServerConnection endpoint="" navigation={mockNavigation} />)
+
+ await waitFor(() => {
+ expect(getByText("No endpoint")).toBeTruthy()
+ })
+ })
+
+ it("shows 'No endpoint' when endpoint is null", async () => {
+ const { getByText } = render(<ServerConnection endpoint={null} navigation={mockNavigation} />)
+
+ await waitFor(() => {
+ expect(getByText("No endpoint")).toBeTruthy()
+ })
+ })
+
+ it("shows 'Offline' when offline mode is enabled", async () => {
+ mockSettings.isOfflineMode = true
+
+ const { getByText } = render(
+ <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ )
+
+ await waitFor(() => {
+ expect(getByText("Offline")).toBeTruthy()
+ })
+ })
+
+ it("shows 'Device offline' when network is unavailable", async () => {
+ mockIsNetworkAvailable.mockResolvedValue(false)
+
+ const { getByText } = render(
+ <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ )
+
+ await waitFor(() => {
+ expect(getByText("Device offline")).toBeTruthy()
+ })
+ })
+
+ it("falls back to endpoint URL when /health returns 404", async () => {
+ mockFetch
+ .mockResolvedValueOnce({ ok: false, status: 404 }) // /health
+ .mockResolvedValueOnce({ ok: true, status: 200 }) // original endpoint
+
+ const { getByText } = render(
+ <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ )
+
+ await waitFor(() => {
+ expect(getByText("Connected")).toBeTruthy()
+ })
+
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ })
+
+ it("falls back to base URL when endpoint also fails", async () => {
+ mockFetch
+ .mockResolvedValueOnce({ ok: false, status: 404 }) // /health
+ .mockResolvedValueOnce({ ok: false, status: 500 }) // endpoint
+ .mockResolvedValueOnce({ ok: true, status: 200 }) // base URL
+
+ const { getByText } = render(
+ <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ )
+
+ await waitFor(() => {
+ expect(getByText("Connected")).toBeTruthy()
+ })
+
+ expect(mockFetch).toHaveBeenCalledTimes(3)
+ })
+
+ it("displays the host portion of the endpoint URL", async () => {
+ mockFetch.mockResolvedValue({ ok: true, status: 200 })
+
+ const { getByText } = render(
+ <ServerConnection endpoint="https://my-server.com/api/locations" navigation={mockNavigation} />
+ )
+
+ expect(getByText("my-server.com")).toBeTruthy()
+ })
+
+ it("displays 'Server' when endpoint is empty", () => {
+ const { getByText } = render(<ServerConnection endpoint="" navigation={mockNavigation} />)
+
+ expect(getByText("Server")).toBeTruthy()
+ })
+
+ it("includes auth headers in health check", async () => {
+ mockGetAuthHeaders.mockResolvedValue({ Authorization: "Bearer token123" })
+ mockFetch.mockResolvedValue({ ok: true, status: 200 })
+
+ render(<ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />)
+
+ await waitFor(() => {
+ expect(mockFetch).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ headers: { Authorization: "Bearer token123" }
+ })
+ )
+ })
+ })
+
+ it("proceeds without auth headers if getAuthHeaders fails", async () => {
+ mockGetAuthHeaders.mockRejectedValue(new Error("no credentials"))
+ mockFetch.mockResolvedValue({ ok: true, status: 200 })
+
+ const { getByText } = render(
+ <ServerConnection endpoint="https://example.com/api/locations" navigation={mockNavigation} />
+ )
+
+ await waitFor(() => {
+ expect(getByText("Connected")).toBeTruthy()
+ })
+ })
+})
diff --git a/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx b/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx
new file mode 100644
index 00000000..40c0d866
--- /dev/null
+++ b/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx
@@ -0,0 +1,250 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { DEFAULT_SETTINGS, TRACKING_PRESETS, Settings } from "../../../../types/global"
+
+// Mock barrel export (avoids transitive native module imports)
+jest.mock("../../../index", () => {
+ const R = require("react")
+ const { View, Text, TextInput } = require("react-native")
+ return {
+ SectionTitle: ({ children }: any) => R.createElement(Text, null, children),
+ Card: ({ children }: any) => R.createElement(View, null, children),
+ Divider: () => R.createElement(View, null),
+ NumericInput: ({ label, value, onChange, onBlur, unit, hint, placeholder: ph }: any) =>
+ R.createElement(
+ View,
+ null,
+ R.createElement(Text, null, label),
+ hint && R.createElement(Text, null, hint),
+ R.createElement(TextInput, {
+ value,
+ onChangeText: onChange,
+ onBlur,
+ placeholder: ph,
+ keyboardType: "numeric"
+ }),
+ R.createElement(Text, null, unit)
+ )
+ }
+})
+
+jest.mock("../PresetOption", () => ({
+ PresetOption: ({ preset, isSelected, onSelect }: any) => {
+ const R = require("react")
+ const { TouchableOpacity, Text } = require("react-native")
+ return R.createElement(
+ TouchableOpacity,
+ { testID: `preset-${preset}`, onPress: () => onSelect(preset) },
+ R.createElement(Text, null, preset, isSelected ? " (selected)" : "")
+ )
+ }
+}))
+
+const mockColors = {
+ primary: "#0d9488",
+ primaryDark: "#115E59",
+ border: "#e5e7eb",
+ text: "#000",
+ textSecondary: "#6b7280",
+ textLight: "#9ca3af",
+ background: "#fff",
+ info: "#3b82f6",
+ card: "#fff",
+ backgroundElevated: "#f9fafb",
+ placeholder: "#9ca3af",
+ textOnPrimary: "#fff"
+} as any
+
+import { SyncStrategySettings } from "../SyncStrategySettings"
+
+describe("SyncStrategySettings", () => {
+ let mockOnSettingsChange: jest.Mock
+ let mockOnDebouncedSave: jest.Mock
+ let mockOnImmediateSave: jest.Mock
+ let baseSettings: Settings
+
+ beforeEach(() => {
+ mockOnSettingsChange = jest.fn()
+ mockOnDebouncedSave = jest.fn()
+ mockOnImmediateSave = jest.fn()
+ baseSettings = { ...DEFAULT_SETTINGS }
+ })
+
+ function renderComponent(settingsOverride?: Partial<Settings>) {
+ const settings = { ...baseSettings, ...settingsOverride }
+ return render(
+ <SyncStrategySettings
+ settings={settings}
+ onSettingsChange={mockOnSettingsChange}
+ onDebouncedSave={mockOnDebouncedSave}
+ onImmediateSave={mockOnImmediateSave}
+ colors={mockColors}
+ />
+ )
+ }
+
+ describe("presets", () => {
+ it("renders all three presets", () => {
+ const { getByTestId } = renderComponent()
+
+ expect(getByTestId("preset-instant")).toBeTruthy()
+ expect(getByTestId("preset-balanced")).toBeTruthy()
+ expect(getByTestId("preset-powersaver")).toBeTruthy()
+ })
+
+ it("selecting a preset applies its config via onImmediateSave", () => {
+ const { getByTestId } = renderComponent()
+
+ fireEvent.press(getByTestId("preset-balanced"))
+
+ expect(mockOnImmediateSave).toHaveBeenCalledWith(
+ expect.objectContaining({
+ syncPreset: "balanced",
+ interval: TRACKING_PRESETS.balanced.interval,
+ distance: TRACKING_PRESETS.balanced.distance,
+ syncInterval: TRACKING_PRESETS.balanced.syncInterval
+ })
+ )
+ })
+ })
+
+ describe("advanced toggle", () => {
+ it("shows advanced settings when toggle is pressed", () => {
+ const { getByText, queryByText } = renderComponent()
+
+ expect(queryByText("Tracking Parameters")).toBeNull()
+
+ fireEvent.press(getByText("+ Show Advanced Settings"))
+
+ expect(getByText("Tracking Parameters")).toBeTruthy()
+ expect(getByText("Network Settings")).toBeTruthy()
+ })
+
+ it("hides advanced settings when toggle is pressed again", () => {
+ const { getByText, queryByText } = renderComponent()
+
+ fireEvent.press(getByText("+ Show Advanced Settings"))
+ expect(getByText("Tracking Parameters")).toBeTruthy()
+
+ fireEvent.press(getByText("− Hide Advanced Settings"))
+ expect(queryByText("Tracking Parameters")).toBeNull()
+ })
+ })
+
+ describe("custom banner", () => {
+ it("shows custom configuration banner when preset is custom", () => {
+ const { getByText } = renderComponent({ syncPreset: "custom" })
+
+ fireEvent.press(getByText("+ Show Advanced Settings"))
+
+ expect(getByText("Using custom configuration")).toBeTruthy()
+ })
+
+ it("does not show custom banner when a named preset is selected", () => {
+ const { getByText, queryByText } = renderComponent({ syncPreset: "instant" })
+
+ fireEvent.press(getByText("+ Show Advanced Settings"))
+
+ expect(queryByText("Using custom configuration")).toBeNull()
+ })
+ })
+
+ describe("sync interval grid", () => {
+ it("renders all sync interval options", () => {
+ const { getByText } = renderComponent()
+
+ fireEvent.press(getByText("+ Show Advanced Settings"))
+
+ expect(getByText("Instant")).toBeTruthy()
+ expect(getByText("1 min")).toBeTruthy()
+ expect(getByText("5 min")).toBeTruthy()
+ expect(getByText("15 min")).toBeTruthy()
+ })
+
+ it("selecting a sync interval sets preset to custom", () => {
+ const { getByText } = renderComponent()
+
+ fireEvent.press(getByText("+ Show Advanced Settings"))
+ fireEvent.press(getByText("5 min"))
+
+ expect(mockOnSettingsChange).toHaveBeenCalledWith(
+ expect.objectContaining({
+ syncInterval: 300,
+ syncPreset: "custom"
+ })
+ )
+ expect(mockOnDebouncedSave).toHaveBeenCalled()
+ })
+ })
+
+ describe("retry failed uploads toggle", () => {
+ it("shows delete hint when maxRetries is 5 (default)", () => {
+ const { getByText } = renderComponent({ maxRetries: 5 })
+
+ fireEvent.press(getByText("+ Show Advanced Settings"))
+
+ expect(getByText("Failed uploads are permanently deleted after 5 failed send attempts")).toBeTruthy()
+ })
+
+ it("shows keep hint when maxRetries is 0 (retry forever)", () => {
+ const { getByText } = renderComponent({ maxRetries: 0 })
+
+ fireEvent.press(getByText("+ Show Advanced Settings"))
+
+ expect(getByText("Failed uploads stay in the queue until they succeed")).toBeTruthy()
+ })
+
+ it("toggling retry on sets maxRetries to 0", () => {
+ const { getByText, getAllByRole } = renderComponent({ maxRetries: 5 })
+
+ fireEvent.press(getByText("+ Show Advanced Settings"))
+
+ const retrySwitch = getAllByRole("switch")[0]
+
+ fireEvent(retrySwitch, "valueChange", true)
+
+ expect(mockOnSettingsChange).toHaveBeenCalledWith(
+ expect.objectContaining({
+ maxRetries: 0,
+ syncPreset: "custom"
+ })
+ )
+ expect(mockOnImmediateSave).toHaveBeenCalled()
+ })
+
+ it("toggling retry off sets maxRetries to 5", () => {
+ const { getByText, getAllByRole } = renderComponent({ maxRetries: 0 })
+
+ fireEvent.press(getByText("+ Show Advanced Settings"))
+
+ const retrySwitch = getAllByRole("switch")[0]
+
+ fireEvent(retrySwitch, "valueChange", false)
+
+ expect(mockOnSettingsChange).toHaveBeenCalledWith(
+ expect.objectContaining({
+ maxRetries: 5,
+ syncPreset: "custom"
+ })
+ )
+ })
+ })
+
+ describe("filter inaccurate locations", () => {
+ it("shows accuracy threshold input when filter is enabled", () => {
+ const { getByText } = renderComponent({ filterInaccurateLocations: true })
+
+ fireEvent.press(getByText("+ Show Advanced Settings"))
+
+ expect(getByText("Accuracy Threshold")).toBeTruthy()
+ })
+
+ it("hides accuracy threshold input when filter is disabled", () => {
+ const { getByText, queryByText } = renderComponent({ filterInaccurateLocations: false })
+
+ fireEvent.press(getByText("+ Show Advanced Settings"))
+
+ expect(queryByText("Accuracy Threshold")).toBeNull()
+ })
+ })
+})
diff --git a/apps/mobile/src/components/index.ts b/apps/mobile/src/components/index.ts
index eac32ac9..a4376513 100644
--- a/apps/mobile/src/components/index.ts
+++ b/apps/mobile/src/components/index.ts
@@ -42,6 +42,5 @@ export { MapCenterButton } from "./features/map/MapCenterButton"
// Feature Components - Settings
// ============================================================================
export { StatsCard } from "./features/settings/StatsCard"
-export { PresetOption } from "./features/settings/PresetOption"
export { ConnectionSettings } from "./features/settings/ConnectionSettings"
export { SyncStrategySettings } from "./features/settings/SyncStrategySettings"
diff --git a/apps/mobile/src/components/ui/Container.tsx b/apps/mobile/src/components/ui/Container.tsx
index f2f2ef99..e74afea6 100644
--- a/apps/mobile/src/components/ui/Container.tsx
+++ b/apps/mobile/src/components/ui/Container.tsx
@@ -10,7 +10,6 @@ import { useTheme } from "../../hooks/useTheme"
type ContainerProps = {
children: React.ReactNode
style?: StyleProp<ViewStyle>
- useKeyboardAvoid?: boolean
}
export function Container({ children, style }: ContainerProps) {
diff --git a/apps/mobile/src/components/ui/ErrorBoundary.tsx b/apps/mobile/src/components/ui/ErrorBoundary.tsx
index 074d33b5..d73723c9 100644
--- a/apps/mobile/src/components/ui/ErrorBoundary.tsx
+++ b/apps/mobile/src/components/ui/ErrorBoundary.tsx
@@ -6,7 +6,7 @@ import React, { Component } from "react"
import { View, Text, StyleSheet, TouchableOpacity } from "react-native"
import { ThemeColors } from "../../types/global"
import { useTheme } from "../../hooks/useTheme"
-import { logger } from "../../services/logger"
+import { logger } from "../../utils/logger"
import { fonts, fontSizes } from "../../styles/typography"
interface ErrorBoundaryInternalProps {
diff --git a/apps/mobile/src/components/ui/__tests__/ErrorBoundary.test.tsx b/apps/mobile/src/components/ui/__tests__/ErrorBoundary.test.tsx
new file mode 100644
index 00000000..dcc24526
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/ErrorBoundary.test.tsx
@@ -0,0 +1,122 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { Text } from "react-native"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({
+ colors: {
+ background: "#fff",
+ text: "#000",
+ textSecondary: "#666",
+ primary: "#0d9488",
+ textOnPrimary: "#fff"
+ }
+ })
+}))
+
+jest.mock("../../../utils/logger", () => ({
+ logger: {
+ error: jest.fn()
+ }
+}))
+
+import { ErrorBoundary } from "../ErrorBoundary"
+import { logger } from "../../../utils/logger"
+
+beforeEach(() => {
+ jest.clearAllMocks()
+})
+
+function ThrowingChild({ shouldThrow }: { shouldThrow: boolean }) {
+ if (shouldThrow) {
+ throw new Error("Test error message")
+ }
+ return <Text>Child content</Text>
+}
+
+describe("ErrorBoundary", () => {
+ let errorSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ errorSpy = jest.spyOn(console, "error").mockImplementation()
+ })
+
+ afterEach(() => {
+ errorSpy.mockRestore()
+ })
+
+ it("renders children when no error occurs", () => {
+ const { getByText } = render(
+ <ErrorBoundary>
+ <ThrowingChild shouldThrow={false} />
+ </ErrorBoundary>
+ )
+
+ expect(getByText("Child content")).toBeTruthy()
+ })
+
+ it("renders fallback UI when child throws", () => {
+ const { getByText } = render(
+ <ErrorBoundary>
+ <ThrowingChild shouldThrow={true} />
+ </ErrorBoundary>
+ )
+
+ expect(getByText("Something went wrong")).toBeTruthy()
+ expect(getByText("Test error message")).toBeTruthy()
+ expect(getByText("Try Again")).toBeTruthy()
+ })
+
+ it("logs error via logger.error", () => {
+ render(
+ <ErrorBoundary>
+ <ThrowingChild shouldThrow={true} />
+ </ErrorBoundary>
+ )
+
+ expect(logger.error).toHaveBeenCalledWith(
+ "ErrorBoundary caught an error:",
+ expect.any(Error),
+ expect.objectContaining({ componentStack: expect.any(String) })
+ )
+ })
+
+ it("recovers when Try Again is pressed", () => {
+ let shouldThrow = true
+
+ function ToggleChild() {
+ if (shouldThrow) {
+ throw new Error("recoverable error")
+ }
+ return <Text>Recovered</Text>
+ }
+
+ const { getByText } = render(
+ <ErrorBoundary>
+ <ToggleChild />
+ </ErrorBoundary>
+ )
+
+ expect(getByText("Something went wrong")).toBeTruthy()
+
+ shouldThrow = false
+
+ fireEvent.press(getByText("Try Again"))
+
+ expect(getByText("Recovered")).toBeTruthy()
+ })
+
+ it("shows generic message when error has no message", () => {
+ function EmptyErrorChild(): React.ReactNode {
+ throw new Error("")
+ }
+
+ const { getByText } = render(
+ <ErrorBoundary>
+ <EmptyErrorChild />
+ </ErrorBoundary>
+ )
+
+ expect(getByText("Something went wrong")).toBeTruthy()
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/NumericInput.test.tsx b/apps/mobile/src/components/ui/__tests__/NumericInput.test.tsx
new file mode 100644
index 00000000..71fec407
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/NumericInput.test.tsx
@@ -0,0 +1,93 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { NumericInput } from "../NumericInput"
+
+const mockColors = {
+ text: "#000",
+ textLight: "#9ca3af",
+ textSecondary: "#6b7280",
+ border: "#e5e7eb",
+ backgroundElevated: "#f9fafb",
+ placeholder: "#9ca3af"
+} as any
+
+describe("NumericInput", () => {
+ const mockOnChange = jest.fn()
+ const mockOnBlur = jest.fn()
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ })
+
+ function renderInput(overrides: Partial<React.ComponentProps<typeof NumericInput>> = {}) {
+ return render(
+ <NumericInput
+ label="Test Label"
+ value="10"
+ onChange={mockOnChange}
+ onBlur={mockOnBlur}
+ unit="seconds"
+ colors={mockColors}
+ {...overrides}
+ />
+ )
+ }
+
+ it("renders label, value, and unit", () => {
+ const { getByText, getByDisplayValue } = renderInput()
+
+ expect(getByText("Test Label")).toBeTruthy()
+ expect(getByDisplayValue("10")).toBeTruthy()
+ expect(getByText("seconds")).toBeTruthy()
+ })
+
+ it("renders hint when provided", () => {
+ const { getByText } = renderInput({ hint: "Enter a number" })
+
+ expect(getByText("Enter a number")).toBeTruthy()
+ })
+
+ it("does not render hint when not provided", () => {
+ const { queryByText } = renderInput()
+
+ expect(queryByText("Enter a number")).toBeNull()
+ })
+
+ it("calls onChange when text changes", () => {
+ const { getByDisplayValue } = renderInput()
+
+ fireEvent.changeText(getByDisplayValue("10"), "25")
+
+ expect(mockOnChange).toHaveBeenCalledWith("25")
+ })
+
+ it("calls onBlur when input loses focus", () => {
+ const { getByDisplayValue } = renderInput()
+
+ fireEvent(getByDisplayValue("10"), "blur")
+
+ expect(mockOnBlur).toHaveBeenCalled()
+ })
+
+ it("uses numeric keyboard type", () => {
+ const { getByDisplayValue } = renderInput()
+
+ const input = getByDisplayValue("10")
+ expect(input.props.keyboardType).toBe("numeric")
+ })
+
+ it("displays placeholder text", () => {
+ const { getByPlaceholderText } = renderInput({
+ value: "",
+ placeholder: "50"
+ })
+
+ expect(getByPlaceholderText("50")).toBeTruthy()
+ })
+
+ it("renders different units correctly", () => {
+ const { getByText } = renderInput({ unit: "meters" })
+
+ expect(getByText("meters")).toBeTruthy()
+ })
+})
diff --git a/apps/mobile/src/contexts/TrackingProvider.tsx b/apps/mobile/src/contexts/TrackingProvider.tsx
index 5e61bae8..dc198324 100644
--- a/apps/mobile/src/contexts/TrackingProvider.tsx
+++ b/apps/mobile/src/contexts/TrackingProvider.tsx
@@ -8,7 +8,7 @@ import { Settings, DEFAULT_SETTINGS, LocationCoords, ApiTemplateName } from "../
import { useLocationTracking } from "../hooks/useLocationTracking"
import NativeLocationService from "../services/NativeLocationService"
import SettingsService from "../services/SettingsService"
-import { logger } from "../services/logger"
+import { logger } from "../utils/logger"
type TrackingContextType = {
settings: Settings
diff --git a/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx b/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx
index 65f91660..1608fb06 100644
--- a/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx
+++ b/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx
@@ -2,7 +2,6 @@ import React from "react"
import { renderHook, act } from "@testing-library/react-native"
import { DEFAULT_SETTINGS } from "../../types/global"
-// Mock the services
jest.mock("../../services/NativeLocationService", () => ({
getAllSettings: jest.fn().mockResolvedValue({}),
start: jest.fn().mockResolvedValue(undefined),
@@ -17,22 +16,36 @@ jest.mock("../../services/SettingsService", () => ({
updateSetting: jest.fn().mockResolvedValue(true)
}))
-// Mock useLocationTracking hook — use require() inside factory to avoid out-of-scope reference
+const mockStartTracking = jest.fn().mockResolvedValue(undefined)
+const mockStopTracking = jest.fn()
+const mockRestartTracking = jest.fn().mockResolvedValue(undefined)
+const mockReconnect = jest.fn()
+
jest.mock("../../hooks/useLocationTracking", () => ({
useLocationTracking: jest.fn(() => ({
coords: null,
tracking: false,
- startTracking: jest.fn().mockResolvedValue(undefined),
- stopTracking: jest.fn(),
- restartTracking: jest.fn().mockResolvedValue(undefined),
- reconnect: jest.fn(),
+ startTracking: mockStartTracking,
+ stopTracking: mockStopTracking,
+ restartTracking: mockRestartTracking,
+ reconnect: mockReconnect,
settings: require("../../types/global").DEFAULT_SETTINGS
}))
}))
+jest.mock("../../utils/logger", () => ({
+ logger: {
+ debug: jest.fn(),
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn()
+ }
+}))
+
import { TrackingProvider, useTracking } from "../TrackingProvider"
import NativeLocationService from "../../services/NativeLocationService"
import SettingsService from "../../services/SettingsService"
+import { logger } from "../../utils/logger"
const mockGetAllSettings = NativeLocationService.getAllSettings as jest.Mock
const mockUpdateMultiple = SettingsService.updateMultiple as jest.Mock
@@ -41,6 +54,8 @@ beforeEach(() => {
jest.clearAllMocks()
})
+const wrapper = ({ children }: { children: React.ReactNode }) => <TrackingProvider>{children}</TrackingProvider>
+
describe("useTracking", () => {
it("throws when used outside TrackingProvider", () => {
const spy = jest.spyOn(console, "error").mockImplementation()
@@ -55,8 +70,6 @@ describe("useTracking", () => {
it("provides default settings on initial render", async () => {
mockGetAllSettings.mockResolvedValueOnce({})
- const wrapper = ({ children }: { children: React.ReactNode }) => <TrackingProvider>{children}</TrackingProvider>
-
const { result } = renderHook(() => useTracking(), { wrapper })
expect(result.current.settings.interval).toBe(DEFAULT_SETTINGS.interval)
@@ -76,8 +89,6 @@ describe("useTracking", () => {
apiTemplate: "dawarich"
})
- const wrapper = ({ children }: { children: React.ReactNode }) => <TrackingProvider>{children}</TrackingProvider>
-
const { result } = renderHook(() => useTracking(), { wrapper })
await act(async () => {
@@ -97,8 +108,6 @@ describe("useTracking", () => {
it("calls SettingsService.updateMultiple when setSettings is called", async () => {
mockGetAllSettings.mockResolvedValueOnce({})
- const wrapper = ({ children }: { children: React.ReactNode }) => <TrackingProvider>{children}</TrackingProvider>
-
const { result } = renderHook(() => useTracking(), { wrapper })
const newSettings = { ...DEFAULT_SETTINGS, interval: 30, endpoint: "https://new.com" }
@@ -109,4 +118,128 @@ describe("useTracking", () => {
expect(mockUpdateMultiple).toHaveBeenCalledWith(newSettings)
})
+
+ it("initializes DB with defaults when storage is empty", async () => {
+ mockGetAllSettings.mockResolvedValueOnce({})
+
+ renderHook(() => useTracking(), { wrapper })
+
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 100))
+ })
+
+ expect(mockUpdateMultiple).toHaveBeenCalledWith(DEFAULT_SETTINGS)
+ })
+
+ it("sets error state when hydration fails", async () => {
+ mockGetAllSettings.mockRejectedValueOnce(new Error("DB read failed"))
+
+ const { result } = renderHook(() => useTracking(), { wrapper })
+
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 100))
+ })
+
+ expect(result.current.error).toBeInstanceOf(Error)
+ expect(result.current.error?.message).toBe("DB read failed")
+ expect(result.current.isLoading).toBe(false)
+ expect(logger.error).toHaveBeenCalledWith("[TrackingContext] Hydration failed:", expect.any(Error))
+ })
+
+ it("sets isLoading to false after successful hydration", async () => {
+ mockGetAllSettings.mockResolvedValueOnce({ interval: "5000" })
+
+ const { result } = renderHook(() => useTracking(), { wrapper })
+
+ expect(result.current.isLoading).toBe(true)
+
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 100))
+ })
+
+ expect(result.current.isLoading).toBe(false)
+ })
+
+ it("reconnects when tracking was active in native storage", async () => {
+ mockGetAllSettings.mockResolvedValueOnce({
+ interval: "5000",
+ tracking_enabled: "true"
+ })
+
+ renderHook(() => useTracking(), { wrapper })
+
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 100))
+ })
+
+ expect(mockReconnect).toHaveBeenCalled()
+ })
+
+ it("does not reconnect when tracking was not active", async () => {
+ mockGetAllSettings.mockResolvedValueOnce({
+ interval: "5000",
+ tracking_enabled: "false"
+ })
+
+ renderHook(() => useTracking(), { wrapper })
+
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 100))
+ })
+
+ expect(mockReconnect).not.toHaveBeenCalled()
+ })
+
+ it("sets error when setSettings persistence fails", async () => {
+ mockGetAllSettings.mockResolvedValueOnce({ interval: "5000" })
+
+ const { result } = renderHook(() => useTracking(), { wrapper })
+
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 100))
+ })
+
+ mockUpdateMultiple.mockRejectedValueOnce(new Error("Write failed"))
+
+ await act(async () => {
+ try {
+ await result.current.setSettings({ ...DEFAULT_SETTINGS, interval: 99 })
+ } catch {
+ // expected
+ }
+ })
+
+ expect(result.current.error?.message).toBe("Write failed")
+ expect(logger.error).toHaveBeenCalledWith("[TrackingContext] Persistence failed:", expect.any(Error))
+ })
+
+ it("clears previous error on successful setSettings", async () => {
+ mockGetAllSettings.mockResolvedValueOnce({ interval: "5000" })
+
+ const { result } = renderHook(() => useTracking(), { wrapper })
+
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 100))
+ })
+
+ mockUpdateMultiple.mockRejectedValueOnce(new Error("fail"))
+
+ await act(async () => {
+ try {
+ await result.current.setSettings({ ...DEFAULT_SETTINGS })
+ } catch {
+ // expected
+ }
+ })
+
+ expect(result.current.error).toBeTruthy()
+
+ mockUpdateMultiple.mockResolvedValueOnce(undefined)
+
+ await act(async () => {
+ await result.current.setSettings({ ...DEFAULT_SETTINGS, interval: 10 })
+ })
+
+ expect(result.current.error).toBeNull()
+ })
})
diff --git a/apps/mobile/src/hooks/__tests__/useTheme.test.tsx b/apps/mobile/src/hooks/__tests__/useTheme.test.tsx
new file mode 100644
index 00000000..0372aacb
--- /dev/null
+++ b/apps/mobile/src/hooks/__tests__/useTheme.test.tsx
@@ -0,0 +1,123 @@
+import React from "react"
+import { renderHook, act } from "@testing-library/react-native"
+import { Appearance } from "react-native"
+
+import { ThemeProvider, useTheme } from "../useTheme"
+
+let appearanceListener: ((prefs: { colorScheme: string | null }) => void) | null = null
+
+jest.spyOn(Appearance, "getColorScheme").mockReturnValue("light")
+jest.spyOn(Appearance, "addChangeListener").mockImplementation((cb: any) => {
+ appearanceListener = cb
+ return { remove: jest.fn() }
+})
+
+const wrapper = ({ children }: { children: React.ReactNode }) => <ThemeProvider>{children}</ThemeProvider>
+
+beforeEach(() => {
+ appearanceListener = null
+ ;(Appearance.getColorScheme as jest.Mock).mockReturnValue("light")
+})
+
+describe("useTheme", () => {
+ it("throws when used outside ThemeProvider", () => {
+ const spy = jest.spyOn(console, "error").mockImplementation()
+
+ expect(() => {
+ renderHook(() => useTheme())
+ }).toThrow("useTheme must be used within a ThemeProvider")
+
+ spy.mockRestore()
+ })
+
+ it("initializes with system theme (light)", () => {
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ expect(result.current.mode).toBe("light")
+ expect(result.current.isDark).toBe(false)
+ expect(result.current.colors).toBeDefined()
+ expect(result.current.colors.primary).toBeDefined()
+ })
+
+ it("initializes with system theme (dark)", () => {
+ ;(Appearance.getColorScheme as jest.Mock).mockReturnValue("dark")
+
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ expect(result.current.mode).toBe("dark")
+ expect(result.current.isDark).toBe(true)
+ })
+
+ it("defaults to light when system scheme is null", () => {
+ ;(Appearance.getColorScheme as jest.Mock).mockReturnValue(null)
+
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ expect(result.current.mode).toBe("light")
+ })
+
+ it("toggleTheme switches from light to dark", () => {
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ act(() => {
+ result.current.toggleTheme()
+ })
+
+ expect(result.current.mode).toBe("dark")
+ expect(result.current.isDark).toBe(true)
+ })
+
+ it("toggleTheme switches back from dark to light", () => {
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ act(() => {
+ result.current.toggleTheme()
+ })
+ act(() => {
+ result.current.toggleTheme()
+ })
+
+ expect(result.current.mode).toBe("light")
+ expect(result.current.isDark).toBe(false)
+ })
+
+ it("follows system theme changes when no manual override", () => {
+ renderHook(() => useTheme(), { wrapper })
+
+ expect(appearanceListener).not.toBeNull()
+
+ act(() => {
+ appearanceListener!({ colorScheme: "dark" })
+ })
+
+ expect(appearanceListener).toBeDefined()
+ })
+
+ it("ignores system theme changes after manual toggle", () => {
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ act(() => {
+ result.current.toggleTheme()
+ })
+ expect(result.current.mode).toBe("dark")
+ act(() => {
+ appearanceListener?.({ colorScheme: "light" })
+ })
+
+ expect(result.current.mode).toBe("dark")
+ })
+
+ it("provides different color objects for light and dark modes", () => {
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ const lightColors = result.current.colors
+
+ act(() => {
+ result.current.toggleTheme()
+ })
+
+ const darkColors = result.current.colors
+
+ expect(lightColors).not.toBe(darkColors)
+ })
+})
diff --git a/apps/mobile/src/hooks/useAutoSave.ts b/apps/mobile/src/hooks/useAutoSave.ts
index e772f8ed..f90fe789 100644
--- a/apps/mobile/src/hooks/useAutoSave.ts
+++ b/apps/mobile/src/hooks/useAutoSave.ts
@@ -6,7 +6,7 @@
import { useState, useCallback } from "react"
import { useTimeout } from "./useTimeout"
import { AUTOSAVE_DEBOUNCE_MS, SAVE_SUCCESS_DISPLAY_MS } from "../constants"
-import { logger } from "../services/logger"
+import { logger } from "../utils/logger"
/**
* Hook that encapsulates the debounced auto-save pattern used across settings screens.
diff --git a/apps/mobile/src/hooks/useLocationTracking.ts b/apps/mobile/src/hooks/useLocationTracking.ts
index 0517163d..1428c354 100644
--- a/apps/mobile/src/hooks/useLocationTracking.ts
+++ b/apps/mobile/src/hooks/useLocationTracking.ts
@@ -8,7 +8,7 @@ import { NativeEventEmitter, NativeModules, Alert } from "react-native"
import NativeLocationService from "../services/NativeLocationService"
import { LocationCoords, Settings, LocationTrackingResult } from "../types/global"
import { ensurePermissions } from "../services/LocationServicePermission"
-import { logger } from "../services/logger"
+import { logger } from "../utils/logger"
const { LocationServiceModule } = NativeModules
const locationEventEmitter = new NativeEventEmitter(LocationServiceModule)
diff --git a/apps/mobile/src/screens/AboutScreen.tsx b/apps/mobile/src/screens/AboutScreen.tsx
index 430ce9fe..c89eec70 100644
--- a/apps/mobile/src/screens/AboutScreen.tsx
+++ b/apps/mobile/src/screens/AboutScreen.tsx
@@ -13,7 +13,7 @@ import { Card, Container, Divider, Footer } from "../components"
import NativeLocationService from "../services/NativeLocationService"
import icon from "../assets/icons/icon.png"
import { REPO_URL, PRIVACY_POLICY_URL } from "../constants"
-import { logger } from "../services/logger"
+import { logger } from "../utils/logger"
// Helper function to map SDK to Android version
function getAndroidVersion(sdkVersion: number): string {
diff --git a/apps/mobile/src/screens/AuthSettingsScreen.tsx b/apps/mobile/src/screens/AuthSettingsScreen.tsx
index 461db0bc..f3945634 100644
--- a/apps/mobile/src/screens/AuthSettingsScreen.tsx
+++ b/apps/mobile/src/screens/AuthSettingsScreen.tsx
@@ -12,7 +12,7 @@ import { useTracking } from "../contexts/TrackingProvider"
import { fonts, fontSizes } from "../styles/typography"
import { SectionTitle, FloatingSaveIndicator, Container, Card, Divider } from "../components"
import NativeLocationService from "../services/NativeLocationService"
-import { logger } from "../services/logger"
+import { logger } from "../utils/logger"
const AUTH_TYPES: { value: AuthType; label: string }[] = [
{ value: "none", label: "None" },
diff --git a/apps/mobile/src/screens/DashboardScreen.tsx b/apps/mobile/src/screens/DashboardScreen.tsx
index f73277f0..d739b514 100644
--- a/apps/mobile/src/screens/DashboardScreen.tsx
+++ b/apps/mobile/src/screens/DashboardScreen.tsx
@@ -22,7 +22,7 @@ import {
} from "../components"
import { STATS_REFRESH_IDLE } from "../constants"
import { Square, Play } from "lucide-react-native"
-import { logger } from "../services/logger"
+import { logger } from "../utils/logger"
export function DashboardScreen({ navigation }: ScreenProps) {
const { coords, settings, tracking, startTracking, stopTracking, setSettings } = useTracking()
@@ -43,8 +43,6 @@ export function DashboardScreen({ navigation }: ScreenProps) {
// Animation for button
const buttonScale = useRef(new Animated.Value(1)).current
- const isInPauseZone = !!currentPauseZone
-
const handleStart = async () => {
// Bounce animation
Animated.sequence([
@@ -158,12 +156,7 @@ export function DashboardScreen({ navigation }: ScreenProps) {
onTouchStart={() => setScrollEnabled(false)}
onTouchEnd={() => setScrollEnabled(true)}
>
- <DashboardMap
- coords={coords}
- tracking={tracking}
- isPaused={isInPauseZone}
- activeZoneName={currentPauseZone}
- />
+ <DashboardMap coords={coords} tracking={tracking} activeZoneName={currentPauseZone} />
</View>
{/* Tracking Control Button */}
diff --git a/apps/mobile/src/screens/DataManagementScreen.tsx b/apps/mobile/src/screens/DataManagementScreen.tsx
index 850ec804..42bcf34a 100644
--- a/apps/mobile/src/screens/DataManagementScreen.tsx
+++ b/apps/mobile/src/screens/DataManagementScreen.tsx
@@ -23,7 +23,7 @@ import NativeLocationService from "../services/NativeLocationService"
import { Button, SectionTitle, Card, Container, Divider, FloatingSaveIndicator } from "../components"
import { STATS_REFRESH_FAST } from "../constants"
import { useTimeout } from "../hooks/useTimeout"
-import { logger } from "../services/logger"
+import { logger } from "../utils/logger"
export function DataManagementScreen({}: ScreenProps) {
const { colors } = useTheme()
diff --git a/apps/mobile/src/screens/ExportDataScreen.tsx b/apps/mobile/src/screens/ExportDataScreen.tsx
index 0ec02f7e..3d37cbd4 100644
--- a/apps/mobile/src/screens/ExportDataScreen.tsx
+++ b/apps/mobile/src/screens/ExportDataScreen.tsx
@@ -12,7 +12,7 @@ import { useTheme } from "../hooks/useTheme"
import { ThemeColors, LocationCoords } from "../types/global"
import NativeLocationService from "../services/NativeLocationService"
import { LARGE_FILE_THRESHOLD, formatBytes, getByteSize, EXPORT_FORMATS, ExportFormat } from "../utils/exportConverters"
-import { logger } from "../services/logger"
+import { logger } from "../utils/logger"
interface ExportStats {
totalLocations: number
diff --git a/apps/mobile/src/screens/GeofenceScreen.tsx b/apps/mobile/src/screens/GeofenceScreen.tsx
index 3942d7ea..8f3db09a 100644
--- a/apps/mobile/src/screens/GeofenceScreen.tsx
+++ b/apps/mobile/src/screens/GeofenceScreen.tsx
@@ -26,7 +26,7 @@ import { Container, SectionTitle, Card } from "../components"
import { useFocusEffect } from "@react-navigation/native"
import { STATS_REFRESH_IDLE } from "../constants"
import { MapCenterButton } from "../components/features/map/MapCenterButton"
-import { logger } from "../services/logger"
+import { logger } from "../utils/logger"
export function GeofenceScreen({}: ScreenProps) {
const { coords, tracking } = useTracking()
diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsx
index c8861199..73ad6260 100644
--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx
+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx
@@ -12,7 +12,7 @@ import { useTheme } from "../hooks/useTheme"
import { ThemeColors } from "../types/global"
import NativeLocationService from "../services/NativeLocationService"
import { STATS_REFRESH_FAST } from "../constants"
-import { logger } from "../services/logger"
+import { logger } from "../utils/logger"
// Types
interface LocationData {
diff --git a/apps/mobile/src/screens/SettingsScreen.tsx b/apps/mobile/src/screens/SettingsScreen.tsx
index 6edf2e1a..bd7476f4 100644
--- a/apps/mobile/src/screens/SettingsScreen.tsx
+++ b/apps/mobile/src/screens/SettingsScreen.tsx
@@ -16,7 +16,7 @@ import { fonts } from "../styles/typography"
import { SectionTitle, Card, Container, Divider } from "../components"
import { ChevronRight } from "lucide-react-native"
import { StatsCard } from "../components"
-import { logger } from "../services/logger"
+import { logger } from "../utils/logger"
import { ConnectionSettings } from "../components/features/settings/ConnectionSettings"
import { SyncStrategySettings } from "../components/features/settings/SyncStrategySettings"
@@ -232,10 +232,5 @@ const styles = StyleSheet.create({
linkSub: {
fontSize: 13,
...fonts.regular
- },
- linkArrow: {
- fontSize: 28,
- ...fonts.regular,
- marginLeft: 12
}
})
diff --git a/apps/mobile/src/services/LocationServicePermission.ts b/apps/mobile/src/services/LocationServicePermission.ts
index ab7a5485..469d8d0c 100644
--- a/apps/mobile/src/services/LocationServicePermission.ts
+++ b/apps/mobile/src/services/LocationServicePermission.ts
@@ -5,7 +5,7 @@
import { Platform, PermissionsAndroid, Alert } from "react-native"
import NativeLocationService from "./NativeLocationService"
-import { logger } from "./logger"
+import { logger } from "../utils/logger"
/**
* Permission status for location tracking
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index 0718ff94..0b3bcc5f 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -5,7 +5,7 @@
import { NativeModules } from "react-native"
import { AuthConfig, DatabaseStats, Geofence, Settings } from "../types/global"
-import { logger } from "./logger"
+import { logger } from "../utils/logger"
const { LocationServiceModule, BuildConfigModule } = NativeModules
diff --git a/apps/mobile/src/services/SettingsService.ts b/apps/mobile/src/services/SettingsService.ts
index 08ad277c..bc62183c 100644
--- a/apps/mobile/src/services/SettingsService.ts
+++ b/apps/mobile/src/services/SettingsService.ts
@@ -5,7 +5,7 @@
import NativeLocationService from "./NativeLocationService"
import { Settings } from "../types/global"
-import { logger } from "./logger"
+import { logger } from "../utils/logger"
/**
* Bridge between UI state and native SQLite configuration.
diff --git a/apps/mobile/src/utils/__tests__/logger.test.ts b/apps/mobile/src/utils/__tests__/logger.test.ts
new file mode 100644
index 00000000..1de0e3d7
--- /dev/null
+++ b/apps/mobile/src/utils/__tests__/logger.test.ts
@@ -0,0 +1,87 @@
+const originalDev = (global as any).__DEV__
+
+beforeEach(() => {
+ jest.spyOn(console, "log").mockImplementation()
+ jest.spyOn(console, "warn").mockImplementation()
+ jest.spyOn(console, "error").mockImplementation()
+})
+
+afterEach(() => {
+ jest.restoreAllMocks()
+ jest.resetModules()
+ ;(global as any).__DEV__ = originalDev
+})
+
+function loadLogger() {
+ return require("../logger").logger
+}
+
+describe("logger", () => {
+ describe("in development (__DEV__ = true)", () => {
+ beforeEach(() => {
+ ;(global as any).__DEV__ = true
+ })
+
+ it("debug logs via console.log", () => {
+ const logger = loadLogger()
+ logger.debug("test message", 123)
+
+ expect(console.log).toHaveBeenCalledWith("test message", 123)
+ })
+
+ it("info logs via console.log", () => {
+ const logger = loadLogger()
+ logger.info("info message")
+
+ expect(console.log).toHaveBeenCalledWith("info message")
+ })
+
+ it("warn logs via console.warn", () => {
+ const logger = loadLogger()
+ logger.warn("warning")
+
+ expect(console.warn).toHaveBeenCalledWith("warning")
+ })
+
+ it("error logs via console.error", () => {
+ const logger = loadLogger()
+ logger.error("error", new Error("test"))
+
+ expect(console.error).toHaveBeenCalledWith("error", expect.any(Error))
+ })
+ })
+
+ describe("in production (__DEV__ = false)", () => {
+ beforeEach(() => {
+ ;(global as any).__DEV__ = false
+ })
+
+ it("debug is suppressed", () => {
+ const logger = loadLogger()
+ logger.debug("should not appear")
+
+ expect(console.log).not.toHaveBeenCalled()
+ })
+
+ it("info is suppressed", () => {
+ const logger = loadLogger()
+ logger.info("should not appear")
+
+ expect(console.log).not.toHaveBeenCalled()
+ })
+
+ it("warn still logs", () => {
+ const logger = loadLogger()
+ logger.warn("visible warning")
+
+ expect(console.warn).toHaveBeenCalledWith("visible warning")
+ })
+
+ it("error still logs", () => {
+ const logger = loadLogger()
+ logger.error("visible error")
+
+ expect(console.error).toHaveBeenCalledWith("visible error")
+ })
+ })
+})
diff --git a/apps/mobile/src/services/logger.ts b/apps/mobile/src/utils/logger.ts
similarity index 94%
rename from apps/mobile/src/services/logger.ts
rename to apps/mobile/src/utils/logger.ts
index b2ac4f57..e7a8ac5e 100644
--- a/apps/mobile/src/services/logger.ts
+++ b/apps/mobile/src/utils/logger.ts
@@ -6,8 +6,6 @@
* - warn/error: Always logged
*/
-/* eslint-disable no-console */
-
export const logger = {
debug: (...args: unknown[]) => {
if (__DEV__) console.log(...args)