/* @vitest-environment node */ import { describe, it, expect } from "vitest"; import { SEARCH_RESULTS_SORT, toSearchItemIsoDateKey, formatSearchItemDateDe, sortSearchItems, } from "./resultsSorting.js"; describe("lib/frontend/search/resultsSorting", () => { it("builds ISO date keys (YYYY-MM-DD) with zero padding", () => { expect(toSearchItemIsoDateKey({ year: "2025", month: "1", day: "2" })).toBe( "2025-01-02" ); }); it("formats German date strings (DD.MM.YYYY) with zero padding", () => { expect(formatSearchItemDateDe({ year: "2025", month: "1", day: "2" })).toBe( "02.01.2025" ); }); it("RELEVANCE keeps backend order (shallow copy)", () => { const items = [{ filename: "b.pdf" }, { filename: "a.pdf" }]; const out = sortSearchItems(items, SEARCH_RESULTS_SORT.RELEVANCE); expect(out.map((x) => x.filename)).toEqual(["b.pdf", "a.pdf"]); // Ensure we did not return the same array instance (mutation safety). expect(out).not.toBe(items); }); it("DATE_DESC sorts newest date first, then branch asc, then filename asc", () => { const items = [ // Same date, different branches { branch: "NL10", year: "2025", month: "12", day: "18", filename: "b.pdf", }, { branch: "NL2", year: "2025", month: "12", day: "18", filename: "a.pdf", }, // Older date { branch: "NL01", year: "2025", month: "01", day: "02", filename: "z.pdf", }, ]; const out = sortSearchItems(items, SEARCH_RESULTS_SORT.DATE_DESC); expect( out.map((x) => `${toSearchItemIsoDateKey(x)}|${x.branch}|${x.filename}`) ).toEqual([ "2025-12-18|NL2|a.pdf", // NL2 before NL10 (numeric) "2025-12-18|NL10|b.pdf", "2025-01-02|NL01|z.pdf", ]); }); it("BRANCH_ASC sorts branch asc (numeric), then newest date first, then filename asc", () => { const items = [ // NL10 should come after NL2 { branch: "NL10", year: "2025", month: "12", day: "18", filename: "b.pdf", }, { branch: "NL2", year: "2025", month: "12", day: "18", filename: "a.pdf", }, // Same branch (NL2), older date + different filename { branch: "NL2", year: "2025", month: "01", day: "02", filename: "z.pdf", }, { branch: "NL2", year: "2025", month: "12", day: "18", filename: "c.pdf", }, ]; const out = sortSearchItems(items, SEARCH_RESULTS_SORT.BRANCH_ASC); expect( out.map((x) => `${x.branch}|${toSearchItemIsoDateKey(x)}|${x.filename}`) ).toEqual([ // NL2 group first "NL2|2025-12-18|a.pdf", "NL2|2025-12-18|c.pdf", // same date -> filename tie-breaker "NL2|2025-01-02|z.pdf", // then NL10 "NL10|2025-12-18|b.pdf", ]); }); it("unknown sort mode fails safe to backend order", () => { const items = [{ filename: "b.pdf" }, { filename: "a.pdf" }]; const out = sortSearchItems(items, "unknown"); expect(out.map((x) => x.filename)).toEqual(["b.pdf", "a.pdf"]); }); });