Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(geomap): cover the paths the search left untested
Elian Doran69c7d7b280ed
diff --git a/apps/client/src/utils/units.spec.ts b/apps/client/src/utils/units.spec.tsnew file mode 100644index 0000000000..64cc870423--- /dev/null+++ b/apps/client/src/utils/units.spec.ts@@ -0,0 +1,49 @@+/**+ * How a measurement is read out, in either of the systems Trilium states distances in.+ *+ * The unit strings resolve to nothing under test — i18next is never initialized — so what is checked+ * is which unit was reached for and what was handed to it: the number, and how far it was rounded.+ */+import { describe, expect, it, vi } from "vitest";++import { formatDistance, formatElevation, formatSpeed } from "./units";++vi.mock("../services/i18n", () => ({+ t: (key: string, vars?: Record<string, unknown>) => `${key}|${Object.values(vars ?? {}).join()}`+}));++describe("formatDistance", () => {+ it("reads in metres up close and kilometres beyond, where distances are stated in metric", () => {+ expect(formatDistance(0, "metric")).toBe("gpx_preview.unit_m|0");+ expect(formatDistance(850.4, "metric")).toBe("gpx_preview.unit_m|850");+ // The last metre before it turns over, and the first kilometre after.+ expect(formatDistance(999, "metric")).toBe("gpx_preview.unit_m|999");+ expect(formatDistance(1000, "metric")).toBe("gpx_preview.unit_km|1");+ });++ it("reads in miles throughout, where that is how distances are stated", () => {+ // Under a mile is still stated in miles: nobody gives a distance in feet.+ expect(formatDistance(804.672, "imperial")).toBe("gpx_preview.unit_mi|0.5");+ expect(formatDistance(1609.344, "imperial")).toBe("gpx_preview.unit_mi|1");+ });++ it("keeps fewer decimals the larger the number, a distance being read at what it is worth", () => {+ expect(formatDistance(1234, "metric")).toBe("gpx_preview.unit_km|1.23");+ expect(formatDistance(12_340, "metric")).toBe("gpx_preview.unit_km|12.3");+ expect(formatDistance(1_234_000, "metric")).toBe("gpx_preview.unit_km|1,234");+ });+});++describe("formatElevation", () => {+ it("reads in metres or in feet, whole either way — a hill is not measured to the centimetre", () => {+ expect(formatElevation(1234.6, "metric")).toBe("gpx_preview.unit_m|1,235");+ expect(formatElevation(1000, "imperial")).toBe("gpx_preview.unit_ft|3,281");+ });+});++describe("formatSpeed", () => {+ it("reads in kilometres or miles an hour, from the kilometres an hour it is given", () => {+ expect(formatSpeed(12.34, "metric")).toBe("gpx_preview.unit_kmh|12.3");+ expect(formatSpeed(160.9344, "imperial")).toBe("gpx_preview.unit_mph|100");+ });+});diff --git a/apps/client/src/widgets/collections/geomap/api.spec.ts b/apps/client/src/widgets/collections/geomap/api.spec.tsindex 820a0dea65..577d7b3ff2 100644--- a/apps/client/src/widgets/collections/geomap/api.spec.ts+++ b/apps/client/src/widgets/collections/geomap/api.spec.ts@@ -1,19 +1,34 @@/**- * What the geo map writes when something is put on it (see api.ts): the note a placement click- * creates, and the note a GPX file is brought in as. Both go through the ordinary note-creation- * service; what is checked here is what they ask it for.+ * What the geo map writes when something is put on it or taken off it (see api.ts): the note a+ * placement click creates, the note a searched place is kept as, the note a GPX file is brought in+ * as, and what becomes of a marker the reader is done with. All go through the ordinary note+ * services; what is checked here is what they are asked for.*/-import { describe, expect, it, vi } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";+import attributes from "../../../services/attributes";+import dialog from "../../../services/dialog";import note_create from "../../../services/note_create";+import { deleteNoteOrBranch } from "../../../services/note_deletion";import { buildNote } from "../../../test/easy-froca";-import { createNewNote, importGpxTrack } from "./api";+import { createNewNote, createNoteForPlace, importGpxTrack, moveMarker, removeFromMap } from "./api";vi.mock("../../../services/note_create", () => ({default: { createNote: vi.fn(async () => ({ note: { noteId: "created" }, branch: null })) }}));+vi.mock("../../../services/attributes", () => ({ default: { setLabel: vi.fn(async () => {}) } }));+vi.mock("../../../services/note_deletion", () => ({ deleteNoteOrBranch: vi.fn(async () => {}) }));+vi.mock("../../../services/dialog", () => ({+ default: { confirmDeleteNoteBoxWithNote: vi.fn() }+}));+const createNote = vi.mocked(note_create.createNote);+const setLabel = vi.mocked(attributes.setLabel);+const confirmDelete = vi.mocked(dialog.confirmDeleteNoteBoxWithNote);++// What each of these asks for is what is checked, so what an earlier one asked for is noise.+beforeEach(() => vi.clearAllMocks());describe("geo map api", () => {it("creates a placed note under the stock name, located where the click landed", async () => {@@ -38,6 +53,24 @@ describe("geo map api", () => {}));});+ it("names a note for a searched place as the place is named, and stands it there", async () => {+ const parent = buildNote({ title: "The map" });++ const created = await createNoteForPlace(parent, { name: "Jumbo", lat: 45.796, lng: 24.147 });++ expect(created).toEqual({ noteId: "created" });+ expect(createNote).toHaveBeenCalledWith(parent.noteId, expect.objectContaining({+ // Named already, unlike a note dropped by clicking: the geocoder named the place.+ title: "Jumbo",+ type: "text",+ activate: false,+ attributes: expect.arrayContaining([+ { type: "label", name: "geolocation", value: "45.796,24.147" },+ { type: "label", name: "iconClass", value: "bx bx-pin" }+ ])+ }));+ });+it("brings a GPX file in as a file note the map draws tracks by", async () => {const parent = buildNote({ title: "The map" });const file = new File([ "<gpx><trk/></gpx>" ], "sunday-ride.gpx");@@ -56,4 +89,47 @@ describe("geo map api", () => {attributes: [ { type: "label", name: "originalFileName", value: "sunday-ride.gpx" } ]}));});++ it("writes a marker's location, and empties it to take the marker off the map", async () => {+ await moveMarker("note1", { lat: 45.796, lng: 24.147 });+ expect(setLabel).toHaveBeenLastCalledWith("note1", "geolocation", "45.796,24.147");++ // An empty value is what leaves the note in place with no marker standing for it.+ await moveMarker("note1", null);+ expect(setLabel).toHaveBeenLastCalledWith("note1", "geolocation", "");+ });++ describe("taking a marker off the map", () => {+ it("deletes the note where that is what the reader agreed to", async () => {+ const map = buildNote({ title: "The map" });+ const note = buildNote({ title: "A place" });+ confirmDelete.mockResolvedValue({ confirmed: true, isDeleteNoteChecked: true });++ await removeFromMap(note, map);++ expect(deleteNoteOrBranch).toHaveBeenCalledWith(note.noteId, null);+ expect(setLabel).not.toHaveBeenCalledWith(note.noteId, "geolocation", "");+ });++ it("keeps the note and clears its location where the reader only wanted it off the map", async () => {+ const map = buildNote({ title: "The map" });+ const note = buildNote({ title: "A place" });+ confirmDelete.mockResolvedValue({ confirmed: true, isDeleteNoteChecked: false });++ await removeFromMap(note, map);++ expect(setLabel).toHaveBeenLastCalledWith(note.noteId, "geolocation", "");+ });++ it("leaves the marker alone where the reader changed their mind", async () => {+ const map = buildNote({ title: "The map" });+ const note = buildNote({ title: "A place" });+ confirmDelete.mockResolvedValue({ confirmed: false, isDeleteNoteChecked: false });++ await removeFromMap(note, map);++ expect(deleteNoteOrBranch).not.toHaveBeenCalled();+ expect(setLabel).not.toHaveBeenCalled();+ });+ });});diff --git a/apps/client/src/widgets/collections/geomap/nominatim.spec.ts b/apps/client/src/widgets/collections/geomap/nominatim.spec.tsindex a8f938b64b..64b65190e6 100644--- a/apps/client/src/widgets/collections/geomap/nominatim.spec.ts+++ b/apps/client/src/widgets/collections/geomap/nominatim.spec.ts@@ -6,7 +6,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { nominatim as provider } from "./nominatim";-vi.mock("../../../services/i18n", () => ({ getCurrentLanguage: () => "pt_br" }));+/** The locale the app is running in, which a test can settle for itself. */+let language = "pt_br";++vi.mock("../../../services/i18n", () => ({ getCurrentLanguage: () => language }));/** One entry as Nominatim's `jsonv2` answer carries it. */function place(overrides: Record<string, unknown> = {}) {@@ -58,7 +61,10 @@ function requestedUrl(fetchMock: ReturnType<typeof respondWith>, call = 0) {return new URL(fetchMock.mock.calls[call][0]);}-beforeEach(() => vi.useFakeTimers());+beforeEach(() => {+ vi.useFakeTimers();+ language = "pt_br";+});afterEach(() => {vi.useRealTimers();vi.unstubAllGlobals();@@ -298,6 +304,83 @@ describe("Nominatim geocoding", () => {expect(await outlineFetch).toBeNull();});+ it("asks for no language in particular where the app has settled on none", async () => {+ language = "";+ const fetchMock = respondWith([]);++ await search("berlin");++ expect(requestedUrl(fetchMock).searchParams.get("accept-language")).toBeNull();+ });++ it("names a town and a region by whichever kind of place fills that role", async () => {+ respondWith([+ // A village has no city, and a county stands in for a state where a country has none.+ place({ address: { village: "Rasinari", county: "Sibiu", country: "Romania", country_code: "RO" } })+ ]);++ const [ result ] = await search("rasinari");++ expect(result.address).toMatchObject({+ locality: "Rasinari",+ region: "Sibiu",+ country: "Romania",+ // Lowercased, a flag being looked up by it.+ countryCode: "ro"+ });+ });++ it("holds no address for a result Nominatim broke into no parts of one", async () => {+ // Distinct places: two that read the same are one answer, and only one survives.+ respondWith([+ place({ address: {} }),+ place({ osm_id: 63, display_name: "Elsewhere", address: undefined })+ ]);++ const results = await search("nowhere");++ expect(results.map((result) => result.address)).toEqual([ undefined, undefined ]);+ });++ it("falls back to Nominatim's numbering, and then to the position, to tell a place apart", async () => {+ respondWith([+ // No OSM object named at all, so its own numbering is all there is to go on.+ place({ osm_type: undefined, osm_id: undefined, place_id: 111, display_name: "One" }),+ // A kind of object without the id of one, which names nothing either.+ place({ osm_type: "node", osm_id: undefined, place_id: 222, display_name: "Two" }),+ // Not even that, and what is left is where it stands.+ place({+ osm_type: undefined, osm_id: undefined, place_id: undefined,+ display_name: "Three", lat: "1.5", lon: "2.5"+ })+ ]);++ const results = await search("anywhere");++ expect(results.map((result) => result.id)).toEqual([ "111", "222", "1.5,2.5" ]);+ // None of them can be asked for a boundary: that wants an OSM object to look up.+ expect(results.map((result) => result.outline)).toEqual([ undefined, undefined, undefined ]);+ });++ it("frames nothing for a place whose extent runs the other way round the world", async () => {+ // Reported west of east, which as a rectangle is the whole world the long way round.+ respondWith([ place({ boundingbox: [ "-18", "-16", "177", "-179" ] }) ]);++ const [ result ] = await search("fiji");++ expect(result.bounds).toBeUndefined();+ });++ it("reports a refused boundary lookup rather than drawing nothing quietly", async () => {+ respondWith([ place() ]);+ const [ berlin ] = await search("berlin");++ respondWith([], { ok: false, status: 429 });+ const refused = expect(berlin.outline?.()).rejects.toThrow("429");+ await vi.runAllTimersAsync();+ await refused;+ });+it("holds searches to the one request a second the usage policy allows", async () => {const requestedAt: number[] = [];vi.stubGlobal("fetch", vi.fn(async () => {