Files
kandev/apps/web/components/gitlab/my-gitlab/use-saved-presets.test.ts
T
João Salavisa cf76a27488 feat(web): normalize /gitlab page to match /github layout (#1082)
* feat(web): normalize /gitlab page to match /github layout

Adds a presets sidebar (MR/Issue toggle, Inbox/Created groups, Saved
section), a top toolbar with project filter and custom-query input,
paginated MR/Issue lists, and a save-preset dialog backed by a
localStorage store at kandev:gitlab-presets:v1.

Replaces the bespoke tabbed layout and supersedes
hooks/domains/gitlab/use-user-search with the pagination-aware
useGitLabSearch under components/gitlab/my-gitlab/. Project filtering is
applied client-side since GitLab's global MR/issue endpoints have no
path_with_namespace qualifier. No backend changes — the controller
already accepts filter / custom_query / page / per_page.

* fix(web): address /gitlab review feedback

- Merge duplicate cn/formatRelativeTime imports in list-toolbar.
- Drop the generic T from useGitLabSearch — it always resolved to MR | Issue,
  so the as-unknown-as double-cast was just hiding that. Now returns
  Array<MR | Issue> directly and exposes rawTotal alongside total.
- When projectFilter is active, total reflects the client-side filtered
  count instead of the server's unfiltered total so the toolbar badge and
  pagination don't claim "47 results" while only 3 rows render.
- Save flow uses committedQuery, not the draft customQuery, so a preset
  saved without pressing Enter matches what's actually displayed.
- Wrap mobile sidebar handlers in useCallback to keep props stable.
- Drop the unused refresh callback in useGitLabStatusFetch (no caller).
- Add hook-level tests for useSavedPresets save/remove/sync; use
  resetKnownProjectsStore directly in the known-projects test.

* fix(web): address round-2 /gitlab review feedback

- useSavedPresets save/remove now read from localStorage on every call so a
  concurrent write from another tab can't be silently overwritten by a stale
  in-memory snapshot.
- Tighten persisted shape validation: customQuery, projectFilter, and
  createdAt must all be strings (plus 3 regression tests).
- ResultsPagination clamps page to [1, totalPages] before deriving start/end
  and prev/next state, so a stale out-of-range page doesn't render an
  invalid range like "101–30 of 30" after a refresh that shrinks results.
- PresetsSidebar: ignore keydown bubbling from the nested delete button so
  Enter/Space on delete doesn't also trigger row selection, and add an
  aria-label to the icon-only delete control.
- Revert the hook's filtered-total policy: useGitLabSearch always returns
  the raw server total now (so pagination can still navigate to later
  pages). The page client owns the toolbar's displayedCount, computing
  filtered.length only when a project filter is active.

* fix(web): drop dead gitlab preset re-exports, tighten save dialog deps

- Remove unused IconBug / IconPencil imports and the re-export from
  presets.ts — no consumer imports them from this module.
- save-preset-dialog: inline the trimmed check inside handleSubmit so
  canSubmit no longer needs to be in the deps array. ESLint exhaustive-
  deps forced the previous duplication; inlining removes it cleanly.

* fix(web): null-safe response unwrap in useGitLabSearch

If the API returns null, the cast `(response as {mrs: ...}).mrs` would
crash before the `?? []` fallback could run. Optional-chain the cast so a
null payload yields an empty list, matching the existing total_count guard.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-26 16:00:55 +01:00

173 lines
4.9 KiB
TypeScript

import { describe, it, expect, beforeEach, vi } from "vitest";
import { act, renderHook } from "@testing-library/react";
import {
__resetSnapshotForTests,
readStorage,
useSavedPresets,
type SavedPreset,
} from "./use-saved-presets";
const STORAGE_KEY = "kandev:gitlab-presets:v1";
function makeLocalStorageMock() {
const store = new Map<string, string>();
return {
getItem: (key: string) => store.get(key) ?? null,
setItem: (key: string, value: string) => store.set(key, value),
removeItem: (key: string) => store.delete(key),
clear: () => store.clear(),
get length() {
return store.size;
},
key: (index: number) => Array.from(store.keys())[index] ?? null,
};
}
const localStorageMock = makeLocalStorageMock();
vi.stubGlobal("localStorage", localStorageMock);
function set(raw: string | null) {
if (raw === null) localStorageMock.removeItem(STORAGE_KEY);
else localStorageMock.setItem(STORAGE_KEY, raw);
}
const valid: SavedPreset = {
id: "g_1",
kind: "mr",
label: "My MRs",
customQuery: "scope=created_by_me",
projectFilter: "",
createdAt: "2026-01-01T00:00:00Z",
};
describe("readStorage (gitlab)", () => {
beforeEach(() => {
localStorageMock.clear();
});
it("returns empty array when no value is stored", () => {
expect(readStorage()).toEqual([]);
});
it("returns empty array for malformed JSON", () => {
set("not-json{");
expect(readStorage()).toEqual([]);
});
it("returns empty array when parsed value is not an array", () => {
set(JSON.stringify({ id: "g_1" }));
expect(readStorage()).toEqual([]);
});
it("keeps valid entries", () => {
set(JSON.stringify([valid]));
expect(readStorage()).toEqual([valid]);
});
it("drops entries missing an id", () => {
const missingId = { ...valid } as Partial<SavedPreset>;
delete missingId.id;
set(JSON.stringify([missingId, valid]));
expect(readStorage()).toEqual([valid]);
});
it("drops entries with invalid kind", () => {
set(JSON.stringify([{ ...valid, kind: "pr" }, valid]));
expect(readStorage()).toEqual([valid]);
});
it("drops non-object entries", () => {
set(JSON.stringify(["string", 42, null, valid]));
expect(readStorage()).toEqual([valid]);
});
it("drops entries with non-string label", () => {
set(JSON.stringify([{ ...valid, label: 123 }, valid]));
expect(readStorage()).toEqual([valid]);
});
it("accepts issue kind", () => {
const issue: SavedPreset = { ...valid, kind: "issue" };
set(JSON.stringify([issue]));
expect(readStorage()).toEqual([issue]);
});
it("drops entries missing customQuery", () => {
const broken = { ...valid } as Partial<SavedPreset>;
delete broken.customQuery;
set(JSON.stringify([broken, valid]));
expect(readStorage()).toEqual([valid]);
});
it("drops entries missing projectFilter", () => {
const broken = { ...valid } as Partial<SavedPreset>;
delete broken.projectFilter;
set(JSON.stringify([broken, valid]));
expect(readStorage()).toEqual([valid]);
});
it("drops entries missing createdAt", () => {
const broken = { ...valid } as Partial<SavedPreset>;
delete broken.createdAt;
set(JSON.stringify([broken, valid]));
expect(readStorage()).toEqual([valid]);
});
});
describe("useSavedPresets (gitlab)", () => {
beforeEach(() => {
localStorageMock.clear();
__resetSnapshotForTests();
});
it("save appends a preset and assigns id + createdAt", () => {
const { result } = renderHook(() => useSavedPresets());
act(() => {
result.current.save({
kind: "mr",
label: "My MRs",
customQuery: "scope=created_by_me",
projectFilter: "",
});
});
expect(result.current.presets).toHaveLength(1);
const [p] = result.current.presets;
expect(p.label).toBe("My MRs");
expect(p.kind).toBe("mr");
expect(p.id).toMatch(/^g_/);
expect(p.createdAt).toBeTruthy();
});
it("remove deletes the preset", () => {
const { result } = renderHook(() => useSavedPresets());
let created!: SavedPreset;
act(() => {
created = result.current.save({
kind: "issue",
label: "Triage",
customQuery: "labels=bug",
projectFilter: "",
});
});
expect(result.current.presets).toHaveLength(1);
act(() => result.current.remove(created.id));
expect(result.current.presets).toHaveLength(0);
});
it("two hook instances stay in sync via the module-level store", () => {
const a = renderHook(() => useSavedPresets());
const b = renderHook(() => useSavedPresets());
act(() => {
a.result.current.save({
kind: "mr",
label: "Shared",
customQuery: "q",
projectFilter: "",
});
});
expect(a.result.current.presets).toHaveLength(1);
expect(b.result.current.presets).toHaveLength(1);
expect(b.result.current.presets[0].label).toBe("Shared");
});
});