Colota - Android GPS Location tracker
Add unit tests for uncovered screens and components
Max Dietrich9738ca0e3062
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.ktindex 35c4cf10..e3f6bba6 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/ProfileManagerTest.kt@@ -419,6 +419,32 @@ class ProfileManagerTest {assertEquals("Car Mode", switchedProfileName)}+ @Test+ fun `applies new tracking interval when switching between profiles`() = runTest {+ val charging = chargingProfile(id = 1, intervalMs = 10000, priority = 10)+ val carMode = carModeProfile(id = 2, intervalMs = 3000, priority = 20)+ every { profileHelper.getEnabledProfiles() } returns listOf(carMode, charging)++ val manager = createManager()++ // Activate charging profile - interval should be 10s+ manager.onChargingStateChanged(true)+ assertEquals("Charging", switchedProfileName)+ assertEquals(10000L, switchedInterval)++ // Enable car mode - higher priority takes over, interval switches to 3s+ manager.onCarModeStateChanged(true)+ assertEquals("Car Mode", switchedProfileName)+ assertEquals(3000L, switchedInterval)+ assertEquals(5f, switchedDistance, 0.01f)+ assertEquals(60, switchedSyncInterval)++ // Disable car mode - charging still active, falls back immediately+ manager.onCarModeStateChanged(false)+ assertEquals("Charging", switchedProfileName)+ assertEquals(10000L, switchedInterval)+ }+// --- Immediate deactivation when profile disabled/deleted ---@Testdiff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/PayloadBuilderTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/PayloadBuilderTest.ktindex 7b2f84b9..bccb72cf 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/sync/PayloadBuilderTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/PayloadBuilderTest.kt@@ -268,6 +268,116 @@ class PayloadBuilderTest {assertNull(builder.parseCustomFields("not json"))}+ // --- buildPayload custom fields edge-case tests ---++ @Test+ fun `buildPayload includes multiple custom fields`() {+ val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f)+ val customFields = mapOf(+ "_type" to "location",+ "device" to "phone1",+ "region" to "eu-west"+ )++ val payload = builder.buildPayload(+ location = location,+ batteryLevel = 80,+ batteryStatus = 2,+ fieldMap = emptyMap(),+ timestamp = 1700000000L,+ customFields = customFields+ )++ assertEquals("location", payload.getString("_type"))+ assertEquals("phone1", payload.getString("device"))+ assertEquals("eu-west", payload.getString("region"))+ }++ @Test+ fun `buildPayload custom field does not override standard fields`() {+ val location = createMockLocation(lat = 52.52, lon = 13.405, acc = 5.0f, speed = 0.0f)+ // Custom field uses the same key "lat" as the standard latitude field+ val customFields = mapOf("lat" to "999.0")++ val payload = builder.buildPayload(+ location = location,+ batteryLevel = 80,+ batteryStatus = 2,+ fieldMap = emptyMap(),+ timestamp = 1700000000L,+ customFields = customFields+ )++ // Standard fields are written after custom fields, so the standard value wins+ assertEquals(52.52, payload.getDouble("lat"), 0.001)+ }++ @Test+ fun `buildPayload with empty custom fields map`() {+ val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f)+ val customFields = emptyMap<String, String>()++ val payload = builder.buildPayload(+ location = location,+ batteryLevel = 80,+ batteryStatus = 2,+ fieldMap = emptyMap(),+ timestamp = 1700000000L,+ customFields = customFields+ )++ // Only standard fields should be present (no altitude/speed/bearing since mocked without them)+ assertEquals(52.0, payload.getDouble("lat"), 0.001)+ assertEquals(13.0, payload.getDouble("lon"), 0.001)+ assertEquals(5, payload.getInt("acc"))+ assertEquals(80, payload.getInt("batt"))+ assertEquals(2, payload.getInt("bs"))+ assertEquals(1700000000L, payload.getLong("tst"))+ // Verify the payload has exactly the expected keys (no extras from custom fields)+ val keys = payload.keys().asSequence().toSet()+ assertEquals(setOf("lat", "lon", "acc", "vel", "batt", "bs", "tst"), keys)+ }++ @Test+ fun `buildPayload includes blank custom field keys`() {+ val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f)+ // The implementation does not filter blank keys - they are passed through as-is+ val customFields = mapOf("" to "some_value", "valid" to "data")++ val payload = builder.buildPayload(+ location = location,+ batteryLevel = 80,+ batteryStatus = 2,+ fieldMap = emptyMap(),+ timestamp = 1700000000L,+ customFields = customFields+ )++ // Blank key is included because buildPayload does not filter it+ assertEquals("some_value", payload.getString(""))+ assertEquals("data", payload.getString("valid"))+ }++ @Test+ fun `buildPayload includes blank custom field values`() {+ val location = createMockLocation(lat = 52.0, lon = 13.0, acc = 5.0f, speed = 0.0f)+ // The implementation does not filter blank values - they are passed through as-is+ val customFields = mapOf("myfield" to "", "other" to "ok")++ val payload = builder.buildPayload(+ location = location,+ batteryLevel = 80,+ batteryStatus = 2,+ fieldMap = emptyMap(),+ timestamp = 1700000000L,+ customFields = customFields+ )++ // Blank value is included because buildPayload does not filter it+ assertEquals("", payload.getString("myfield"))+ assertEquals("ok", payload.getString("other"))+ }+// --- helpers ---private fun createMockLocation(diff --git a/apps/mobile/src/components/features/inspector/__tests__/LocationTable.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/LocationTable.test.tsxnew file mode 100644index 00000000..6592a8f1--- /dev/null+++ b/apps/mobile/src/components/features/inspector/__tests__/LocationTable.test.tsx@@ -0,0 +1,166 @@+import React from "react"+import { render } from "@testing-library/react-native"+import { LocationCoords } from "../../../../types/global"++// --- Mocks ---++jest.mock("../../../../utils/geo", () => ({+ formatTime: jest.fn((_ts: number) => "12:00:00"),+ getSpeedUnit: jest.fn(() => ({ factor: 3.6, unit: "km/h" }))+}))++jest.mock("../../../../styles/typography", () => ({+ fonts: { regular: {}, bold: {}, semiBold: {} }+}))++import { LocationTable } from "../LocationTable"++const mockColors = {+ text: "#000",+ textSecondary: "#6b7280",+ border: "#e5e7eb",+ surface: "#fff"+} as any++const locations: LocationCoords[] = [+ {+ latitude: 48.1,+ longitude: 11.5,+ accuracy: 10,+ timestamp: 1000,+ altitude: 500,+ speed: 5,+ bearing: 90,+ battery: 80,+ battery_status: 2+ },+ {+ latitude: 48.2,+ longitude: 11.6,+ accuracy: 15,+ timestamp: 1030,+ altitude: 510,+ speed: 8,+ bearing: 180,+ battery: 79,+ battery_status: 3+ },+ {+ latitude: 48.3,+ longitude: 11.7,+ accuracy: 20,+ timestamp: 1060,+ altitude: null as any,+ speed: null as any,+ bearing: null as any,+ battery: null as any,+ battery_status: null as any+ }+]++describe("LocationTable", () => {+ beforeEach(() => {+ jest.clearAllMocks()+ })++ it("shows empty state message when no locations", () => {+ const { getByText } = render(<LocationTable locations={[]} colors={mockColors} />)++ expect(getByText("No data for this day")).toBeTruthy()+ })++ it("renders table header with column names", () => {+ const { getByText } = render(<LocationTable locations={locations} colors={mockColors} />)++ expect(getByText("Time")).toBeTruthy()+ expect(getByText("Δs")).toBeTruthy()+ expect(getByText("Lat")).toBeTruthy()+ expect(getByText("Lon")).toBeTruthy()+ expect(getByText("Acc")).toBeTruthy()+ expect(getByText("km/h")).toBeTruthy()+ expect(getByText("Alt")).toBeTruthy()+ expect(getByText("Bear")).toBeTruthy()+ expect(getByText("Batt")).toBeTruthy()+ expect(getByText("Status")).toBeTruthy()+ })++ it("renders location rows with correct values", () => {+ const { getAllByText, getByText } = render(<LocationTable locations={locations} colors={mockColors} />)++ // formatTime is mocked to return "12:00:00" for all timestamps+ expect(getAllByText("12:00:00").length).toBe(3)++ // Latitude values (5 decimal places)+ expect(getByText("48.10000")).toBeTruthy()+ expect(getByText("48.20000")).toBeTruthy()+ expect(getByText("48.30000")).toBeTruthy()++ // Longitude values (5 decimal places)+ expect(getByText("11.50000")).toBeTruthy()+ expect(getByText("11.60000")).toBeTruthy()+ expect(getByText("11.70000")).toBeTruthy()+ })++ it("shows newest location first (reversed order)", () => {+ const { getAllByText } = render(<LocationTable locations={locations} colors={mockColors} />)++ // The component reverses the array, so the newest timestamp (1060) should be first+ // Verify all three timestamps were rendered+ expect(getAllByText("12:00:00").length).toBe(3)++ // The first row should be the newest (index 2 from original = lat 48.3)+ // and the last row should be the oldest (index 0 = lat 48.1)+ // We can verify this by checking the rendered order of latitude values+ const latTexts = ["48.30000", "48.20000", "48.10000"]+ latTexts.forEach((lat) => {+ expect(getAllByText(lat).length).toBe(1)+ })+ })++ it("computes delta correctly between consecutive timestamps", () => {+ const { getAllByText } = render(<LocationTable locations={locations} colors={mockColors} />)++ // Deltas computed in chronological order:+ // index 0 (ts=1000): delta = null (first item)+ // index 1 (ts=1030): delta = 1030 - 1000 = 30+ // index 2 (ts=1060): delta = 1060 - 1030 = 30+ // After reverse: [index2, index1, index0]+ // Both index2 and index1 have delta = 30, index0 has delta = null+ const deltaElements = getAllByText("+30s")+ expect(deltaElements.length).toBe(2)+ })++ it("first row (newest) has no delta", () => {+ const { queryAllByText } = render(<LocationTable locations={locations} colors={mockColors} />)++ // After reversing: the newest item (originally index 2) has delta=30+ // The second item (originally index 1) has delta=30+ // The oldest item (originally index 0) has delta=null (empty string)+ // So there should be exactly two "+30s" entries+ const deltaElements = queryAllByText("+30s")+ expect(deltaElements.length).toBe(2)++ // The oldest (now last) row has no delta - it renders as empty string ""+ // This means there is no "+0s" or similar text for the first chronological item+ expect(queryAllByText(/^\+\d+s$/).length).toBe(2)+ })++ it("handles null optional fields (altitude, speed, bearing, battery)", () => {+ const { getAllByText } = render(<LocationTable locations={locations} colors={mockColors} />)++ // The third location (index 2, but shown first after reverse) has null altitude,+ // speed, bearing, battery - all rendered as "-"+ // There should be dashes for: altitude, speed, bearing, battery = 4 dashes from+ // the null-field row. Plus the newest row has no delta so its delta cell is empty.+ const dashes = getAllByText("-")+ expect(dashes.length).toBeGreaterThanOrEqual(4)+ })++ it("shows battery status text (Charging, Discharging, etc.)", () => {+ const { getByText } = render(<LocationTable locations={locations} colors={mockColors} />)++ // battery_status 2 = "Charging", battery_status 3 = "Discharging"+ expect(getByText("Charging")).toBeTruthy()+ expect(getByText("Discharging")).toBeTruthy()+ })+})diff --git a/apps/mobile/src/screens/__tests__/AboutScreen.test.tsx b/apps/mobile/src/screens/__tests__/AboutScreen.test.tsxnew file mode 100644index 00000000..dcbd4e59--- /dev/null+++ b/apps/mobile/src/screens/__tests__/AboutScreen.test.tsx@@ -0,0 +1,235 @@+import React from "react"+import { render, fireEvent, waitFor } from "@testing-library/react-native"+import { Linking } from "react-native"++// --- Mocks ---++jest.mock("@react-navigation/native", () => ({+ useFocusEffect: jest.fn()+}))++jest.mock("../../hooks/useTheme", () => ({+ useTheme: () => ({+ colors: {+ primary: "#0d9488",+ text: "#000",+ textSecondary: "#6b7280",+ card: "#fff",+ warning: "#f59e0b",+ border: "#e5e7eb",+ textLight: "#9ca3af",+ success: "#22c55e",+ primaryDark: "#0d9488",+ textOnPrimary: "#fff",+ background: "#fff"+ },+ mode: "light"+ })+}))++jest.mock("../../hooks/useTimeout", () => ({+ useTimeout: () => ({ set: jest.fn(), clear: jest.fn() })+}))++const mockGetBuildConfig = jest.fn().mockReturnValue({+ VERSION_NAME: "1.3.0",+ VERSION_CODE: 10,+ FLAVOR: "foss",+ TARGET_SDK_VERSION: 35,+ MIN_SDK_VERSION: 26,+ COMPILE_SDK_VERSION: 35,+ BUILD_TOOLS_VERSION: "35.0.0",+ KOTLIN_VERSION: "2.0.0",+ NDK_VERSION: "27.0.0"+})+const mockGetSetting = jest.fn().mockResolvedValue("false")+const mockSaveSetting = jest.fn().mockResolvedValue(undefined)+const mockGetDeviceInfo = jest.fn().mockResolvedValue({+ model: "Pixel 8",+ brand: "Google",+ deviceId: "abc123",+ systemVersion: "15",+ apiLevel: 35+})+const mockCopyToClipboard = jest.fn().mockResolvedValue(undefined)+const mockGetNativeLogs = jest.fn().mockResolvedValue([])+const mockWriteFile = jest.fn().mockResolvedValue("/tmp/logs.txt")+const mockShareFile = jest.fn().mockResolvedValue(undefined)++jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getBuildConfig: (...args: any[]) => mockGetBuildConfig(...args),+ getSetting: (...args: any[]) => mockGetSetting(...args),+ saveSetting: (...args: any[]) => mockSaveSetting(...args),+ getDeviceInfo: (...args: any[]) => mockGetDeviceInfo(...args),+ copyToClipboard: (...args: any[]) => mockCopyToClipboard(...args),+ getNativeLogs: (...args: any[]) => mockGetNativeLogs(...args),+ writeFile: (...args: any[]) => mockWriteFile(...args),+ shareFile: (...args: any[]) => mockShareFile(...args)+ }+}))++jest.mock("../../utils/logger", () => ({+ logger: { error: jest.fn() },+ getLogEntries: jest.fn().mockReturnValue([]),+ setLogCollecting: jest.fn()+}))++jest.mock("../../assets/icons/icon.png", () => "mock-icon")++jest.mock("../../components", () => {+ const R = require("react")+ const { View, Text } = require("react-native")+ return {+ Container: ({ children }: any) => R.createElement(View, null, children),+ Card: ({ children }: any) => R.createElement(View, null, children),+ SectionTitle: ({ children }: any) => R.createElement(Text, null, children),+ Footer: () => R.createElement(View, null),+ Divider: () => R.createElement(View, null)+ }+})++jest.mock("lucide-react-native", () => {+ const R = require("react")+ const { Text } = require("react-native")+ const stub = (name: string) => (_props: any) => R.createElement(Text, null, name)+ return {+ ChevronRight: stub("ChevronRight"),+ Bug: stub("Bug"),+ FileText: stub("FileText"),+ Code: stub("Code"),+ ScrollText: stub("ScrollText"),+ MessageCircle: stub("MessageCircle"),+ Copy: stub("Copy"),+ Check: stub("Check")+ }+})++import { AboutScreen } from "../AboutScreen"+import { setLogCollecting } from "../../utils/logger"++describe("AboutScreen", () => {+ beforeEach(() => {+ jest.clearAllMocks()+ mockGetSetting.mockResolvedValue("false")+ jest.spyOn(Linking, "openURL").mockResolvedValue(true as any)+ })++ function renderScreen() {+ return render(<AboutScreen navigation={{} as any} />)+ }++ it("renders app title and version", () => {+ const { getByText } = renderScreen()++ expect(getByText("Colota")).toBeTruthy()+ expect(getByText("Version 1.3.0")).toBeTruthy()+ })++ it("shows tap hint after first taps", () => {+ const { getByText } = renderScreen()++ const versionText = getByText("Version 1.3.0")+ fireEvent.press(versionText)++ expect(getByText("6 more taps to enable debug mode")).toBeTruthy()+ })++ it("enables debug mode after 7 taps", async () => {+ const { getByText } = renderScreen()++ const versionText = getByText("Version 1.3.0")+ for (let i = 0; i < 7; i++) {+ fireEvent.press(versionText)+ }++ await waitFor(() => {+ expect(getByText("Debug Mode (tap to hide)")).toBeTruthy()+ })++ expect(mockSaveSetting).toHaveBeenCalledWith("debug_mode_enabled", "true")+ expect(setLogCollecting).toHaveBeenCalledWith(true)+ })++ it("shows debug badge when debug mode is enabled", async () => {+ const { getByText } = renderScreen()++ const versionText = getByText("Version 1.3.0")+ for (let i = 0; i < 7; i++) {+ fireEvent.press(versionText)+ }++ await waitFor(() => {+ expect(getByText("Debug Mode (tap to hide)")).toBeTruthy()+ })+ })++ it("shows BUILD section with SDK info when debug enabled", async () => {+ const { getByText } = renderScreen()++ const versionText = getByText("Version 1.3.0")+ for (let i = 0; i < 7; i++) {+ fireEvent.press(versionText)+ }++ await waitFor(() => {+ expect(getByText("BUILD")).toBeTruthy()+ })++ expect(getByText("FOSS")).toBeTruthy()+ expect(getByText("35 (Android 15)")).toBeTruthy()+ expect(getByText("26 (Android 8.0)")).toBeTruthy()+ expect(getByText("35.0.0")).toBeTruthy()+ expect(getByText("2.0.0")).toBeTruthy()+ expect(getByText("27.0.0")).toBeTruthy()+ })++ it("disables debug mode when debug badge is tapped", async () => {+ const { getByText, queryByText } = renderScreen()++ const versionText = getByText("Version 1.3.0")+ for (let i = 0; i < 7; i++) {+ fireEvent.press(versionText)+ }++ await waitFor(() => {+ expect(getByText("Debug Mode (tap to hide)")).toBeTruthy()+ })++ mockSaveSetting.mockClear()+ ;(setLogCollecting as jest.Mock).mockClear()++ fireEvent.press(getByText("Debug Mode (tap to hide)"))++ await waitFor(() => {+ expect(queryByText("Debug Mode (tap to hide)")).toBeNull()+ })++ expect(mockSaveSetting).toHaveBeenCalledWith("debug_mode_enabled", "false")+ expect(setLogCollecting).toHaveBeenCalledWith(false)+ })++ it("loads persisted debug mode on mount", async () => {+ mockGetSetting.mockResolvedValue("true")++ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("Debug Mode (tap to hide)")).toBeTruthy()+ })++ expect(mockGetSetting).toHaveBeenCalledWith("debug_mode_enabled", "false")+ expect(setLogCollecting).toHaveBeenCalledWith(true)+ })++ it("opens Privacy Policy URL when link pressed", async () => {+ const { getByText } = renderScreen()++ fireEvent.press(getByText("Privacy Policy"))++ await waitFor(() => {+ expect(Linking.openURL).toHaveBeenCalledWith("https://colota.app/privacy-policy")+ })+ })+})diff --git a/apps/mobile/src/screens/__tests__/DashboardScreen.test.tsx b/apps/mobile/src/screens/__tests__/DashboardScreen.test.tsxnew file mode 100644index 00000000..3b309d33--- /dev/null+++ b/apps/mobile/src/screens/__tests__/DashboardScreen.test.tsx@@ -0,0 +1,154 @@+import React from "react"+import { render } from "@testing-library/react-native"+import { DEFAULT_SETTINGS, Settings } from "../../types/global"++// --- Mocks ---++const mockStartTracking = jest.fn().mockResolvedValue(undefined)+const mockStopTracking = jest.fn().mockResolvedValue(undefined)+const mockSetSettings = jest.fn().mockResolvedValue(undefined)++let mockSettings: Settings = { ...DEFAULT_SETTINGS }+let mockTracking = false+let mockCoords: { latitude: number; longitude: number } | null = null++jest.mock("../../contexts/TrackingProvider", () => ({+ useTracking: () => ({+ settings: mockSettings,+ tracking: mockTracking,+ startTracking: mockStartTracking,+ stopTracking: mockStopTracking,+ setSettings: mockSetSettings,+ activeProfileName: "Default"+ }),+ useCoords: () => mockCoords+}))++jest.mock("../../hooks/useTheme", () => ({+ useTheme: () => ({+ colors: {+ primary: "#0d9488",+ primaryDark: "#115E59",+ border: "#e5e7eb",+ text: "#000",+ textSecondary: "#6b7280",+ textLight: "#9ca3af",+ background: "#fff",+ info: "#3b82f6",+ success: "#22c55e",+ error: "#ef4444",+ card: "#fff",+ backgroundElevated: "#f9fafb",+ placeholder: "#9ca3af",+ textOnPrimary: "#fff"+ }+ })+}))++jest.mock("@react-navigation/native", () => ({+ useFocusEffect: jest.fn()+}))++jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getStats: jest.fn().mockResolvedValue({+ queued: 0,+ sent: 5,+ total: 10,+ today: 3,+ databaseSizeMB: 0.5+ }),+ checkCurrentPauseZone: jest.fn().mockResolvedValue(null)+ }+}))++jest.mock("../../components", () => {+ const R = require("react")+ const { View, Text, Pressable } = require("react-native")+ return {+ DashboardMap: () => R.createElement(View, { testID: "DashboardMap" }),+ CoordinateDisplay: () => R.createElement(View, { testID: "CoordinateDisplay" }),+ DatabaseStatistics: () => R.createElement(View, { testID: "DatabaseStatistics" }),+ ServerConnection: () => R.createElement(View, { testID: "ServerConnection" }),+ QuickAccess: () => R.createElement(View, { testID: "QuickAccess" }),+ WelcomeCard: () => R.createElement(View, { testID: "WelcomeCard" }),+ Container: ({ children }: any) => R.createElement(View, null, children),+ Button: ({ title, onPress }: any) => R.createElement(Pressable, { onPress }, R.createElement(Text, null, title))+ }+})++import { DashboardScreen } from "../DashboardScreen"++const mockNavigation = { navigate: jest.fn() } as any++describe("DashboardScreen", () => {+ beforeEach(() => {+ jest.clearAllMocks()+ mockSettings = { ...DEFAULT_SETTINGS }+ mockTracking = false+ mockCoords = null+ })++ it("shows Start Tracking button when not tracking", () => {+ mockTracking = false++ const { getByText } = render(<DashboardScreen navigation={mockNavigation} />)++ expect(getByText("Start Tracking")).toBeTruthy()+ })++ it("shows Stop Tracking button when tracking", () => {+ mockTracking = true++ const { getByText } = render(<DashboardScreen navigation={mockNavigation} />)++ expect(getByText("Stop Tracking")).toBeTruthy()+ })++ it("shows CoordinateDisplay when tracking with valid coords", () => {+ mockTracking = true+ mockCoords = { latitude: 52.52, longitude: 13.405 }++ const { getByTestId } = render(<DashboardScreen navigation={mockNavigation} />)++ expect(getByTestId("CoordinateDisplay")).toBeTruthy()+ })++ it("hides CoordinateDisplay when not tracking", () => {+ mockTracking = false+ mockCoords = { latitude: 52.52, longitude: 13.405 }++ const { queryByTestId } = render(<DashboardScreen navigation={mockNavigation} />)++ expect(queryByTestId("CoordinateDisplay")).toBeNull()+ })++ it("shows WelcomeCard when hasCompletedSetup is false", () => {+ mockSettings = { ...DEFAULT_SETTINGS, hasCompletedSetup: false }++ const { getByTestId } = render(<DashboardScreen navigation={mockNavigation} />)++ expect(getByTestId("WelcomeCard")).toBeTruthy()+ })++ it("hides WelcomeCard when hasCompletedSetup is true", () => {+ mockSettings = { ...DEFAULT_SETTINGS, hasCompletedSetup: true }++ const { queryByTestId } = render(<DashboardScreen navigation={mockNavigation} />)++ expect(queryByTestId("WelcomeCard")).toBeNull()+ })++ it("renders DatabaseStatistics component", () => {+ const { getByTestId } = render(<DashboardScreen navigation={mockNavigation} />)++ expect(getByTestId("DatabaseStatistics")).toBeTruthy()+ })++ it("renders ServerConnection component", () => {+ const { getByTestId } = render(<DashboardScreen navigation={mockNavigation} />)++ expect(getByTestId("ServerConnection")).toBeTruthy()+ })+})diff --git a/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx b/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsxnew file mode 100644index 00000000..d772f00f--- /dev/null+++ b/apps/mobile/src/screens/__tests__/DataManagementScreen.test.tsx@@ -0,0 +1,282 @@+import React from "react"+import { render, fireEvent, waitFor } from "@testing-library/react-native"++// --- Mocks ---++jest.mock("@react-navigation/native", () => ({+ useFocusEffect: jest.fn((cb) => cb()())+}))++jest.mock("../../hooks/useTheme", () => ({+ useTheme: () => ({+ colors: {+ primary: "#0d9488",+ primaryDark: "#115E59",+ text: "#000",+ textSecondary: "#6b7280",+ textLight: "#9ca3af",+ card: "#fff",+ border: "#e5e7eb",+ background: "#fff",+ backgroundElevated: "#f9fafb",+ success: "#22c55e",+ warning: "#f59e0b",+ info: "#3b82f6",+ error: "#ef4444",+ placeholder: "#9ca3af",+ textOnPrimary: "#fff",+ overlay: "rgba(0,0,0,0.5)"+ }+ })+}))++jest.mock("../../hooks/useTimeout", () => ({+ useTimeout: () => ({ set: jest.fn(), clear: jest.fn() })+}))++const mockGetStats = jest.fn().mockResolvedValue({ queued: 5, sent: 100, total: 105, today: 3, databaseSizeMB: 1.5 })+const mockGetSetting = jest.fn().mockResolvedValue("false")+const mockManualFlush = jest.fn().mockResolvedValue(undefined)+const mockClearSentHistory = jest.fn().mockResolvedValue(undefined)+const mockClearQueue = jest.fn().mockResolvedValue(5)+const mockDeleteOlderThan = jest.fn().mockResolvedValue(10)+const mockVacuumDatabase = jest.fn().mockResolvedValue(undefined)+const mockInsertDummyData = jest.fn().mockResolvedValue(200)++jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getStats: function () {+ return mockGetStats.apply(null, arguments)+ },+ getSetting: function () {+ return mockGetSetting.apply(null, arguments)+ },+ manualFlush: function () {+ return mockManualFlush.apply(null, arguments)+ },+ clearSentHistory: function () {+ return mockClearSentHistory.apply(null, arguments)+ },+ clearQueue: function () {+ return mockClearQueue.apply(null, arguments)+ },+ deleteOlderThan: function () {+ return mockDeleteOlderThan.apply(null, arguments)+ },+ vacuumDatabase: function () {+ return mockVacuumDatabase.apply(null, arguments)+ },+ insertDummyData: function () {+ return mockInsertDummyData.apply(null, arguments)+ }+ }+}))++const mockShowConfirm = jest.fn().mockResolvedValue(true)++jest.mock("../../services/modalService", () => ({+ showConfirm: function () {+ return mockShowConfirm.apply(null, arguments)+ }+}))++jest.mock("../../utils/logger", () => ({+ logger: { error: jest.fn(), warn: jest.fn() }+}))++jest.mock("../../components", () => {+ const R = require("react")+ const RN = require("react-native")+ return {+ Button: function (props) {+ return R.createElement(+ RN.Pressable,+ { onPress: props.onPress, disabled: props.disabled, accessibilityRole: "button" },+ R.createElement(RN.Text, null, props.title)+ )+ },+ SectionTitle: function (props) {+ return R.createElement(RN.Text, null, props.children)+ },+ Card: function (props) {+ return R.createElement(RN.View, null, props.children)+ },+ Container: function (props) {+ return R.createElement(RN.View, null, props.children)+ },+ Divider: function () {+ return R.createElement(RN.View, null)+ },+ FloatingSaveIndicator: function () {+ return null+ }+ }+})++jest.mock("lucide-react-native", () => {+ const R = require("react")+ const RN = require("react-native")+ function stub(name) {+ return function () {+ return R.createElement(RN.Text, null, name)+ }+ }+ return {+ Lightbulb: stub("Lightbulb")+ }+})++// Mock NativeEventEmitter from react-native+const mockAddListener = jest.fn().mockReturnValue({ remove: jest.fn() })+jest.mock("react-native/Libraries/EventEmitter/NativeEventEmitter", () => {+ return {+ __esModule: true,+ default: function () {+ return {+ addListener: function () {+ return mockAddListener.apply(null, arguments)+ }+ }+ }+ }+})++import { DataManagementScreen } from "../DataManagementScreen"++describe("DataManagementScreen", () => {+ beforeEach(() => {+ jest.clearAllMocks()+ mockGetStats.mockResolvedValue({ queued: 5, sent: 100, total: 105, today: 3, databaseSizeMB: 1.5 })+ mockGetSetting.mockResolvedValue("false")+ mockShowConfirm.mockResolvedValue(true)+ })++ function renderScreen() {+ return render(<DataManagementScreen navigation={{} as any} />)+ }++ it("renders Data Management title", async () => {+ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("Data Management")).toBeTruthy()+ })+ })++ it("shows database statistics with correct values", async () => {+ const { getByText, getAllByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("Total Locations")).toBeTruthy()+ expect(getByText("105")).toBeTruthy()+ expect(getByText("Sent")).toBeTruthy()+ // "100" appears as stat value and as badge count for Clear Sent History+ expect(getAllByText("100").length).toBeGreaterThanOrEqual(1)+ expect(getByText("Queued")).toBeTruthy()+ expect(getAllByText("5").length).toBeGreaterThanOrEqual(1)+ expect(getByText("Today")).toBeTruthy()+ expect(getByText("3")).toBeTruthy()+ expect(getByText("Storage")).toBeTruthy()+ expect(getByText("1.50 MB")).toBeTruthy()+ })+ })++ it("shows Sync Now button", async () => {+ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("Sync Now")).toBeTruthy()+ })+ })++ it("disables Sync Now when queue is empty", async () => {+ mockGetStats.mockResolvedValue({ queued: 0, sent: 100, total: 100, today: 3, databaseSizeMB: 1.5 })++ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("Queue is empty")).toBeTruthy()+ })+ })++ it("shows Clear Sent History with badge count", async () => {+ const { getByText, getAllByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("Clear Sent History")).toBeTruthy()+ // "100" appears both as the Sent stat and as the Clear Sent History badge+ expect(getAllByText("100").length).toBeGreaterThanOrEqual(2)+ })+ })++ it("shows Clear Queue action", async () => {+ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("Clear Queue")).toBeTruthy()+ })+ })++ it("shows Delete Old Locations section with days input", async () => {+ const { getByText, getByDisplayValue } = renderScreen()++ await waitFor(() => {+ expect(getByText("Delete Old Locations")).toBeTruthy()+ expect(getByDisplayValue("90")).toBeTruthy()+ expect(getByText("days")).toBeTruthy()+ expect(getByText("Delete")).toBeTruthy()+ })+ })++ it("shows Optimize Database action", async () => {+ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("Optimize Database")).toBeTruthy()+ expect(getByText("Optimize")).toBeTruthy()+ })+ })++ it("shows DEV TOOLS section when debug mode enabled", async () => {+ mockGetSetting.mockResolvedValue("true")++ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("DEV TOOLS")).toBeTruthy()+ expect(getByText("Insert Dummy Data")).toBeTruthy()+ })+ })++ it("hides DEV TOOLS section when debug mode disabled", async () => {+ mockGetSetting.mockResolvedValue("false")++ const { queryByText } = renderScreen()++ await waitFor(() => {+ expect(queryByText("DEV TOOLS")).toBeNull()+ expect(queryByText("Insert Dummy Data")).toBeNull()+ })+ })++ it("Clear Sent History shows confirmation dialog", async () => {+ const { getByText, getAllByText } = renderScreen()++ // Wait for stats to load so the ActionRow is enabled (stats.sent > 0)+ await waitFor(() => {+ expect(getAllByText("100").length).toBeGreaterThanOrEqual(1)+ })++ fireEvent.press(getByText("Clear Sent History"))++ await waitFor(() => {+ expect(mockShowConfirm).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Clear Sent History",+ destructive: true+ })+ )+ })+ })+})diff --git a/apps/mobile/src/screens/__tests__/ExportDataScreen.test.tsx b/apps/mobile/src/screens/__tests__/ExportDataScreen.test.tsxnew file mode 100644index 00000000..c320134a--- /dev/null+++ b/apps/mobile/src/screens/__tests__/ExportDataScreen.test.tsx@@ -0,0 +1,301 @@+import React from "react"+import { render, fireEvent, waitFor } from "@testing-library/react-native"++// --- Mocks ---++jest.mock("../../hooks/useTheme", () => ({+ useTheme: () => ({+ colors: {+ primary: "#0d9488",+ primaryDark: "#115E59",+ text: "#000",+ textSecondary: "#6b7280",+ textLight: "#9ca3af",+ card: "#fff",+ border: "#e5e7eb",+ background: "#fff",+ backgroundElevated: "#f9fafb",+ success: "#22c55e",+ warning: "#f59e0b",+ info: "#3b82f6",+ error: "#ef4444",+ placeholder: "#9ca3af",+ textOnPrimary: "#fff",+ overlay: "rgba(0,0,0,0.5)"+ }+ })+}))++const mockGetStats = jest.fn().mockResolvedValue({ total: 100 })+const mockGetExportData = jest.fn().mockResolvedValue([+ { latitude: 52.52, longitude: 13.405, accuracy: 10, altitude: 34, speed: 1.2, battery: 85, timestamp: 1700000000 },+ { latitude: 48.8566, longitude: 2.3522, accuracy: 15, altitude: 40, speed: 0.5, battery: 72, timestamp: 1700003600 }+])+const mockWriteFile = jest.fn().mockResolvedValue("/path/file.csv")+const mockShareFile = jest.fn().mockResolvedValue(undefined)++jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getStats: function () {+ return mockGetStats.apply(null, arguments)+ },+ getExportData: function () {+ return mockGetExportData.apply(null, arguments)+ },+ writeFile: function () {+ return mockWriteFile.apply(null, arguments)+ },+ shareFile: function () {+ return mockShareFile.apply(null, arguments)+ }+ }+}))++const mockShowAlert = jest.fn()+const mockShowConfirm = jest.fn().mockResolvedValue(true)++jest.mock("../../services/modalService", () => ({+ showAlert: function () {+ return mockShowAlert.apply(null, arguments)+ },+ showConfirm: function () {+ return mockShowConfirm.apply(null, arguments)+ }+}))++jest.mock("../../utils/exportConverters", () => ({+ LARGE_FILE_THRESHOLD: 10 * 1024 * 1024,+ formatBytes: function (bytes) {+ if (bytes < 1024) return bytes + " B"+ if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB"+ return (bytes / (1024 * 1024)).toFixed(1) + " MB"+ },+ getByteSize: function (content) {+ return content.length+ },+ EXPORT_FORMATS: {+ csv: {+ label: "CSV",+ subtitle: "Spreadsheet Format",+ description: "Excel, Google Sheets, data analysis",+ icon: function () {+ return null+ },+ extension: ".csv",+ mimeType: "text/csv",+ convert: function () {+ return "id,lat,lon\n1,52.52,13.405"+ }+ },+ geojson: {+ label: "GeoJSON",+ subtitle: "Geographic Data",+ description: "Mapbox, Leaflet, QGIS, ArcGIS",+ icon: function () {+ return null+ },+ extension: ".geojson",+ mimeType: "application/json",+ convert: function () {+ return '{"type":"FeatureCollection","features":[]}'+ }+ },+ gpx: {+ label: "GPX",+ subtitle: "GPS Exchange",+ description: "Garmin, Strava, Google Earth",+ icon: function () {+ return null+ },+ extension: ".gpx",+ mimeType: "application/gpx+xml",+ convert: function () {+ return "<gpx></gpx>"+ }+ },+ kml: {+ label: "KML",+ subtitle: "Keyhole Markup Language",+ description: "Google Earth, Google Maps, ArcGIS",+ icon: function () {+ return null+ },+ extension: ".kml",+ mimeType: "application/vnd.google-earth.kml+xml",+ convert: function () {+ return "<kml></kml>"+ }+ }+ }+}))++jest.mock("../../utils/logger", () => ({+ logger: { error: jest.fn(), warn: jest.fn() }+}))++jest.mock("../../components", () => {+ const R = require("react")+ const RN = require("react-native")+ return {+ Container: function (props) {+ return R.createElement(RN.View, null, props.children)+ },+ Card: function (props) {+ return R.createElement(RN.View, null, props.children)+ },+ SectionTitle: function (props) {+ return R.createElement(RN.Text, null, props.children)+ },+ Divider: function () {+ return R.createElement(RN.View, null)+ },+ Button: function (props) {+ return R.createElement(+ RN.Pressable,+ { onPress: props.onPress, disabled: props.disabled, accessibilityRole: "button" },+ R.createElement(RN.Text, null, props.title)+ )+ }+ }+})++jest.mock("lucide-react-native", () => {+ const R = require("react")+ const RN = require("react-native")+ function stub(name) {+ return function () {+ return R.createElement(RN.Text, null, name)+ }+ }+ return {+ Download: stub("Download"),+ MapPinOff: stub("MapPinOff"),+ Table2: stub("Table2"),+ Globe: stub("Globe"),+ MapPin: stub("MapPin"),+ Earth: stub("Earth")+ }+})++import { ExportDataScreen } from "../ExportDataScreen"++describe("ExportDataScreen", () => {+ beforeEach(() => {+ jest.clearAllMocks()+ mockGetStats.mockResolvedValue({ total: 100 })+ mockGetExportData.mockResolvedValue([+ {+ latitude: 52.52,+ longitude: 13.405,+ accuracy: 10,+ altitude: 34,+ speed: 1.2,+ battery: 85,+ timestamp: 1700000000+ },+ {+ latitude: 48.8566,+ longitude: 2.3522,+ accuracy: 15,+ altitude: 40,+ speed: 0.5,+ battery: 72,+ timestamp: 1700003600+ }+ ])+ })++ function renderScreen() {+ return render(<ExportDataScreen />)+ }++ it("shows Export Data title", async () => {+ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("Export Data")).toBeTruthy()+ })+ })++ it("shows empty state when no locations", async () => {+ mockGetStats.mockResolvedValue({ total: 0 })++ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("No Locations")).toBeTruthy()+ expect(getByText("Start tracking to record locations that can be exported.")).toBeTruthy()+ })+ })++ it("shows total location count", async () => {+ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("Total")).toBeTruthy()+ expect(getByText("100")).toBeTruthy()+ })+ })++ it("renders all format options", async () => {+ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("CSV")).toBeTruthy()+ expect(getByText("GeoJSON")).toBeTruthy()+ expect(getByText("GPX")).toBeTruthy()+ expect(getByText("KML")).toBeTruthy()+ })+ })++ it("selecting a format shows the export button", async () => {+ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("CSV")).toBeTruthy()+ })++ fireEvent.press(getByText("CSV"))++ await waitFor(() => {+ expect(getByText("Export CSV")).toBeTruthy()+ })+ })++ it("shows loading overlay during export", async () => {+ // Make writeFile hang so we can observe the loading state+ mockWriteFile.mockImplementation(() => new Promise(() => {}))++ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("CSV")).toBeTruthy()+ })++ fireEvent.press(getByText("CSV"))++ await waitFor(() => {+ expect(getByText("Export CSV")).toBeTruthy()+ })++ fireEvent.press(getByText("Export CSV"))++ await waitFor(() => {+ expect(getByText("Exporting Data")).toBeTruthy()+ })+ })++ it("shows alert when exporting with no data", async () => {+ mockGetStats.mockResolvedValue({ total: 0 })++ const { getByText, queryByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("No Locations")).toBeTruthy()+ })++ // totalLocations is 0 so the format cards are not rendered and no export button exists+ expect(queryByText("CSV")).toBeNull()+ })+})diff --git a/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx b/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsxnew file mode 100644index 00000000..01d6c13a--- /dev/null+++ b/apps/mobile/src/screens/__tests__/GeofenceScreen.test.tsx@@ -0,0 +1,323 @@+import React from "react"+import { render, fireEvent, waitFor } from "@testing-library/react-native"+import { Geofence } from "../../types/global"++// --- Mocks ---++jest.mock("@maplibre/maplibre-react-native", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ __esModule: true,+ default: { setAccessToken: jest.fn() },+ MapView: (props: any) => R.createElement(View, { testID: "mapview", ...props }),+ Camera: () => null,+ ShapeSource: ({ children }: any) => children,+ FillLayer: () => null,+ LineLayer: () => null,+ SymbolLayer: () => null,+ CircleLayer: () => null,+ MarkerView: ({ children }: any) => children+ }+})++jest.mock("@react-navigation/native", () => ({+ useFocusEffect: jest.fn()+}))++jest.mock("../../hooks/useTheme", () => ({+ useTheme: () => ({+ colors: {+ primary: "#0d9488",+ text: "#000",+ textSecondary: "#6b7280",+ textDisabled: "#d1d5db",+ card: "#fff",+ warning: "#f59e0b",+ info: "#3b82f6",+ background: "#fff",+ border: "#e5e7eb",+ borderRadius: 12,+ success: "#22c55e",+ error: "#ef4444",+ link: "#0d9488",+ textLight: "#9ca3af",+ textOnPrimary: "#fff",+ placeholder: "#d1d5db",+ primaryDark: "#0d9488",+ backgroundElevated: "#f9fafb",+ surface: "#fff",+ overlay: "rgba(0,0,0,0.5)"+ },+ mode: "light"+ })+}))++jest.mock("../../contexts/TrackingProvider", () => ({+ useTracking: () => ({ tracking: true }),+ useCoords: () => ({ latitude: 48.1, longitude: 11.5, accuracy: 10 })+}))++const mockGetGeofences = jest.fn().mockResolvedValue([])+const mockCreateGeofence = jest.fn().mockResolvedValue(undefined)+const mockUpdateGeofence = jest.fn().mockResolvedValue(undefined)+const mockDeleteGeofence = jest.fn().mockResolvedValue(undefined)+const mockCheckCurrentPauseZone = jest.fn().mockResolvedValue(null)+const mockIsNetworkAvailable = jest.fn().mockResolvedValue(true)+const mockRecheckZoneSettings = jest.fn().mockResolvedValue(undefined)+const mockGetMostRecentLocation = jest.fn().mockResolvedValue(null)++jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getGeofences: (...args: any[]) => mockGetGeofences(...args),+ createGeofence: (...args: any[]) => mockCreateGeofence(...args),+ updateGeofence: (...args: any[]) => mockUpdateGeofence(...args),+ deleteGeofence: (...args: any[]) => mockDeleteGeofence(...args),+ checkCurrentPauseZone: (...args: any[]) => mockCheckCurrentPauseZone(...args),+ isNetworkAvailable: (...args: any[]) => mockIsNetworkAvailable(...args),+ recheckZoneSettings: (...args: any[]) => mockRecheckZoneSettings(...args),+ getMostRecentLocation: (...args: any[]) => mockGetMostRecentLocation(...args)+ }+}))++const mockShowAlert = jest.fn()+const mockShowConfirm = jest.fn().mockResolvedValue(true)++jest.mock("../../services/modalService", () => ({+ showAlert: (...args: any[]) => mockShowAlert(...args),+ showConfirm: (...args: any[]) => mockShowConfirm(...args)+}))++jest.mock("../../components/features/map/ColotaMapView", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ ColotaMapView: R.forwardRef(({ children }: any, _ref: any) =>+ R.createElement(View, { testID: "colota-map" }, children)+ )+ }+})++jest.mock("../../components/features/map/GeofenceLayers", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ GeofenceLayers: () => R.createElement(View, { testID: "geofence-layers" })+ }+})++jest.mock("../../components/features/map/UserLocationOverlay", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ UserLocationOverlay: () => R.createElement(View, { testID: "user-location-overlay" })+ }+})++jest.mock("../../components/features/map/MapCenterButton", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ MapCenterButton: () => R.createElement(View, { testID: "center-button" })+ }+})++jest.mock("../../components/features/map/mapUtils", () => ({+ buildGeofencesGeoJSON: jest.fn().mockReturnValue({ fills: null, labels: null })+}))++jest.mock("../../components", () => {+ const R = require("react")+ const { View, Text } = require("react-native")+ return {+ Container: ({ children }: any) => R.createElement(View, null, children),+ SectionTitle: ({ children }: any) => R.createElement(Text, null, children),+ Card: ({ children, style }: any) => R.createElement(View, { style }, children)+ }+})++jest.mock("../../assets/icons/icon.png", () => "mock-icon")++jest.mock("lucide-react-native", () => {+ const R = require("react")+ const { Text } = require("react-native")+ return {+ X: (props: any) => R.createElement(Text, props, "X"),+ WifiOff: (props: any) => R.createElement(Text, props, "WifiOff")+ }+})++jest.mock("../../utils/logger", () => ({+ logger: { debug: jest.fn(), error: jest.fn(), warn: jest.fn(), info: jest.fn() }+}))++import { GeofenceScreen } from "../GeofenceScreen"++// --- Test data ---++const mockGeofences: Geofence[] = [+ {+ id: 1,+ name: "Home",+ lat: 48.1,+ lon: 11.5,+ radius: 100,+ enabled: true,+ pauseTracking: true+ },+ {+ id: 2,+ name: "Office",+ lat: 48.2,+ lon: 11.6,+ radius: 200,+ enabled: true,+ pauseTracking: false+ }+]++// --- Tests ---++describe("GeofenceScreen", () => {+ beforeEach(() => {+ jest.clearAllMocks()+ mockGetGeofences.mockResolvedValue([])+ mockShowConfirm.mockResolvedValue(true)+ })++ function renderScreen() {+ return render(<GeofenceScreen navigation={{} as any} />)+ }++ it("shows empty state when no geofences exist", async () => {+ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("No geofences yet")).toBeTruthy()+ })+ })++ it("renders geofence list with name and radius", async () => {+ mockGetGeofences.mockResolvedValue(mockGeofences)++ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("Home")).toBeTruthy()+ expect(getByText("100m radius")).toBeTruthy()+ expect(getByText("Office")).toBeTruthy()+ expect(getByText("200m radius")).toBeTruthy()+ })+ })++ it("shows validation alert when name is empty", async () => {+ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("Place Geofence")).toBeTruthy()+ })++ fireEvent.press(getByText("Place Geofence"))++ expect(mockShowAlert).toHaveBeenCalledWith("Missing Name", "Please enter a name.", "warning")+ })++ it("shows validation alert when radius is invalid (0 or negative)", async () => {+ const { getByText, getByPlaceholderText, getByDisplayValue } = renderScreen()++ await waitFor(() => {+ expect(getByText("Place Geofence")).toBeTruthy()+ })++ fireEvent.changeText(getByPlaceholderText("Home, Office..."), "Test Zone")+ fireEvent.changeText(getByDisplayValue("50"), "0")+ fireEvent.press(getByText("Place Geofence"))++ expect(mockShowAlert).toHaveBeenCalledWith("Invalid Radius", "Please enter a valid radius.", "warning")+ })++ it("enters placing mode on valid name and radius", async () => {+ const { getByText, getByPlaceholderText, getByDisplayValue } = renderScreen()++ await waitFor(() => {+ expect(getByText("Place Geofence")).toBeTruthy()+ })++ fireEvent.changeText(getByPlaceholderText("Home, Office..."), "Test Zone")+ fireEvent.changeText(getByDisplayValue("50"), "100")+ fireEvent.press(getByText("Place Geofence"))++ expect(mockShowAlert).not.toHaveBeenCalled()+ expect(getByText("Tap Map to Place...")).toBeTruthy()+ })++ it("toggles pause tracking on a geofence", async () => {+ mockGetGeofences.mockResolvedValue(mockGeofences)++ const { getAllByRole } = renderScreen()++ await waitFor(() => {+ expect(getAllByRole("switch").length).toBeGreaterThanOrEqual(2)+ })++ const switches = getAllByRole("switch")+ // The second geofence (Office) has pauseTracking: false, toggle it on+ fireEvent(switches[1], "onValueChange", true)++ await waitFor(() => {+ expect(mockUpdateGeofence).toHaveBeenCalledWith({ id: 2, pauseTracking: true })+ })++ await waitFor(() => {+ expect(mockRecheckZoneSettings).toHaveBeenCalled()+ })+ })++ it("shows delete confirmation dialog", async () => {+ mockGetGeofences.mockResolvedValue(mockGeofences)+ mockShowConfirm.mockResolvedValue(false)++ const { getAllByText } = renderScreen()++ await waitFor(() => {+ expect(getAllByText("X").length).toBeGreaterThanOrEqual(1)+ })++ // Press the first delete button (X icon)+ fireEvent.press(getAllByText("X")[0])++ await waitFor(() => {+ expect(mockShowConfirm).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Delete Geofence",+ message: 'Delete "Home"?',+ confirmText: "Delete",+ destructive: true+ })+ )+ })+ })++ it("deletes geofence after confirmation", async () => {+ mockGetGeofences.mockResolvedValue(mockGeofences)+ mockShowConfirm.mockResolvedValue(true)++ const { getAllByText } = renderScreen()++ await waitFor(() => {+ expect(getAllByText("X").length).toBeGreaterThanOrEqual(1)+ })++ // Press the first delete button (X icon)+ fireEvent.press(getAllByText("X")[0])++ await waitFor(() => {+ expect(mockShowConfirm).toHaveBeenCalled()+ })++ await waitFor(() => {+ expect(mockDeleteGeofence).toHaveBeenCalledWith(1)+ })+ })+})diff --git a/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx b/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsxnew file mode 100644index 00000000..a48a3e24--- /dev/null+++ b/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx@@ -0,0 +1,198 @@+import React from "react"+import { render, fireEvent } from "@testing-library/react-native"++// --- Mocks ---++jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getDaysWithData: jest.fn().mockResolvedValue([]),+ getLocationsByDateRange: jest.fn().mockResolvedValue([]),+ writeFile: jest.fn(),+ shareFile: jest.fn()+ }+}))++jest.mock("../../utils/trips", () => ({+ segmentTrips: jest.fn().mockReturnValue([])+}))++jest.mock("../../utils/geo", () => ({+ formatDistance: jest.fn().mockReturnValue("0 km")+}))++jest.mock("../../utils/exportConverters", () => ({+ TRIP_CONVERTERS: {},+ EXPORT_FORMATS: {}+}))++jest.mock("../../services/modalService", () => ({+ showAlert: jest.fn()+}))++jest.mock("../../hooks/useTheme", () => ({+ useTheme: () => ({+ colors: {+ primary: "#0d9488",+ primaryDark: "#115E59",+ border: "#e5e7eb",+ text: "#000",+ textSecondary: "#6b7280",+ textLight: "#9ca3af",+ background: "#fff",+ success: "#22c55e",+ error: "#ef4444",+ card: "#fff",+ surface: "#fff",+ backgroundElevated: "#f9fafb",+ textOnPrimary: "#fff",+ borderRadius: 8+ }+ })+}))++jest.mock("lucide-react-native", () => {+ const R = require("react")+ const { Text } = require("react-native")+ const stub = (name: string) => (_props: any) => R.createElement(Text, null, name)+ return {+ BarChart2: stub("BarChart2")+ }+})++jest.mock("../../components", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ Container: ({ children }: any) => R.createElement(View, null, children)+ }+})++jest.mock("../../components/features/inspector/CalendarPicker", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ CalendarPicker: (_props: any) => R.createElement(View, { testID: "CalendarPicker" })+ }+})++jest.mock("../../components/features/inspector/TrackMap", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ TrackMap: (_props: any) => R.createElement(View, { testID: "TrackMap" })+ }+})++jest.mock("../../components/features/inspector/TripList", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ TripList: (_props: any) => R.createElement(View, { testID: "TripList" })+ }+})++jest.mock("../../components/features/inspector/LocationTable", () => {+ const R = require("react")+ const { View } = require("react-native")+ return {+ LocationTable: (_props: any) => R.createElement(View, { testID: "LocationTable" })+ }+})++jest.mock("../../styles/typography", () => ({+ fonts: { regular: {}, bold: {}, semiBold: {} }+}))++jest.mock("../../utils/logger", () => ({+ logger: { error: jest.fn(), info: jest.fn(), debug: jest.fn() }+}))++import { LocationHistoryScreen } from "../LocationInspectorScreen"++const createProps = () => ({+ navigation: {+ navigate: jest.fn(),+ setOptions: jest.fn()+ },+ route: {+ params: {}+ }+})++describe("LocationHistoryScreen", () => {+ beforeEach(() => {+ jest.clearAllMocks()+ })++ it("renders all three tabs (Map, Trips, Data)", () => {+ const props = createProps()+ const { getByText } = render(<LocationHistoryScreen {...props} />)++ expect(getByText("Map")).toBeTruthy()+ expect(getByText("Trips")).toBeTruthy()+ expect(getByText("Data")).toBeTruthy()+ })++ it("Map tab is active by default", () => {+ const props = createProps()+ const { getByTestId, queryByTestId } = render(<LocationHistoryScreen {...props} />)++ // Map tab shows TrackMap+ expect(getByTestId("TrackMap")).toBeTruthy()+ // Trips and Data content should not be visible+ expect(queryByTestId("TripList")).toBeNull()+ expect(queryByTestId("LocationTable")).toBeNull()+ })++ it("switches to Trips tab on press", () => {+ const props = createProps()+ const { getByText, getByTestId, queryByTestId } = render(<LocationHistoryScreen {...props} />)++ fireEvent.press(getByText("Trips"))++ expect(getByTestId("TripList")).toBeTruthy()+ expect(queryByTestId("TrackMap")).toBeNull()+ expect(queryByTestId("LocationTable")).toBeNull()+ })++ it("switches to Data tab on press", () => {+ const props = createProps()+ const { getByText, getByTestId, queryByTestId } = render(<LocationHistoryScreen {...props} />)++ fireEvent.press(getByText("Data"))++ expect(getByTestId("LocationTable")).toBeTruthy()+ expect(queryByTestId("TrackMap")).toBeNull()+ expect(queryByTestId("TripList")).toBeNull()+ })++ it("renders CalendarPicker in each tab", () => {+ const props = createProps()+ const { getByText, getByTestId } = render(<LocationHistoryScreen {...props} />)++ // Map tab (default) - should have CalendarPicker+ expect(getByTestId("CalendarPicker")).toBeTruthy()++ // Switch to Trips tab+ fireEvent.press(getByText("Trips"))+ expect(getByTestId("CalendarPicker")).toBeTruthy()++ // Switch to Data tab+ fireEvent.press(getByText("Data"))+ expect(getByTestId("CalendarPicker")).toBeTruthy()+ })++ it("shows LocationTable in Data tab", () => {+ const props = createProps()+ const { getByText, getByTestId } = render(<LocationHistoryScreen {...props} />)++ // Initially not visible+ expect(() => getByTestId("LocationTable")).toThrow()++ // Switch to Data tab+ fireEvent.press(getByText("Data"))++ expect(getByTestId("LocationTable")).toBeTruthy()+ })+})