Colota - Android GPS Location tracker
test: wait for async reads inside act so jest prints no act() warnings (#1010)
Max Dietrich79a3d4859c2f
diff --git a/apps/mobile/src/components/features/map/__tests__/ColotaMapView.test.tsx b/apps/mobile/src/components/features/map/__tests__/ColotaMapView.test.tsxindex 01536045..451b087a 100644--- a/apps/mobile/src/components/features/map/__tests__/ColotaMapView.test.tsx+++ b/apps/mobile/src/components/features/map/__tests__/ColotaMapView.test.tsx@@ -65,6 +65,13 @@ function rightOf(node: any): number | undefined {return positionOf(node, "right")}+/** Renders and lets the style URL read land, so no state update arrives after the test ends. */+async function renderLoaded(ui: React.ReactElement) {+ const view = render(ui)+ await act(async () => {})+ return view+}+describe("ColotaMapView camera padding", () => {beforeEach(() => {mockSetStop.mockClear()@@ -119,8 +126,10 @@ describe("ColotaMapView camera padding", () => {describe("ColotaMapView control slots", () => {const controlsBottom = 250- it("puts the attribution disc on the base line and the compass two slots above it", () => {- const { getByRole, getByTestId } = render(<ColotaMapView initialCenter={center} controlsBottom={controlsBottom} />)+ it("puts the attribution disc on the base line and the compass two slots above it", async () => {+ const { getByRole, getByTestId } = await renderLoaded(+ <ColotaMapView initialCenter={center} controlsBottom={controlsBottom} />+ )rotateMap(getByTestId)expect(bottomOf(getByRole("button", { name: "Show map attribution" }))).toBe(controlsBottom)@@ -129,8 +138,8 @@ describe("ColotaMapView control slots", () => {)})- it("moves both discs in from the right edge by the column end a screen gives, clear of a side navigation bar", () => {- const { getByRole, getByTestId } = render(+ it("moves both discs in from the right edge by the column end a screen gives, clear of a side navigation bar", async () => {+ const { getByRole, getByTestId } = await renderLoaded(<ColotaMapView initialCenter={center} controlsBottom={controlsBottom} controlsEnd={64} />)rotateMap(getByTestId)@@ -139,13 +148,13 @@ describe("ColotaMapView control slots", () => {expect(rightOf(getByRole("button", { name: "Reset map to north" }))).toBe(64)})- it("gives the attribution disc the same touch slop as every other disc in the column", () => {- const { getByRole } = render(<ColotaMapView initialCenter={center} controlsBottom={controlsBottom} />)+ it("gives the attribution disc the same touch slop as every other disc in the column", async () => {+ const { getByRole } = await renderLoaded(<ColotaMapView initialCenter={center} controlsBottom={controlsBottom} />)expect(getByRole("button", { name: "Show map attribution" }).props.hitSlop).toEqual(HIT_SLOP_SM)})- it("keeps the fixed disc positions when no base line is given", () => {+ it("keeps the fixed disc positions when no base line is given", async () => {const bare = render(<MapActionButtononPress={() => {}}@@ -159,7 +168,7 @@ describe("ColotaMapView control slots", () => {const defaultBottom = bottomOf(bare.getByRole("button", { name: "bare" }))bare.unmount()- const { getByRole, getByTestId } = render(<ColotaMapView initialCenter={center} />)+ const { getByRole, getByTestId } = await renderLoaded(<ColotaMapView initialCenter={center} />)rotateMap(getByTestId)expect(bottomOf(getByRole("button", { name: "Show map attribution" }))).toBe(defaultBottom)@@ -169,8 +178,8 @@ describe("ColotaMapView control slots", () => {)})- it("names the compass for a screen reader and hides it while the map points north", () => {- const { queryByRole, getByRole, getByTestId } = render(<ColotaMapView initialCenter={center} />)+ it("names the compass for a screen reader and hides it while the map points north", async () => {+ const { queryByRole, getByRole, getByTestId } = await renderLoaded(<ColotaMapView initialCenter={center} />)expect(queryByRole("button", { name: "Reset map to north" })).toBeNull()rotateMap(getByTestId)@@ -181,14 +190,14 @@ describe("ColotaMapView control slots", () => {})describe("ColotaMapView attribution popup", () => {- function openPopup() {- const utils = render(<ColotaMapView initialCenter={center} />)+ async function openPopup() {+ const utils = await renderLoaded(<ColotaMapView initialCenter={center} />)fireEvent.press(utils.getByRole("button", { name: "Show map attribution" }))return utils}- it("names the map data, lists every source as a link and ends with a Close button like the app's dialogs", () => {- const { getByText, getAllByRole, getByRole, queryByLabelText } = openPopup()+ it("names the map data, lists every source as a link and ends with a Close button like the app's dialogs", async () => {+ const { getByText, getAllByRole, getByRole, queryByLabelText } = await openPopup()expect(getByText("Map credits")).toBeTruthy()expect(getAllByRole("link")).toHaveLength(4)@@ -201,16 +210,16 @@ describe("ColotaMapView attribution popup", () => {expect(queryByLabelText("Close")).toBeNull()})- it("holds the Close button 24 under the links like AppModal's button row, counting the 8 Button bakes in", () => {- const { getByRole } = openPopup()+ it("holds the Close button 24 under the links like AppModal's button row, counting the 8 Button bakes in", async () => {+ const { getByRole } = await openPopup()let node: any = getByRole("button", { name: "Close" }).parentwhile (node && StyleSheet.flatten(node.props.style)?.marginTop === undefined) node = node.parentexpect(StyleSheet.flatten(node.props.style).marginTop + space.sm).toBe(space.xl)})- it("closes on the Close button so a reader is not left hunting for a corner glyph", () => {- const { getByRole, queryByText } = openPopup()+ it("closes on the Close button so a reader is not left hunting for a corner glyph", async () => {+ const { getByRole, queryByText } = await openPopup()fireEvent.press(getByRole("button", { name: "Close" }))diff --git a/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx b/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsxindex 7145a778..6359c17a 100644--- a/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx+++ b/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx@@ -86,11 +86,12 @@ const settleHydration = async () => {const wrapper = ({ children }: { children: React.ReactNode }) => <TrackingProvider>{children}</TrackingProvider>// Nothing else shows a disclosure: without these mounts no permission is ever requested on a fresh install.-it("mounts both permission disclosures", () => {+it("mounts both permission disclosures", async () => {mockMountedDisclosures.length = 0renderHook(() => useTracking(), { wrapper })expect(mockMountedDisclosures).toEqual(expect.arrayContaining(["location", "localNetwork"]))+ await settleHydration()})describe("useTracking", () => {@@ -111,6 +112,7 @@ describe("useTracking", () => {expect(result.current.settings.interval).toBe(DEFAULT_SETTINGS.interval)expect(result.current.settings.endpoint).toBe(DEFAULT_SETTINGS.endpoint)+ await settleHydration()})it("hydrates settings from native storage", async () => {diff --git a/apps/mobile/src/screens/__tests__/AppearanceScreen.test.tsx b/apps/mobile/src/screens/__tests__/AppearanceScreen.test.tsxindex a76776a8..33d60184 100644--- a/apps/mobile/src/screens/__tests__/AppearanceScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/AppearanceScreen.test.tsx@@ -107,6 +107,13 @@ import { AppearanceScreen } from "../AppearanceScreen"const mockNavigation = { navigate: jest.fn() } as any+/** Renders and lets the mount reads land, so no state update arrives after the test ends. */+const renderLoaded = async () => {+ const view = render(<AppearanceScreen navigation={mockNavigation} />)+ await act(async () => {})+ return view+}+describe("AppearanceScreen", () => {beforeEach(() => {jest.clearAllMocks()@@ -116,8 +123,8 @@ describe("AppearanceScreen", () => {mockGetSetting.mockResolvedValue(null)})- it("renders theme, units and time format rows", () => {- const { getByText, getByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)+ it("renders theme, units and time format rows", async () => {+ const { getByText, getByTestId } = await renderLoaded()expect(getByText("Theme")).toBeTruthy()expect(getByText("Units")).toBeTruthy()@@ -125,22 +132,22 @@ describe("AppearanceScreen", () => {expect(getByTestId("theme-system")).toBeTruthy()})- it("shows unit system chips with Metric and Imperial", () => {- const { getByText } = render(<AppearanceScreen navigation={mockNavigation} />)+ it("shows unit system chips with Metric and Imperial", async () => {+ const { getByText } = await renderLoaded()expect(getByText("Metric")).toBeTruthy()expect(getByText("Imperial")).toBeTruthy()})- it("shows time format chips with 24h and 12h", () => {- const { getByText } = render(<AppearanceScreen navigation={mockNavigation} />)+ it("shows time format chips with 24h and 12h", async () => {+ const { getByText } = await renderLoaded()expect(getByText("24h")).toBeTruthy()expect(getByText("12h")).toBeTruthy()})it("saves unit system when chip is pressed", async () => {- const { getByText } = render(<AppearanceScreen navigation={mockNavigation} />)+ const { getByText } = await renderLoaded()fireEvent.press(getByText("Imperial"))@@ -150,7 +157,7 @@ describe("AppearanceScreen", () => {})it("saves time format when chip is pressed", async () => {- const { getByText } = render(<AppearanceScreen navigation={mockNavigation} />)+ const { getByText } = await renderLoaded()fireEvent.press(getByText("12h"))@@ -159,48 +166,48 @@ describe("AppearanceScreen", () => {})})- it("offers system alongside light and dark, which a toggle could not", () => {- const { getByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)+ it("offers system alongside light and dark, which a toggle could not", async () => {+ const { getByTestId } = await renderLoaded()expect(getByTestId("theme-system")).toBeTruthy()expect(getByTestId("theme-light")).toBeTruthy()expect(getByTestId("theme-dark")).toBeTruthy()})- it("records the picked mode rather than flipping the current one", () => {- const { getByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)+ it("records the picked mode rather than flipping the current one", async () => {+ const { getByTestId } = await renderLoaded()fireEvent.press(getByTestId("theme-dark"))expect(mockSetPreference).toHaveBeenCalledWith("dark")})- it("keeps the wallpaper palette out of the mode chips, which answer a different question", () => {- const { getByTestId, queryByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)+ it("keeps the wallpaper palette out of the mode chips, which answer a different question", async () => {+ const { getByTestId, queryByTestId } = await renderLoaded()expect(getByTestId("wallpaper-colors-toggle")).toBeTruthy()expect(queryByTestId("theme-wallpaper")).toBeNull()})- it("hides the wallpaper row where the platform has no palette, rather than disabling it", () => {+ it("hides the wallpaper row where the platform has no palette, rather than disabling it", async () => {theme.wallpaperColorsAvailable = false- const { queryByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)+ const { queryByTestId } = await renderLoaded()expect(queryByTestId("wallpaper-colors-toggle")).toBeNull()})// A failed read must not hide the only control that turns the setting off.- it("keeps the wallpaper row when the palette read has not landed, and disables it", () => {+ it("keeps the wallpaper row when the palette read has not landed, and disables it", async () => {theme.wallpaperPaletteReady = false- const { getByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)+ const { getByTestId } = await renderLoaded()expect(getByTestId("wallpaper-colors-toggle").props.accessibilityState.disabled).toBe(true)})- it("hands the wallpaper choice to the theme, which owns the palette", () => {- const { getByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)+ it("hands the wallpaper choice to the theme, which owns the palette", async () => {+ const { getByTestId } = await renderLoaded()fireEvent.press(getByTestId("wallpaper-colors-toggle"))@@ -208,7 +215,7 @@ describe("AppearanceScreen", () => {})it("puts the units the choice produces under the label", async () => {- const { getByText, queryByText } = render(<AppearanceScreen navigation={mockNavigation} />)+ const { getByText, queryByText } = await renderLoaded()expect(getByText("km · km/h · m")).toBeTruthy()@@ -219,7 +226,7 @@ describe("AppearanceScreen", () => {})it("puts a clock in the chosen format under the time format label", async () => {- const { getByText } = render(<AppearanceScreen navigation={mockNavigation} />)+ const { getByText } = await renderLoaded()const { clockSample } = require("../../utils/appearance")expect(getByText(clockSample("24h"))).toBeTruthy()@@ -230,7 +237,7 @@ describe("AppearanceScreen", () => {})it("names the host serving tiles rather than describing the setting", async () => {- const { findByText } = render(<AppearanceScreen navigation={mockNavigation} />)+ const { findByText } = await renderLoaded()expect(await findByText("maps.mxd.codes")).toBeTruthy()})@@ -240,13 +247,13 @@ describe("AppearanceScreen", () => {Promise.resolve(key === "mapStyleUrlLight" ? "https://a.example.org/l.json" : "https://b.example.org/d.json"))- const { findByText } = render(<AppearanceScreen navigation={mockNavigation} />)+ const { findByText } = await renderLoaded()expect(await findByText("a.example.org · b.example.org")).toBeTruthy()})- it("toggles the map tile server panel when pressed", () => {- const { getByTestId, queryByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)+ it("toggles the map tile server panel when pressed", async () => {+ const { getByTestId, queryByTestId } = await renderLoaded()expect(queryByTestId("map-style-url-light")).toBeNull()@@ -258,7 +265,7 @@ describe("AppearanceScreen", () => {// A stored typo blanks every map, and only the reset undoes it.it("refuses a URL that is not one, and saves nothing", async () => {- const { getByTestId, findByText } = render(<AppearanceScreen navigation={mockNavigation} />)+ const { getByTestId, findByText } = await renderLoaded()fireEvent.press(getByTestId("map-tile-server-toggle"))fireEvent.changeText(getByTestId("map-style-url-light"), "htps://tiles.example.org")@@ -269,7 +276,7 @@ describe("AppearanceScreen", () => {})it("saves a good URL and moves the host on the row", async () => {- const { getByTestId, findByText } = render(<AppearanceScreen navigation={mockNavigation} />)+ const { getByTestId, findByText } = await renderLoaded()fireEvent.press(getByTestId("map-tile-server-toggle"))fireEvent.changeText(getByTestId("map-style-url-light"), "https://tiles.example.org/light.json")@@ -283,7 +290,7 @@ describe("AppearanceScreen", () => {it("accepts an emptied field as a return to the default", async () => {mockGetSetting.mockResolvedValue("https://tiles.example.org/light.json")- const { getByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)+ const { getByTestId } = await renderLoaded()fireEvent.press(getByTestId("map-tile-server-toggle"))fireEvent.changeText(getByTestId("map-style-url-light"), "")@@ -293,20 +300,20 @@ describe("AppearanceScreen", () => {})it("offers the reset only once something custom is stored", async () => {- const { getByTestId, queryByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)+ const { getByTestId, queryByTestId } = await renderLoaded()fireEvent.press(getByTestId("map-tile-server-toggle"))expect(queryByTestId("map-style-reset-btn")).toBeNull()mockGetSetting.mockResolvedValue("https://tiles.example.org/light.json")- const custom = render(<AppearanceScreen navigation={mockNavigation} />)+ const custom = await renderLoaded()fireEvent.press(custom.getByTestId("map-tile-server-toggle"))await waitFor(() => expect(custom.getByTestId("map-style-reset-btn")).toBeTruthy())})it("opens the Language screen from a row that names the current choice", async () => {- const { getByTestId, findByText } = render(<AppearanceScreen navigation={mockNavigation} />)+ const { getByTestId, findByText } = await renderLoaded()expect(await findByText("System default")).toBeTruthy()fireEvent.press(getByTestId("nav-language"))@@ -316,7 +323,7 @@ describe("AppearanceScreen", () => {// Android's App languages page changes the choice while Colota sits in the background.it("re-reads the language row when the app comes back to the foreground", async () => {const { AppState } = require("react-native")- const { findByText } = render(<AppearanceScreen navigation={mockNavigation} />)+ const { findByText } = await renderLoaded()expect(await findByText("System default")).toBeTruthy()mockGetAppLanguage.mockResolvedValueOnce({ picked: "en", effective: "en" })diff --git a/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx b/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsxindex 22f32209..c667983b 100644--- a/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx@@ -26,7 +26,13 @@ jest.mock("../../hooks/useTheme", () => ({}))jest.mock("@react-navigation/native", () => ({- useFocusEffect: jest.fn((cb) => cb())+ useFocusEffect: (cb: () => (() => void) | void) => {+ const R = require("react")+ R.useEffect(() => {+ const cleanup = cb()+ return typeof cleanup === "function" ? cleanup : undefined+ }, [cb])+ }}))const mockGetAutoExportStatus = jest.fn().mockResolvedValue({diff --git a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsxindex 51c1482d..ff17c0b6 100644--- a/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/ProfileEditorScreen.test.tsx@@ -332,7 +332,7 @@ describe("ProfileEditorScreen", () => {"On Wi-Fi, track every 1 min after 10 m and sync every 5 min.")- fireEvent.press(getByTestId("condition-wifi_ssid"))+ await act(async () => fireEvent.press(getByTestId("condition-wifi_ssid")))expect(getByTestId("wifi-ssid-input").props.value).toBe("HomeNet")expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(false)})@@ -353,9 +353,9 @@ describe("ProfileEditorScreen", () => {})describe("bluetooth device", () => {- it("blocks Save until a device is picked and opens the device screen for it", () => {+ it("blocks Save until a device is picked and opens the device screen for it", async () => {const { getByTestId, getByText } = renderNew()- fireEvent.press(getByTestId("condition-bluetooth_device"))+ await act(async () => fireEvent.press(getByTestId("condition-bluetooth_device")))expect(getByText("Pick a device")).toBeTruthy()expect(getByText("Pick a device or the profile can't match")).toBeTruthy()@@ -398,7 +398,7 @@ describe("ProfileEditorScreen", () => {})fireEvent.press(getByTestId("condition-charging"))- fireEvent.press(getByTestId("condition-bluetooth_device"))+ await act(async () => fireEvent.press(getByTestId("condition-bluetooth_device")))expect(getByText("Old Car")).toBeTruthy()expect(getByTestId("save-profile-btn").props.accessibilityState.disabled).toBe(false)})diff --git a/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx b/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsxindex 1b6a795b..4b4f00fa 100644--- a/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx@@ -354,7 +354,9 @@ describe("SettingsScreen", () => {// The five slower reads must already be in flight while getStats is still pending.await waitFor(() => expect(mockLoadOfflineAreas).toHaveBeenCalled())expect(mockGetAutoExportStatus).toHaveBeenCalled()- releaseStats({ queued: 0, sent: 0, total: 0, today: 0, databaseSizeMB: 0, lastSyncTime: 0, lastSyncError: "" })+ await act(async () =>+ releaseStats({ queued: 0, sent: 0, total: 0, today: 0, databaseSizeMB: 0, lastSyncTime: 0, lastSyncError: "" })+ )})it("re-reads only the two cheap values on a sync event, not the pack walk", async () => {diff --git a/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx b/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsxindex d1e3fdcb..43499c94 100644--- a/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx@@ -216,8 +216,9 @@ describe("TrackingProfilesScreen", () => {await waitFor(() => expect(mockShowAlert).toHaveBeenCalledWith("Error", "Failed to update profile.", "error"))})- it("reloads on focus, so an edit shows on the way back", () => {- renderScreen()+ it("reloads on focus, so an edit shows on the way back", async () => {+ const { findByTestId } = renderScreen()+ await findByTestId("profile-1")expect(mockAddListener).toHaveBeenCalledWith("focus", expect.any(Function))})})