From bdf1afe596f45ee1b3f71d05f19d5c3fdacc039d Mon Sep 17 00:00:00 2001
From: Tara Aqeel
Date: Sun, 1 Nov 2026 01:01:11 +0100
Subject: [PATCH 1/5] test: legg til tester for useHomeStats
---
frontend/src/hooks/useHomeStats.test.tsx | 86 ++++++++++++++++++++++++
1 file changed, 86 insertions(+)
create mode 100644 frontend/src/hooks/useHomeStats.test.tsx
diff --git a/frontend/src/hooks/useHomeStats.test.tsx b/frontend/src/hooks/useHomeStats.test.tsx
new file mode 100644
index 0000000..9631456
--- /dev/null
+++ b/frontend/src/hooks/useHomeStats.test.tsx
@@ -0,0 +1,86 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+import { useQuery } from "@apollo/client/react";
+import { useHomeStats } from "./useHomeStats";
+
+// Vi erstatter Apollos useQuery med en mock, slik at backend ikke trengs.
+vi.mock("@apollo/client/react", () => ({
+ useQuery: vi.fn(),
+}));
+
+const mockedUseQuery = vi.mocked(useQuery);
+
+describe("useHomeStats", () => {
+ // Nullstiller mocken etter hver test.
+ afterEach(() => {
+ vi.resetAllMocks();
+ });
+
+ // Sjekker at hooken returnerer riktig produkt- og butikkantall.
+ it("returnerer produktantall og antall butikker", () => {
+ mockedUseQuery.mockReturnValue({
+ data: {
+ productsCount: 46853,
+ stores: [{ code: "KIWI" }, { code: "MENY_NO" }],
+ },
+ loading: false,
+ error: undefined,
+ } as ReturnType);
+
+ const { result } = renderHook(() => useHomeStats());
+
+ expect(result.current.productCount).toBe(46853);
+ expect(result.current.storeCount).toBe(2);
+ expect(result.current.loading).toBe(false);
+ expect(result.current.error).toBeUndefined();
+ });
+
+ // Under lasting finnes det ennå ingen statistikk.
+ it("håndterer lasting", () => {
+ mockedUseQuery.mockReturnValue({
+ data: undefined,
+ loading: true,
+ error: undefined,
+ } as ReturnType);
+
+ const { result } = renderHook(() => useHomeStats());
+
+ expect(result.current.loading).toBe(true);
+ expect(result.current.productCount).toBeUndefined();
+ expect(result.current.storeCount).toBeUndefined();
+ });
+
+ // Sjekker at GraphQL-feil sendes videre til komponenten.
+ it("håndterer feil ved henting av data", () => {
+ const error = new Error("Kunne ikke hente statistikk");
+
+ mockedUseQuery.mockReturnValue({
+ data: undefined,
+ loading: false,
+ error,
+ } as ReturnType);
+
+ const { result } = renderHook(() => useHomeStats());
+
+ expect(result.current.error).toBe(error);
+ expect(result.current.productCount).toBeUndefined();
+ expect(result.current.storeCount).toBeUndefined();
+ });
+
+ // En tom butikkliste skal gi 0 butikker, ikke undefined.
+ it("håndterer tom butikkliste", () => {
+ mockedUseQuery.mockReturnValue({
+ data: {
+ productsCount: 0,
+ stores: [],
+ },
+ loading: false,
+ error: undefined,
+ } as ReturnType);
+
+ const { result } = renderHook(() => useHomeStats());
+
+ expect(result.current.productCount).toBe(0);
+ expect(result.current.storeCount).toBe(0);
+ });
+});
\ No newline at end of file
From 6f3c5f8cab8d9a8647a4a12a2d72119057c54194 Mon Sep 17 00:00:00 2001
From: Tara Aqeel
Date: Sun, 1 Nov 2026 01:03:15 +0100
Subject: [PATCH 2/5] test: legg til tester for useCategoryCounts
---
frontend/src/hooks/useCategoryCounts.test.tsx | 144 ++++++++++++++++++
1 file changed, 144 insertions(+)
create mode 100644 frontend/src/hooks/useCategoryCounts.test.tsx
diff --git a/frontend/src/hooks/useCategoryCounts.test.tsx b/frontend/src/hooks/useCategoryCounts.test.tsx
new file mode 100644
index 0000000..8dc29ee
--- /dev/null
+++ b/frontend/src/hooks/useCategoryCounts.test.tsx
@@ -0,0 +1,144 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+import { useQuery } from "@apollo/client/react";
+import { useCategoryCounts } from "./useCategoryCounts";
+import { homeCategories } from "../pages/home/homeCategories";
+
+// Erstatter GraphQL-kallet med testdata, uten behov for backend.
+vi.mock("@apollo/client/react", () => ({
+ useQuery: vi.fn(),
+}));
+
+const mockedUseQuery = vi.mocked(useQuery);
+
+describe("useCategoryCounts", () => {
+ // Nullstiller mocken mellom testene.
+ afterEach(() => {
+ vi.resetAllMocks();
+ });
+
+ it("kobler kategoriantall til riktige kategorier", () => {
+ const category = homeCategories[0];
+
+ mockedUseQuery.mockReturnValue({
+ data: {
+ categoryFilterCounts: [
+ {
+ value: "kategori-1",
+ label: category.name,
+ count: 125,
+ },
+ ],
+ },
+ loading: false,
+ error: undefined,
+ } as ReturnType);
+
+ const { result } = renderHook(() => useCategoryCounts());
+
+ expect(result.current.categories).toEqual([
+ {
+ name: category.name,
+ description: category.description,
+ categoryIds: ["kategori-1"],
+ count: 125,
+ },
+ ]);
+ });
+
+ it("matcher kategorinavn uavhengig av store og små bokstaver", () => {
+ const category = homeCategories[0];
+
+ mockedUseQuery.mockReturnValue({
+ data: {
+ categoryFilterCounts: [
+ {
+ value: "kategori-1",
+ label: category.name.toLocaleUpperCase("nb-NO"),
+ count: 25,
+ },
+ ],
+ },
+ loading: false,
+ error: undefined,
+ } as ReturnType);
+
+ const { result } = renderHook(() => useCategoryCounts());
+
+ expect(result.current.categories[0]?.name).toBe(category.name);
+ expect(result.current.categories[0]?.count).toBe(25);
+ });
+
+ it("sorterer kategoriene alfabetisk på norsk", () => {
+ // Bruker kategorinavn fra den faktiske forsidedefinisjonen.
+ const selectedCategories = homeCategories.slice(0, 3);
+
+ mockedUseQuery.mockReturnValue({
+ data: {
+ categoryFilterCounts: selectedCategories.map((category, index) => ({
+ value: `kategori-${index}`,
+ label: category.name,
+ count: index + 1,
+ })),
+ },
+ loading: false,
+ error: undefined,
+ } as ReturnType);
+
+ const { result } = renderHook(() => useCategoryCounts());
+
+ const names = result.current.categories.map((category) => category.name);
+ const expected = [...names].sort((a, b) => a.localeCompare(b, "nb-NO"));
+
+ expect(names).toEqual(expected);
+ });
+
+ it("utelater kategorier uten treff", () => {
+ mockedUseQuery.mockReturnValue({
+ data: {
+ categoryFilterCounts: [
+ {
+ value: "ukjent",
+ label: "Kategori som ikke finnes",
+ count: 10,
+ },
+ ],
+ },
+ loading: false,
+ error: undefined,
+ } as ReturnType);
+
+ const { result } = renderHook(() => useCategoryCounts());
+
+ expect(result.current.categories).toEqual([]);
+ });
+
+ it("håndterer lasting uten data", () => {
+ mockedUseQuery.mockReturnValue({
+ data: undefined,
+ loading: true,
+ error: undefined,
+ } as ReturnType);
+
+ const { result } = renderHook(() => useCategoryCounts());
+
+ expect(result.current.loading).toBe(true);
+ expect(result.current.categories).toEqual([]);
+ });
+
+ it("videreformidler feil fra GraphQL", () => {
+ const error = new Error("Kunne ikke hente kategorier");
+
+ mockedUseQuery.mockReturnValue({
+ data: undefined,
+ loading: false,
+ error,
+ } as ReturnType);
+
+ const { result } = renderHook(() => useCategoryCounts());
+
+ expect(result.current.error).toBe(error);
+ expect(result.current.categories).toEqual([]);
+ });
+});
+
From a78a34f780841bb73a33afc7eb4e550827de4331 Mon Sep 17 00:00:00 2001
From: Tara Aqeel
Date: Sun, 1 Nov 2026 01:06:00 +0100
Subject: [PATCH 3/5] test: legg til tester for useSearchState
---
.../hooks/useSearchState.test.tsx | 169 ++++++++++++++++++
1 file changed, 169 insertions(+)
create mode 100644 frontend/src/pages/SearchResults/hooks/useSearchState.test.tsx
diff --git a/frontend/src/pages/SearchResults/hooks/useSearchState.test.tsx b/frontend/src/pages/SearchResults/hooks/useSearchState.test.tsx
new file mode 100644
index 0000000..a9dca82
--- /dev/null
+++ b/frontend/src/pages/SearchResults/hooks/useSearchState.test.tsx
@@ -0,0 +1,169 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { MemoryRouter } from "react-router";
+import type { ReactNode } from "react";
+
+import { useSearchState } from "./useSearchState";
+import {
+ defaultSearchPreferences,
+ type SearchPreferences,
+} from "../searchPreferencesStorage";
+import { STORAGE_KEYS } from "../../../constants/storageKeys";
+
+// Simulerer en URL uten å starte hele applikasjonen.
+function createWrapper(url: string) {
+ return function Wrapper({ children }: { children: ReactNode }) {
+ return {children};
+ };
+}
+
+// Leser preferansene som faktisk blir lagret.
+function getSavedPreferences(): SearchPreferences {
+ const saved = localStorage.getItem(STORAGE_KEYS.searchPreferences);
+ expect(saved).not.toBeNull();
+ return JSON.parse(saved!) as SearchPreferences;
+}
+
+describe("useSearchState", () => {
+ // Hver test starter uten lagrede søkeinnstillinger.
+ beforeEach(() => {
+ localStorage.clear();
+ });
+
+ it("leser søkeord fra URL-en", () => {
+ const { result } = renderHook(() => useSearchState(), {
+ wrapper: createWrapper("/search?q=melk"),
+ });
+
+ expect(result.current.searchTerm).toBe("melk");
+ expect(result.current.currentPage).toBe(1);
+ expect(result.current.sort).toBe("relevance");
+ });
+
+ it("starter med standardverdier når søket er tomt", () => {
+ const { result } = renderHook(() => useSearchState(), {
+ wrapper: createWrapper("/search"),
+ });
+
+ expect(result.current.searchTerm).toBe("");
+ expect(result.current.selectedCategories).toEqual([]);
+ expect(result.current.selectedStores).toEqual([]);
+ expect(result.current.currentPage).toBe(1);
+ expect(result.current.sort).toBe("relevance");
+ });
+
+ it("leser flere kategorier fra URL-en", () => {
+ const { result } = renderHook(() => useSearchState(), {
+ wrapper: createWrapper(
+ "/search?category=frukt&category=meieri",
+ ),
+ });
+
+ expect(result.current.selectedCategories).toEqual([
+ "frukt",
+ "meieri",
+ ]);
+ expect(result.current.selectedStores).toEqual([]);
+ });
+
+ it("gjenbruker lagrede preferanser for samme søkeord", () => {
+ // Lagrer preferanser før hooken opprettes.
+ localStorage.setItem(
+ STORAGE_KEYS.searchPreferences,
+ JSON.stringify({
+ searchTerm: "melk",
+ selectedCategories: ["meieri"],
+ selectedStores: ["KIWI"],
+ sort: "price_asc",
+ currentPage: 3,
+ }),
+ );
+
+ const { result } = renderHook(() => useSearchState(), {
+ wrapper: createWrapper("/search?q=melk"),
+ });
+
+ expect(result.current.selectedCategories).toEqual(["meieri"]);
+ expect(result.current.selectedStores).toEqual(["KIWI"]);
+ expect(result.current.sort).toBe("price_asc");
+ expect(result.current.currentPage).toBe(3);
+ });
+
+ it("nullstiller preferanser ved nytt søkeord", () => {
+ localStorage.setItem(
+ STORAGE_KEYS.searchPreferences,
+ JSON.stringify({
+ searchTerm: "melk",
+ selectedCategories: ["meieri"],
+ selectedStores: ["KIWI"],
+ sort: "price_desc",
+ currentPage: 4,
+ }),
+ );
+
+ const { result } = renderHook(() => useSearchState(), {
+ wrapper: createWrapper("/search?q=br%C3%B8d"),
+ });
+
+ expect(result.current.searchTerm).toBe("brød");
+ expect(result.current.selectedCategories).toEqual([]);
+ expect(result.current.selectedStores).toEqual([]);
+ expect(result.current.sort).toBe("relevance");
+ expect(result.current.currentPage).toBe(1);
+ });
+
+ it("oppdaterer sidetall og sortering", () => {
+ const { result } = renderHook(() => useSearchState(), {
+ wrapper: createWrapper("/search?q=melk"),
+ });
+
+ // act sørger for at React behandler state-endringene.
+ act(() => {
+ result.current.setCurrentPage(2);
+ result.current.setSort("price_asc");
+ });
+
+ expect(result.current.currentPage).toBe(2);
+ expect(result.current.sort).toBe("price_asc");
+ });
+
+ it("oppdaterer valgte kategorier og butikker", () => {
+ const { result } = renderHook(() => useSearchState(), {
+ wrapper: createWrapper("/search?q=melk"),
+ });
+
+ act(() => {
+ result.current.setSelectedCategories(["meieri"]);
+ result.current.setSelectedStores(["KIWI", "MENY_NO"]);
+ });
+
+ expect(result.current.selectedCategories).toEqual(["meieri"]);
+ expect(result.current.selectedStores).toEqual([
+ "KIWI",
+ "MENY_NO",
+ ]);
+ });
+
+ it("lagrer oppdaterte søkeinnstillinger i localStorage", async () => {
+ const { result } = renderHook(() => useSearchState(), {
+ wrapper: createWrapper("/search?q=melk"),
+ });
+
+ act(() => {
+ result.current.setCurrentPage(3);
+ result.current.setSort("price_desc");
+ result.current.setSelectedCategories(["meieri"]);
+ });
+
+ // Venter til useEffect har skrevet de nye verdiene.
+ await waitFor(() => {
+ expect(getSavedPreferences()).toEqual({
+ ...defaultSearchPreferences,
+ searchTerm: "melk",
+ selectedCategories: ["meieri"],
+ sort: "price_desc",
+ currentPage: 3,
+ });
+ });
+ });
+});
\ No newline at end of file
From 4f599e0e00d7758f221363495699de1e33d58124 Mon Sep 17 00:00:00 2001
From: Tara Aqeel
Date: Sun, 1 Nov 2026 01:09:49 +0100
Subject: [PATCH 4/5] test: legg til tester for useTheme
---
frontend/src/hooks/useTheme.test.tsx | 106 +++++++++++++++++++++++++++
1 file changed, 106 insertions(+)
create mode 100644 frontend/src/hooks/useTheme.test.tsx
diff --git a/frontend/src/hooks/useTheme.test.tsx b/frontend/src/hooks/useTheme.test.tsx
new file mode 100644
index 0000000..031530d
--- /dev/null
+++ b/frontend/src/hooks/useTheme.test.tsx
@@ -0,0 +1,106 @@
+import { beforeEach, afterEach, describe, expect, it } from "vitest";
+import { act, renderHook, waitFor } from "@testing-library/react";
+
+import { useTheme } from "./useTheme";
+import { STORAGE_KEYS } from "../constants/storageKeys";
+
+describe("useTheme", () => {
+ // Nullstiller localStorage og HTML-tema før hver test.
+ beforeEach(() => {
+ localStorage.clear();
+ document.documentElement.removeAttribute("data-theme");
+ });
+
+ // Rydder opp etter testene.
+ afterEach(() => {
+ document.documentElement.removeAttribute("data-theme");
+ });
+
+ // TEST 1: Standardtema
+ it("bruker systemtema som standard", () => {
+ const { result } = renderHook(() => useTheme());
+
+ expect(result.current[0]).toBe("system");
+ expect(document.documentElement).not.toHaveAttribute("data-theme");
+ });
+
+ // TEST 2: Lyst tema
+ it("setter lyst tema på HTML-elementet", () => {
+ const { result } = renderHook(() => useTheme());
+
+ act(() => {
+ result.current[1]("light");
+ });
+
+ expect(result.current[0]).toBe("light");
+ expect(document.documentElement).toHaveAttribute("data-theme", "light");
+ });
+
+ // TEST 3: Mørkt tema
+ it("setter mørkt tema på HTML-elementet", () => {
+ const { result } = renderHook(() => useTheme());
+
+ act(() => {
+ result.current[1]("dark");
+ });
+
+ expect(result.current[0]).toBe("dark");
+ expect(document.documentElement).toHaveAttribute("data-theme", "dark");
+ });
+
+ // TEST 4: Tilbake til systemtema
+ it("fjerner data-theme når systemtema velges", () => {
+ const { result } = renderHook(() => useTheme());
+
+ // Velger først mørkt tema.
+ act(() => {
+ result.current[1]("dark");
+ });
+
+ expect(document.documentElement).toHaveAttribute("data-theme", "dark");
+
+ // Systemtema skal fjerne den eksplisitte temainnstillingen.
+ act(() => {
+ result.current[1]("system");
+ });
+
+ expect(result.current[0]).toBe("system");
+ expect(document.documentElement).not.toHaveAttribute("data-theme");
+ });
+
+ // TEST 5: Tidligere lagret tema
+ it("leser tidligere lagret tema", () => {
+ localStorage.setItem(STORAGE_KEYS.theme, JSON.stringify("dark"));
+
+ const { result } = renderHook(() => useTheme());
+
+ expect(result.current[0]).toBe("dark");
+ expect(document.documentElement).toHaveAttribute("data-theme", "dark");
+ });
+
+ // TEST 6: Ugyldig lagret tema
+ it("bruker systemtema dersom lagret verdi er ugyldig", () => {
+ localStorage.setItem(STORAGE_KEYS.theme, JSON.stringify("purple"));
+
+ const { result } = renderHook(() => useTheme());
+
+ expect(result.current[0]).toBe("system");
+ expect(document.documentElement).not.toHaveAttribute("data-theme");
+ });
+
+ // TEST 7: Lagring av temavalg
+ it("lagrer temavalget i localStorage", async () => {
+ const { result } = renderHook(() => useTheme());
+
+ act(() => {
+ result.current[1]("light");
+ });
+
+ // Kontrollerer at useEffect har lagret temavalget.
+ await waitFor(() => {
+ expect(
+ JSON.parse(localStorage.getItem(STORAGE_KEYS.theme) ?? "null"),
+ ).toBe("light");
+ });
+ });
+});
From cd5e5adb93f9fcb4c35c36dddd1908440a8a10ff Mon Sep 17 00:00:00 2001
From: Linde Vrenne
Date: Mon, 2 Nov 2026 10:52:09 +0100
Subject: [PATCH 5/5] Formattert #180 med prettier
---
frontend/src/App.tsx | 18 ++--
.../components/resultRow/ResultRow.test.tsx | 15 ++-
.../searchfield/SearchField.test.tsx | 2 +-
frontend/src/hooks/useCategoryCounts.test.tsx | 1 -
frontend/src/hooks/useHomeStats.test.tsx | 2 +-
frontend/src/hooks/useHomeStats.ts | 2 +-
frontend/src/hooks/useStoreNames.ts | 5 +-
.../SearchResults/hooks/usePreserveScroll.ts | 8 +-
.../SearchResults/hooks/useSearchResults.ts | 102 +++++++++---------
.../hooks/useSearchState.test.tsx | 16 +--
.../SearchResults/hooks/useSearchState.ts | 19 ++--
.../SearchResults/searchPreferencesStorage.ts | 47 +++-----
.../src/pages/SearchResults/searchQueries.ts | 2 +-
.../productDetails/ProductDetailsPage.tsx | 38 ++++---
frontend/src/test/setup.ts | 2 +-
frontend/vite.config.ts | 2 +-
16 files changed, 120 insertions(+), 161 deletions(-)
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 01c3bea..a67f4ff 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -180,15 +180,15 @@ function AppLayout() {
} />
-
- }
- />
+
+ }
+ />
} />
diff --git a/frontend/src/components/resultRow/ResultRow.test.tsx b/frontend/src/components/resultRow/ResultRow.test.tsx
index 7c6b606..7c6a03d 100644
--- a/frontend/src/components/resultRow/ResultRow.test.tsx
+++ b/frontend/src/components/resultRow/ResultRow.test.tsx
@@ -43,9 +43,10 @@ describe("ResultRow", () => {
it("viser produktlenke når to er oppgitt", () => {
renderResultRow({ to: "/product/1234567890123" });
- expect(
- screen.getByRole("link", { name: "Havregryn" }),
- ).toHaveAttribute("href", "/product/1234567890123");
+ expect(screen.getByRole("link", { name: "Havregryn" })).toHaveAttribute(
+ "href",
+ "/product/1234567890123",
+ );
});
// Produktnavnet skal være vanlig tekst uten URL.
@@ -107,13 +108,9 @@ describe("ResultRow", () => {
onDecrease,
});
- await user.click(
- screen.getByRole("button", { name: "Flere Havregryn" }),
- );
+ await user.click(screen.getByRole("button", { name: "Flere Havregryn" }));
- await user.click(
- screen.getByRole("button", { name: "Færre Havregryn" }),
- );
+ await user.click(screen.getByRole("button", { name: "Færre Havregryn" }));
expect(onIncrease).toHaveBeenCalledTimes(1);
expect(onDecrease).toHaveBeenCalledTimes(1);
diff --git a/frontend/src/components/searchfield/SearchField.test.tsx b/frontend/src/components/searchfield/SearchField.test.tsx
index 4471e34..deed737 100644
--- a/frontend/src/components/searchfield/SearchField.test.tsx
+++ b/frontend/src/components/searchfield/SearchField.test.tsx
@@ -57,4 +57,4 @@ describe("SearchField", () => {
expect(screen.getByRole("searchbox")).toBeDisabled();
});
-});
\ No newline at end of file
+});
diff --git a/frontend/src/hooks/useCategoryCounts.test.tsx b/frontend/src/hooks/useCategoryCounts.test.tsx
index 8dc29ee..c42ebe3 100644
--- a/frontend/src/hooks/useCategoryCounts.test.tsx
+++ b/frontend/src/hooks/useCategoryCounts.test.tsx
@@ -141,4 +141,3 @@ describe("useCategoryCounts", () => {
expect(result.current.categories).toEqual([]);
});
});
-
diff --git a/frontend/src/hooks/useHomeStats.test.tsx b/frontend/src/hooks/useHomeStats.test.tsx
index 9631456..a08b4e0 100644
--- a/frontend/src/hooks/useHomeStats.test.tsx
+++ b/frontend/src/hooks/useHomeStats.test.tsx
@@ -83,4 +83,4 @@ describe("useHomeStats", () => {
expect(result.current.productCount).toBe(0);
expect(result.current.storeCount).toBe(0);
});
-});
\ No newline at end of file
+});
diff --git a/frontend/src/hooks/useHomeStats.ts b/frontend/src/hooks/useHomeStats.ts
index 0a205de..c4abd7d 100644
--- a/frontend/src/hooks/useHomeStats.ts
+++ b/frontend/src/hooks/useHomeStats.ts
@@ -27,4 +27,4 @@ export function useHomeStats() {
loading,
error,
};
-}
\ No newline at end of file
+}
diff --git a/frontend/src/hooks/useStoreNames.ts b/frontend/src/hooks/useStoreNames.ts
index 9bbbecc..056d3d8 100644
--- a/frontend/src/hooks/useStoreNames.ts
+++ b/frontend/src/hooks/useStoreNames.ts
@@ -34,11 +34,12 @@ export function useStoreNames() {
// Oppslag fra kode til navn. Bygges bare på nytt når dataene endres.
const storeNames = useMemo(
- () => new Map((data?.stores ?? []).map((store) => [store.code, store.name])),
+ () =>
+ new Map((data?.stores ?? []).map((store) => [store.code, store.name])),
[data],
);
const getStoreName = (code: string) => storeNames.get(code) ?? code;
return { getStoreName };
-}
\ No newline at end of file
+}
diff --git a/frontend/src/pages/SearchResults/hooks/usePreserveScroll.ts b/frontend/src/pages/SearchResults/hooks/usePreserveScroll.ts
index 302b938..6fee556 100644
--- a/frontend/src/pages/SearchResults/hooks/usePreserveScroll.ts
+++ b/frontend/src/pages/SearchResults/hooks/usePreserveScroll.ts
@@ -1,4 +1,3 @@
-
import { useLayoutEffect, useRef, useState } from "react";
// Bevarer scrollposisjonen når filtre eller sortering endres.
@@ -8,17 +7,14 @@ export function usePreserveScroll() {
const resultsRef = useRef(null);
const productsSectionRef = useRef(null);
- const [loadingMinHeight, setLoadingMinHeight] =
- useState(null);
+ const [loadingMinHeight, setLoadingMinHeight] = useState(null);
// Husk scrollposisjonen og høyden på resultatlisten.
const preservePosition = () => {
scrollPositionRef.current = window.scrollY;
if (resultsRef.current) {
- setLoadingMinHeight(
- resultsRef.current.getBoundingClientRect().height,
- );
+ setLoadingMinHeight(resultsRef.current.getBoundingClientRect().height);
}
};
diff --git a/frontend/src/pages/SearchResults/hooks/useSearchResults.ts b/frontend/src/pages/SearchResults/hooks/useSearchResults.ts
index 70ee469..b31cefc 100644
--- a/frontend/src/pages/SearchResults/hooks/useSearchResults.ts
+++ b/frontend/src/pages/SearchResults/hooks/useSearchResults.ts
@@ -44,11 +44,13 @@ function normalizeCounts(
typeof item.label === "string" &&
typeof item.count === "number"
) {
- return [{
- value: item.value,
- label: item.label,
- count: item.count,
- }];
+ return [
+ {
+ value: item.value,
+ label: item.label,
+ count: item.count,
+ },
+ ];
}
return [];
@@ -60,19 +62,22 @@ function normalizeCounts(
// ==========================================
function normalizeProducts(
- items: ReadonlyArray<{
- ean?: string;
- name?: string;
- brand?: string | null;
- imageUrl?: string | null;
- categoryId?: string | null;
- prices?: ReadonlyArray<{
- storeCode?: string;
- storeName?: string;
- price?: number;
- unitPrice?: number | null;
- } | null>;
- } | null> | null | undefined,
+ items:
+ | ReadonlyArray<{
+ ean?: string;
+ name?: string;
+ brand?: string | null;
+ imageUrl?: string | null;
+ categoryId?: string | null;
+ prices?: ReadonlyArray<{
+ storeCode?: string;
+ storeName?: string;
+ price?: number;
+ unitPrice?: number | null;
+ } | null>;
+ } | null>
+ | null
+ | undefined,
): SearchProduct[] {
return (items ?? []).flatMap((product) => {
if (
@@ -92,28 +97,30 @@ function normalizeProducts(
return [];
}
- return [{
- storeCode: price.storeCode,
- storeName:
- typeof price.storeName === "string"
- ? price.storeName
- : price.storeCode,
- price: price.price,
- unitPrice:
- typeof price.unitPrice === "number"
- ? price.unitPrice
- : null,
- }];
+ return [
+ {
+ storeCode: price.storeCode,
+ storeName:
+ typeof price.storeName === "string"
+ ? price.storeName
+ : price.storeCode,
+ price: price.price,
+ unitPrice:
+ typeof price.unitPrice === "number" ? price.unitPrice : null,
+ },
+ ];
});
- return [{
- ean: product.ean,
- name: product.name,
- brand: product.brand ?? null,
- imageUrl: product.imageUrl ?? null,
- categoryId: product.categoryId ?? null,
- prices,
- }];
+ return [
+ {
+ ean: product.ean,
+ name: product.name,
+ brand: product.brand ?? null,
+ imageUrl: product.imageUrl ?? null,
+ categoryId: product.categoryId ?? null,
+ prices,
+ },
+ ];
});
}
@@ -130,11 +137,7 @@ export function useSearchResults({
}: UseSearchResultsParams) {
// Hent produkter og antall treff.
// Katalogen skal også fungere uten søkeord eller filtre.
- const {
- data,
- loading,
- error,
- } = useQuery(SEARCH_PRODUCTS_QUERY, {
+ const { data, loading, error } = useQuery(SEARCH_PRODUCTS_QUERY, {
variables: {
search: searchTerm.trim(),
categories: selectedCategories,
@@ -162,13 +165,9 @@ export function useSearchResults({
// Behold forrige filtertall mens nye resultater lastes.
const filterSource = filterData ?? previousFilterData;
- const categoryCounts = normalizeCounts(
- filterSource?.categoryFilterCounts,
- );
+ const categoryCounts = normalizeCounts(filterSource?.categoryFilterCounts);
- const storeCounts = normalizeCounts(
- filterSource?.storeFilterCounts,
- );
+ const storeCounts = normalizeCounts(filterSource?.storeFilterCounts);
// Hent alle kategorinavn for filterbrikker.
const { data: categoryNameData } = useQuery(CATEGORY_NAMES_QUERY);
@@ -187,10 +186,7 @@ export function useSearchResults({
const totalPages = Math.ceil(totalProducts / PAGE_SIZE);
const firstProduct = (currentPage - 1) * PAGE_SIZE + 1;
- const lastProduct = Math.min(
- currentPage * PAGE_SIZE,
- totalProducts,
- );
+ const lastProduct = Math.min(currentPage * PAGE_SIZE, totalProducts);
const hasFilterData = filterSource != null;
diff --git a/frontend/src/pages/SearchResults/hooks/useSearchState.test.tsx b/frontend/src/pages/SearchResults/hooks/useSearchState.test.tsx
index a9dca82..ebd880e 100644
--- a/frontend/src/pages/SearchResults/hooks/useSearchState.test.tsx
+++ b/frontend/src/pages/SearchResults/hooks/useSearchState.test.tsx
@@ -54,15 +54,10 @@ describe("useSearchState", () => {
it("leser flere kategorier fra URL-en", () => {
const { result } = renderHook(() => useSearchState(), {
- wrapper: createWrapper(
- "/search?category=frukt&category=meieri",
- ),
+ wrapper: createWrapper("/search?category=frukt&category=meieri"),
});
- expect(result.current.selectedCategories).toEqual([
- "frukt",
- "meieri",
- ]);
+ expect(result.current.selectedCategories).toEqual(["frukt", "meieri"]);
expect(result.current.selectedStores).toEqual([]);
});
@@ -138,10 +133,7 @@ describe("useSearchState", () => {
});
expect(result.current.selectedCategories).toEqual(["meieri"]);
- expect(result.current.selectedStores).toEqual([
- "KIWI",
- "MENY_NO",
- ]);
+ expect(result.current.selectedStores).toEqual(["KIWI", "MENY_NO"]);
});
it("lagrer oppdaterte søkeinnstillinger i localStorage", async () => {
@@ -166,4 +158,4 @@ describe("useSearchState", () => {
});
});
});
-});
\ No newline at end of file
+});
diff --git a/frontend/src/pages/SearchResults/hooks/useSearchState.ts b/frontend/src/pages/SearchResults/hooks/useSearchState.ts
index ae8eb77..686ddbf 100644
--- a/frontend/src/pages/SearchResults/hooks/useSearchState.ts
+++ b/frontend/src/pages/SearchResults/hooks/useSearchState.ts
@@ -54,11 +54,10 @@ export function useSearchState() {
const searchTerm = urlSearchTerm ?? "";
const urlCategories = searchParams.getAll("category");
- const [preferences, setPreferences] =
- useLocalStorage(
- STORAGE_KEYS.searchPreferences,
- parseSearchPreferences,
- );
+ const [preferences, setPreferences] = useLocalStorage(
+ STORAGE_KEYS.searchPreferences,
+ parseSearchPreferences,
+ );
const [state, setState] = useState(() =>
getInitialSearchState(
@@ -92,9 +91,7 @@ export function useSearchState() {
// Oppdatering av filtre og paginering
// ==========================================
- const updateState = (
- changes: Partial,
- ) => {
+ const updateState = (changes: Partial) => {
setState((previous) => ({
...previous,
...changes,
@@ -105,12 +102,10 @@ export function useSearchState() {
searchTerm,
currentPage: state.currentPage,
- setCurrentPage: (page: number) =>
- updateState({ currentPage: page }),
+ setCurrentPage: (page: number) => updateState({ currentPage: page }),
sort: state.sort,
- setSort: (value: SearchSort) =>
- updateState({ sort: value }),
+ setSort: (value: SearchSort) => updateState({ sort: value }),
selectedCategories: state.selectedCategories,
setSelectedCategories: (values: string[]) =>
diff --git a/frontend/src/pages/SearchResults/searchPreferencesStorage.ts b/frontend/src/pages/SearchResults/searchPreferencesStorage.ts
index ef03f50..6c7df4b 100644
--- a/frontend/src/pages/SearchResults/searchPreferencesStorage.ts
+++ b/frontend/src/pages/SearchResults/searchPreferencesStorage.ts
@@ -1,4 +1,3 @@
-
import type { SearchSort } from "../../types/filters";
import { STORAGE_KEYS } from "../../constants/storageKeys";
@@ -28,9 +27,7 @@ const STORAGE_KEY = STORAGE_KEYS.searchPreferences;
// Validering av lagrede innstillinger
// ==========================================
-export function parseSearchPreferences(
- saved: unknown,
-): SearchPreferences {
+export function parseSearchPreferences(saved: unknown): SearchPreferences {
if (!saved || typeof saved !== "object") {
return { ...defaultSearchPreferences };
}
@@ -38,26 +35,19 @@ export function parseSearchPreferences(
const data = saved as Partial;
return {
- searchTerm:
- typeof data.searchTerm === "string"
- ? data.searchTerm
- : "",
-
- selectedCategories:
- Array.isArray(data.selectedCategories)
- ? data.selectedCategories.filter(
- (value): value is string =>
- typeof value === "string",
- )
- : [],
-
- selectedStores:
- Array.isArray(data.selectedStores)
- ? data.selectedStores.filter(
- (value): value is string =>
- typeof value === "string",
- )
- : [],
+ searchTerm: typeof data.searchTerm === "string" ? data.searchTerm : "",
+
+ selectedCategories: Array.isArray(data.selectedCategories)
+ ? data.selectedCategories.filter(
+ (value): value is string => typeof value === "string",
+ )
+ : [],
+
+ selectedStores: Array.isArray(data.selectedStores)
+ ? data.selectedStores.filter(
+ (value): value is string => typeof value === "string",
+ )
+ : [],
sort:
data.sort === "price_asc" ||
@@ -91,14 +81,9 @@ export function loadSearchPreferences(): SearchPreferences {
}
}
-export function saveSearchPreferences(
- preferences: SearchPreferences,
-): void {
+export function saveSearchPreferences(preferences: SearchPreferences): void {
try {
- localStorage.setItem(
- STORAGE_KEY,
- JSON.stringify(preferences),
- );
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(preferences));
} catch {
// Siden fungerer selv om localStorage ikke er tilgjengelig.
}
diff --git a/frontend/src/pages/SearchResults/searchQueries.ts b/frontend/src/pages/SearchResults/searchQueries.ts
index 148eb88..afc82b3 100644
--- a/frontend/src/pages/SearchResults/searchQueries.ts
+++ b/frontend/src/pages/SearchResults/searchQueries.ts
@@ -106,4 +106,4 @@ export const CATEGORY_NAMES_QUERY: TypedDocumentNode = gql`
name
}
}
-`;
\ No newline at end of file
+`;
diff --git a/frontend/src/pages/productDetails/ProductDetailsPage.tsx b/frontend/src/pages/productDetails/ProductDetailsPage.tsx
index e2525d4..69c23fc 100644
--- a/frontend/src/pages/productDetails/ProductDetailsPage.tsx
+++ b/frontend/src/pages/productDetails/ProductDetailsPage.tsx
@@ -8,14 +8,12 @@ type ProductDetailsPageProps = {
ean: string;
};
-export default function ProductDetailsPage({
- ean,
-}: ProductDetailsPageProps) {
- const { product, loading, error } = useProduct(ean);
- const [quantity, setQuantity] = useState(1);
- const [isInList, setIsInList] = useState(false);
- const [note, setNote] = useState("");
- const [failedImageUrl, setFailedImageUrl] = useState(null);
+export default function ProductDetailsPage({ ean }: ProductDetailsPageProps) {
+ const { product, loading, error } = useProduct(ean);
+ const [quantity, setQuantity] = useState(1);
+ const [isInList, setIsInList] = useState(false);
+ const [note, setNote] = useState("");
+ const [failedImageUrl, setFailedImageUrl] = useState(null);
if (loading) {
return Laster produkt...;
@@ -141,7 +139,7 @@ export default function ProductDetailsPage({
- BILLIGST HOS {cheapest.storeName.toUpperCase()}
+ BILLIGST HOS {cheapest.storeName.toUpperCase()}
>
) : (
@@ -161,17 +159,17 @@ export default function ProductDetailsPage({
{storePrices.map((item, index) => {
const difference = item.price - (cheapest?.price ?? item.price);
- return (
-
- );
- })}
+ return (
+
+ );
+ })}
diff --git a/frontend/src/test/setup.ts b/frontend/src/test/setup.ts
index 8c4286a..25e8ca2 100644
--- a/frontend/src/test/setup.ts
+++ b/frontend/src/test/setup.ts
@@ -5,4 +5,4 @@ import { afterEach } from "vitest";
// Rydder opp mellom tester så de ikke påvirker hverandre.
afterEach(() => {
cleanup();
-});
\ No newline at end of file
+});
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index 63251e8..d5d975d 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -14,4 +14,4 @@ export default defineConfig(({ command }) => ({
globals: true,
css: true,
},
-}));
\ No newline at end of file
+}));