From 21f6e650b858bbebdc8981ebfba79a0968631ae0 Mon Sep 17 00:00:00 2001 From: catjoha04-byte Date: Tue, 17 Nov 2026 14:01:13 +0100 Subject: [PATCH 1/7] feat: add rating as a sort-by option --- Backend/resolvers/GameResolvers.ts | 10 +++++++--- E2E/api/games.api.spec.ts | 6 ++++++ Frontend/src/components/SearchPageControls.tsx | 5 ++++- Frontend/src/pages/SearchPage/SearchPage.tsx | 1 + Frontend/src/tests/SearchPage.test.tsx | 5 +++-- 5 files changed, 21 insertions(+), 6 deletions(-) diff --git a/Backend/resolvers/GameResolvers.ts b/Backend/resolvers/GameResolvers.ts index 143d514..d65c28e 100644 --- a/Backend/resolvers/GameResolvers.ts +++ b/Backend/resolvers/GameResolvers.ts @@ -6,6 +6,7 @@ import { FetchTop10GamesPerGenre, FetchTop3Games } from '../logic/MainPageLogicBackend.ts' +import { REVIEW_SCORE_JOIN } from '../logic/ReviewsLogicBackend.ts' import type { Game } from '../Steam.ts' const NAME_GROUP = `CASE @@ -15,11 +16,12 @@ const NAME_GROUP = `CASE END` const SORT_SQL: Record = { + 'title-asc': `${NAME_GROUP} ASC, LOWER(g.game_name) ASC`, + 'title-desc': `${NAME_GROUP} DESC, LOWER(g.game_name) DESC`, + 'rating-desc': 'rs.review_score DESC NULLS LAST, rs.review_count DESC NULLS LAST', 'discount-desc': 'g.discount_percent DESC NULLS LAST', 'price-asc': 'g.current_price ASC NULLS LAST', - 'price-desc': 'g.current_price DESC NULLS LAST', - 'title-asc': `${NAME_GROUP} ASC, LOWER(g.game_name) ASC`, - 'title-desc': `${NAME_GROUP} DESC, LOWER(g.game_name) DESC` + 'price-desc': 'g.current_price DESC NULLS LAST' } function BuildGameFilter(search?: string | null, genres?: string[] | null, withRank = false) { @@ -91,10 +93,12 @@ export const gameQueryResolvers = { const { where, params, rank } = BuildGameFilter(search, genres, true) const orderBy = [SORT_SQL[sort ?? ''], rank, 'g.game_id'].filter(Boolean).join(', ') + const join = sort === 'rating-desc' ? REVIEW_SCORE_JOIN : '' const { rows } = await pool.query( `SELECT ${GAME_COLUMNS} FROM games g + ${join} ${where} ORDER BY ${orderBy} LIMIT $${params.length + 1} OFFSET $${params.length + 2}`, diff --git a/E2E/api/games.api.spec.ts b/E2E/api/games.api.spec.ts index 94e0240..cee4e32 100644 --- a/E2E/api/games.api.spec.ts +++ b/E2E/api/games.api.spec.ts @@ -86,6 +86,12 @@ test.describe('games', () => { expect(names).toEqual([...names].sort((a, b) => a.localeCompare(b, 'en'))) }) + test('sort rating-desc returns games without errors', async ({ request }) => { + const { data, errors } = await Gql<{ games: Game[] }>(request, GAMES, { l: 10, sort: 'rating-desc' }) + expect(errors).toBeUndefined() + expect(data!.games).toHaveLength(10) + }) + test('an unknown sort value is ignored, not an error', async ({ request }) => { const { data, errors } = await Gql<{ games: Game[] }>(request, GAMES, { l: 3, sort: 'nonsense' }) expect(errors).toBeUndefined() diff --git a/Frontend/src/components/SearchPageControls.tsx b/Frontend/src/components/SearchPageControls.tsx index 586b2c0..a01cd41 100644 --- a/Frontend/src/components/SearchPageControls.tsx +++ b/Frontend/src/components/SearchPageControls.tsx @@ -12,7 +12,7 @@ import type { SelectChangeEvent } from '@mui/material' import { Funnel, X } from 'lucide-react' export type SortOption = - '' | 'discount-desc' | 'price-asc' | 'price-desc' | 'title-asc' | 'title-desc' + '' | 'title-asc' | 'title-desc' | 'rating-desc' | 'discount-desc' | 'price-asc' | 'price-desc' interface SearchPageControlsProps { searchValue: string @@ -98,6 +98,9 @@ export default function SearchPageControls({ Title: Z to A + + Rating: high to low + Discount: high to low diff --git a/Frontend/src/pages/SearchPage/SearchPage.tsx b/Frontend/src/pages/SearchPage/SearchPage.tsx index feebcb5..dfeea06 100644 --- a/Frontend/src/pages/SearchPage/SearchPage.tsx +++ b/Frontend/src/pages/SearchPage/SearchPage.tsx @@ -26,6 +26,7 @@ const DEFAULT_SORT: SortOption = 'title-asc' const SORT_OPTIONS: SortOption[] = [ 'title-asc', 'title-desc', + 'rating-desc', 'discount-desc', 'price-asc', 'price-desc' diff --git a/Frontend/src/tests/SearchPage.test.tsx b/Frontend/src/tests/SearchPage.test.tsx index 773495e..8c9c7dc 100644 --- a/Frontend/src/tests/SearchPage.test.tsx +++ b/Frontend/src/tests/SearchPage.test.tsx @@ -426,9 +426,10 @@ describe('SearchPage', () => { it.each([ ['Title: Z to A', 'title-desc'], + ['Rating: high to low', 'rating-desc'], + ['Discount: high to low', 'discount-desc'], ['Price: low to high', 'price-asc'], - ['Price: high to low', 'price-desc'], - ['Discount: high to low', 'discount-desc'] + ['Price: high to low', 'price-desc'] ])('sends the "%s" sort to the backend as %s', async (label, sort) => { await RenderWithNamedGames() From 501ab2d9cdfe26d1c1eb82c0a3b8a46ebe1920ca Mon Sep 17 00:00:00 2001 From: catjoha04-byte Date: Thu, 19 Nov 2026 22:34:43 +0100 Subject: [PATCH 2/7] refactor: replace searchpage useEffects with hook --- Frontend/src/hooks/useSaveSearchPageState.ts | 32 +++++++++++ .../src/tests/useSaveSearchPageState.test.ts | 55 +++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 Frontend/src/hooks/useSaveSearchPageState.ts create mode 100644 Frontend/src/tests/useSaveSearchPageState.test.ts diff --git a/Frontend/src/hooks/useSaveSearchPageState.ts b/Frontend/src/hooks/useSaveSearchPageState.ts new file mode 100644 index 0000000..7c4c13f --- /dev/null +++ b/Frontend/src/hooks/useSaveSearchPageState.ts @@ -0,0 +1,32 @@ +import { useEffect } from 'react' +import { + SaveFilterMenuOpenSearchpage, + SaveFiltersSearchpage, + SavePageSearchpage, + SaveQuerySearchpage, + SaveSortOptionSearchpage +} from '../FrontendLogic/SearchPageLogicFrontend' + +interface SearchPageState { + page: number + filters: string[] + sort: string + query: string + isFilterMenuOpen: boolean +} + +export function useSaveSearchPageState({ + page, + filters, + sort, + query, + isFilterMenuOpen +}: SearchPageState) { + useEffect(() => { + SavePageSearchpage(page) + SaveFiltersSearchpage(filters) + SaveSortOptionSearchpage(sort) + SaveQuerySearchpage(query) + SaveFilterMenuOpenSearchpage(isFilterMenuOpen) + }, [page, filters, sort, query, isFilterMenuOpen]) +} diff --git a/Frontend/src/tests/useSaveSearchPageState.test.ts b/Frontend/src/tests/useSaveSearchPageState.test.ts new file mode 100644 index 0000000..1021f4f --- /dev/null +++ b/Frontend/src/tests/useSaveSearchPageState.test.ts @@ -0,0 +1,55 @@ +// @vitest-environment jsdom +import { renderHook } from '@testing-library/react' +import { beforeEach, describe, expect, it } from 'vitest' +import { useSaveSearchPageState } from '../hooks/useSaveSearchPageState' +import { + GetFilterMenuOpenSearchpage, + GetPageSearchpage, + GetQuerySearchpage, + GetSavedFiltersSearchpage, + GetSortOptionSearchpage +} from '../FrontendLogic/SearchPageLogicFrontend' + +const initialState = { + page: 2, + filters: ['Action'], + sort: 'price-asc', + query: 'portal', + isFilterMenuOpen: true +} + +describe('useSaveSearchPageState', () => { + beforeEach(() => { + sessionStorage.clear() + }) + + it('saves every part of the search page state on mount', () => { + renderHook(() => useSaveSearchPageState(initialState)) + + expect(GetPageSearchpage()).toBe(2) + expect(GetSavedFiltersSearchpage()).toEqual(['Action']) + expect(GetSortOptionSearchpage()).toBe('price-asc') + expect(GetQuerySearchpage()).toBe('portal') + expect(GetFilterMenuOpenSearchpage()).toBe(true) + }) + + it('saves the new values when the state changes', () => { + const { rerender } = renderHook((state) => useSaveSearchPageState(state), { + initialProps: initialState + }) + + rerender({ + page: 1, + filters: [], + sort: 'rating-desc', + query: '', + isFilterMenuOpen: false + }) + + expect(GetPageSearchpage()).toBe(1) + expect(GetSavedFiltersSearchpage()).toEqual([]) + expect(GetSortOptionSearchpage()).toBe('rating-desc') + expect(GetQuerySearchpage()).toBe('') + expect(GetFilterMenuOpenSearchpage()).toBe(false) + }) +}) From 2d6d0ea4dd7d00e61508c76ae389bcd047866ce8 Mon Sep 17 00:00:00 2001 From: catjoha04-byte Date: Thu, 19 Nov 2026 22:53:08 +0100 Subject: [PATCH 3/7] refactor: use hook in SearchPage --- Frontend/src/pages/SearchPage/SearchPage.tsx | 34 ++++++-------------- 1 file changed, 9 insertions(+), 25 deletions(-) diff --git a/Frontend/src/pages/SearchPage/SearchPage.tsx b/Frontend/src/pages/SearchPage/SearchPage.tsx index dfeea06..fd4abc8 100644 --- a/Frontend/src/pages/SearchPage/SearchPage.tsx +++ b/Frontend/src/pages/SearchPage/SearchPage.tsx @@ -7,18 +7,14 @@ import SearchPageControls, { type SortOption } from '../../components/SearchPage import SearchPageResults from '../../components/SearchPageResults' import { useDebouncedValue } from '../../hooks/useDebouncedValue' import { useSearchPageResults } from '../../hooks/useSearchPageResults' -import { useState, useEffect } from 'react' +import { useSaveSearchPageState } from '../../hooks/useSaveSearchPageState' +import { useState } from 'react' import type { SelectChangeEvent } from '@mui/material' import { GetSavedFiltersSearchpage, - SaveFiltersSearchpage, GetQuerySearchpage, - SaveQuerySearchpage, GetSortOptionSearchpage, - SaveSortOptionSearchpage, GetPageSearchpage, - SavePageSearchpage, - SaveFilterMenuOpenSearchpage, GetFilterMenuOpenSearchpage } from '../../FrontendLogic/SearchPageLogicFrontend' @@ -94,25 +90,13 @@ export function SearchPage() { setPage(1) } - useEffect(() => { - SaveFilterMenuOpenSearchpage(isFilterActive) - }, [isFilterActive]) - - useEffect(() => { - SaveFiltersSearchpage(activeFilters) - }, [activeFilters]) - - useEffect(() => { - SaveSortOptionSearchpage(activeSorting) - }, [activeSorting]) - - useEffect(() => { - SaveQuerySearchpage(searchQuery) - }, [searchQuery]) - - useEffect(() => { - SavePageSearchpage(page) - }, [page]) + useSaveSearchPageState({ + page, + filters: activeFilters, + sort: activeSorting, + query: searchQuery, + isFilterMenuOpen: isFilterActive + }) return (
From 8195504e33a36fd50fbcd6ae463b35b15f21d822 Mon Sep 17 00:00:00 2001 From: catjoha04-byte Date: Thu, 19 Nov 2026 22:54:04 +0100 Subject: [PATCH 4/7] feat: add amount of games found from search to screen readers --- Frontend/src/components/SearchPageResults.tsx | 18 +++++++++--------- Frontend/src/tests/SearchPage.test.tsx | 12 ++++++++++++ 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/Frontend/src/components/SearchPageResults.tsx b/Frontend/src/components/SearchPageResults.tsx index e0aebe7..c72096d 100644 --- a/Frontend/src/components/SearchPageResults.tsx +++ b/Frontend/src/components/SearchPageResults.tsx @@ -1,9 +1,9 @@ import { memo } from 'react' import { Pagination } from '@mui/material' -import type { Game } from '../../../Backend/Steam' +import type { GameSummary } from '../types/Game' import PassiveGameCard from './PassiveGameCard/PassiveGameCard' -const SearchResultsGrid = memo(function SearchResultsGrid({ games }: { games: Game[] }) { +const SearchResultsGrid = memo(function SearchResultsGrid({ games }: { games: GameSummary[] }) { return (
{games.map((game) => { @@ -28,7 +28,7 @@ const SearchResultsGrid = memo(function SearchResultsGrid({ games }: { games: Ga }) interface SearchPageResultsProps { - games: Game[] + games: GameSummary[] error: string | null isLoading: boolean totalCount: number @@ -56,11 +56,11 @@ export default function SearchPageResults({ return ( <>
- {!error && totalCount > 0 && ( -

- {totalCount} {totalCount === 1 ? 'game' : 'games'} found -

- )} +

+ {!error && totalCount > 0 + ? `${totalCount} ${totalCount === 1 ? 'game' : 'games'} found` + : ''} +

Loading games...

} {!error && !isLoading && games.length === 0 && ( -

No games found.

+

No games found.

)} {games.length > 0 && } { expect(screen.getAllByText('9.99')).toHaveLength(12) }) + it('announces the number of games found to screen readers', async () => { + FetchGamesFromDB.mockResolvedValue([MakeGame(1), MakeGame(2), MakeGame(3)]) + + RenderSearchPage() + + const status = screen + .getAllByRole('status') + .find((element) => element.classList.contains('gamesFound')) + expect(status?.getAttribute('aria-live')).toBe('polite') + await waitFor(() => expect(status?.textContent).toBe('3 games found')) + }) + it('shows an empty state when no games are returned', async () => { FetchGamesFromDB.mockResolvedValue([]) From 14370fca3d105a47c8cb1aa1ab8e0156e101ff92 Mon Sep 17 00:00:00 2001 From: catjoha04-byte Date: Thu, 19 Nov 2026 23:04:17 +0100 Subject: [PATCH 5/7] refactor: stop fetching game description for passive cards --- .../src/FrontendLogic/GameLogicFrontend.ts | 49 ++++++------------- .../FrontendLogic/MainPageLogicFrontend.ts | 19 ++++--- Frontend/src/components/GenreGamesSection.tsx | 6 +-- Frontend/src/hooks/useSearchPageResults.ts | 11 ++--- Frontend/src/tests/GameLogicFrontend.test.ts | 35 +++++++++---- Frontend/src/types/Game.ts | 2 + 6 files changed, 62 insertions(+), 60 deletions(-) diff --git a/Frontend/src/FrontendLogic/GameLogicFrontend.ts b/Frontend/src/FrontendLogic/GameLogicFrontend.ts index 64e557f..658e210 100644 --- a/Frontend/src/FrontendLogic/GameLogicFrontend.ts +++ b/Frontend/src/FrontendLogic/GameLogicFrontend.ts @@ -1,4 +1,4 @@ -import type { Game } from '../types/Game' +import type { Game, GameSummary } from '../types/Game' import { BACKEND_URL, NETWORK_ERROR_MESSAGE } from './LogicConnection' import { OrNull, ReadStored, RemoveStored, WriteStored } from './Storage' @@ -20,10 +20,10 @@ const GAMES_CACHE_PREFIX = `games:v2:${encodeURIComponent(BACKEND_URL)}:` interface CachedGames { fetchedAt: number - games: Game[] + games: GameSummary[] } -function IsGame(value: unknown): value is Game { +function IsGameSummary(value: unknown): value is GameSummary { if (typeof value !== 'object' || value === null) return false const game = value as Record @@ -34,11 +34,14 @@ function IsGame(value: unknown): value is Game { typeof game.initialprice === 'string' && typeof game.discount === 'string' && typeof game.img === 'string' && - typeof game.genre === 'string' && - typeof game.description === 'string' + typeof game.genre === 'string' ) } +function IsGame(value: unknown): value is Game { + return IsGameSummary(value) && typeof (value as Game).description === 'string' +} + function IsCachedGames(value: unknown): value is CachedGames { if (typeof value !== 'object' || value === null) return false @@ -46,7 +49,7 @@ function IsCachedGames(value: unknown): value is CachedGames { return ( typeof cache.fetchedAt === 'number' && Array.isArray(cache.games) && - cache.games.every(IsGame) + cache.games.every(IsGameSummary) ) } @@ -66,12 +69,12 @@ function GameByIdCacheKey(appid: number): string { return `game:v1:${appid}` } -function ReadCachedGames(key: string): Game[] | null { +function ReadCachedGames(key: string): GameSummary[] | null { const cache = ReadStored(key, null, OrNull(IsCachedGames), 'local') if (!cache) return null - const age = Date.now() - (IsCachedGames(cache) ? cache.fetchedAt : 0) - if (IsCachedGames(cache) && age >= 0 && age < CACHE_TTL_MS) { + const age = Date.now() - cache.fetchedAt + if (age >= 0 && age < CACHE_TTL_MS) { return cache.games } @@ -79,7 +82,7 @@ function ReadCachedGames(key: string): Game[] | null { return null } -function WriteCachedGames(key: string, games: Game[]): void { +function WriteCachedGames(key: string, games: GameSummary[]): void { WriteStored(key, { fetchedAt: Date.now(), games } satisfies CachedGames, 'local') } @@ -87,26 +90,7 @@ function FindCachedGameById(appid: number): Game | null { const cachedGame = ReadCachedGames(GameByIdCacheKey(appid))?.find( (game) => game.appid === appid ) - if (cachedGame) return cachedGame - - try { - const storage = globalThis.localStorage - if (!storage) return null - - // Collect keys first because readCachedGames may remove expired entries. - const cacheKeys = Array.from({ length: storage.length }, (_, index) => - storage.key(index) - ).filter((key): key is string => key !== null && key.startsWith(GAMES_CACHE_PREFIX)) - - for (const key of cacheKeys) { - const game = ReadCachedGames(key)?.find((candidate) => candidate.appid === appid) - if (game) return game - } - } catch (error) { - console.warn('Unable to search localStorage; fetching game from the database.', error) - } - - return null + return cachedGame && IsGame(cachedGame) ? cachedGame : null } export async function GetGameById(appid: number): Promise { @@ -153,7 +137,7 @@ async function FetchGamesFromDB( limit: number, offset: number, options: GameQueryOptions = {} -): Promise { +): Promise { const cacheKey = GamesCacheKey(limit, offset, options) const cachedGames = ReadCachedGames(cacheKey) if (cachedGames) return cachedGames @@ -172,7 +156,6 @@ async function FetchGamesFromDB( discount img genre - description } } `, @@ -191,7 +174,7 @@ async function FetchGamesFromDB( } const { data, errors } = (await response.json()) as GraphQLResponse<{ - games: Game[] + games: GameSummary[] }> if (errors?.length) throw new Error(errors[0].message) if (!data) throw new Error('No data returned') diff --git a/Frontend/src/FrontendLogic/MainPageLogicFrontend.ts b/Frontend/src/FrontendLogic/MainPageLogicFrontend.ts index e72c8cd..c5449a6 100644 --- a/Frontend/src/FrontendLogic/MainPageLogicFrontend.ts +++ b/Frontend/src/FrontendLogic/MainPageLogicFrontend.ts @@ -1,10 +1,10 @@ import { Gql } from './LogicConnection' -import { type Game } from '../types/Game' +import { type GameSummary } from '../types/Game' import { IsBoolean, IsInteger, IsString, ReadStored, WriteStored } from '../FrontendLogic/Storage' export type MainPageGenreSection = 'top10' | 'discounts' -const GAME_FIELDS = `appid name price initialprice discount img genre description` +const GAME_FIELDS = `appid name price initialprice discount img genre` const DISCOUNT_ONLY_KEY = 'GameStart:discountedOnlySearchpage' const RECENT_REVIEW_KEY = 'GameStart:recentReviewCountMainpage' const DEFAULT_REVIEW_COUNT = 3 @@ -68,21 +68,24 @@ export function PrepareDiscountGenreSearch(genre: string) { } } -export async function LoadTop3Games(): Promise { - const data = await Gql<{ top3Games: Game[] }>(`query { top3Games { ${GAME_FIELDS} } }`, {}) +export async function LoadTop3Games(): Promise { + const data = await Gql<{ top3Games: GameSummary[] }>( + `query { top3Games { ${GAME_FIELDS} } }`, + {} + ) return data.top3Games } -export async function LoadTopGamesByGenre(genre: string): Promise { - const data = await Gql<{ topGamesByGenre: Game[] }>( +export async function LoadTopGamesByGenre(genre: string): Promise { + const data = await Gql<{ topGamesByGenre: GameSummary[] }>( `query ($genre: String!) { topGamesByGenre(genre: $genre) { ${GAME_FIELDS} } }`, { genre } ) return data.topGamesByGenre } -export async function LoadDiscountedGames(genre: string): Promise { - const data = await Gql<{ discountedGames: Game[] }>( +export async function LoadDiscountedGames(genre: string): Promise { + const data = await Gql<{ discountedGames: GameSummary[] }>( `query ($genre: String!) { discountedGames(genre: $genre) { ${GAME_FIELDS} } }`, { genre } ) diff --git a/Frontend/src/components/GenreGamesSection.tsx b/Frontend/src/components/GenreGamesSection.tsx index a369524..24085d0 100644 --- a/Frontend/src/components/GenreGamesSection.tsx +++ b/Frontend/src/components/GenreGamesSection.tsx @@ -1,4 +1,4 @@ -import { type Game } from '../types/Game' +import { type GameSummary } from '../types/Game' import { GetSavedMainPageGenre, SaveMainPageGenre, @@ -13,7 +13,7 @@ import { Link } from 'react-router-dom' const NO_GAMES: PageGame[] = [] -export function ToPageGame(game: Game): PageGame { +export function ToPageGame(game: GameSummary): PageGame { const price = Number(game.price) const salePercent = Number(game.discount) const genres = @@ -39,7 +39,7 @@ type GenreGamesSectionProps = { genres: string[] genresLoading: boolean genresError?: string | null - loadGames: (genre: string) => Promise + loadGames: (genre: string) => Promise loadingText: string emptyText: string showSeeMore?: boolean diff --git a/Frontend/src/hooks/useSearchPageResults.ts b/Frontend/src/hooks/useSearchPageResults.ts index 4fbe40f..de3a183 100644 --- a/Frontend/src/hooks/useSearchPageResults.ts +++ b/Frontend/src/hooks/useSearchPageResults.ts @@ -1,10 +1,10 @@ import { useEffect, useMemo, useState } from 'react' -import type { Game } from '../../../Backend/Steam' +import type { GameSummary } from '../types/Game' import FetchGamesFromDB, { GetTotalGameCount } from '../FrontendLogic/GameLogicFrontend' import { FetchGenres } from '../FrontendLogic/SearchPageLogicFrontend' const GAMES_PER_PAGE = 12 -const NO_GAMES: Game[] = [] +const NO_GAMES: GameSummary[] = [] interface SearchPageResultsOptions { page: number @@ -15,11 +15,11 @@ interface SearchPageResultsOptions { interface SearchPageResult { key: string - games: Game[] + games: GameSummary[] error: string | null } -function AreGamesEqual(first: Game[], second: Game[]): boolean { +function AreGamesEqual(first: GameSummary[], second: GameSummary[]): boolean { return ( first.length === second.length && first.every((game, index) => { @@ -31,8 +31,7 @@ function AreGamesEqual(first: Game[], second: Game[]): boolean { game.initialprice === other.initialprice && game.discount === other.discount && game.img === other.img && - game.genre === other.genre && - game.description === other.description + game.genre === other.genre ) }) ) diff --git a/Frontend/src/tests/GameLogicFrontend.test.ts b/Frontend/src/tests/GameLogicFrontend.test.ts index 919fd67..e26cb91 100644 --- a/Frontend/src/tests/GameLogicFrontend.test.ts +++ b/Frontend/src/tests/GameLogicFrontend.test.ts @@ -38,7 +38,7 @@ function FirstRequestBody() { return RequestBody((global.fetch as ReturnType).mock.calls[0]) } -const game: Game = { +const fullGame: Game = { appid: 10, name: 'Counter-Strike', price: '9.99', @@ -49,6 +49,8 @@ const game: Game = { description: 'A classic shooter.' } +const { description: _description, ...game } = fullGame + describe('fetchGamesFromDB', () => { beforeEach(() => { vi.restoreAllMocks() @@ -60,6 +62,7 @@ describe('fetchGamesFromDB', () => { const result = await FetchGamesFromDB(1, 0) + expect(FirstRequestBody().query).not.toContain('description') expect(global.fetch).toHaveBeenCalledWith( BACKEND_URL, expect.objectContaining({ method: 'POST' }) @@ -178,35 +181,47 @@ describe('fetchGamesFromDB', () => { }) it('returns a game from an existing page cache without fetching', async () => { + const values = new Map([ + ['game:v1:10', JSON.stringify({ fetchedAt: Date.now(), games: [fullGame] })] + ]) + StubLocalStorage(values) + global.fetch = vi.fn() + + await expect(GetGameById(fullGame.appid)).resolves.toEqual(fullGame) + expect(global.fetch).not.toHaveBeenCalled() + }) + + it('fetches the game instead of using a cached search page, which has no description', async () => { const values = new Map([ [ - `${GAMES_CACHE_PREFIX}500:0:::`, + `${GAMES_CACHE_PREFIX}12:0:::`, JSON.stringify({ fetchedAt: Date.now(), games: [game] }) ] ]) StubLocalStorage(values) - global.fetch = vi.fn() + global.fetch = vi.fn().mockResolvedValue(MockResponse({ data: { game: fullGame } })) - await expect(GetGameById(game.appid)).resolves.toEqual(game) - expect(global.fetch).not.toHaveBeenCalled() + await expect(GetGameById(fullGame.appid)).resolves.toEqual(fullGame) + expect(global.fetch).toHaveBeenCalledTimes(1) + expect(FirstRequestBody().query).toContain('description') }) it('fetches a missing game from the database and caches it for subsequent calls', async () => { const values = new Map() StubLocalStorage(values) - global.fetch = vi.fn().mockResolvedValue(MockResponse({ data: { game } })) + global.fetch = vi.fn().mockResolvedValue(MockResponse({ data: { game: fullGame } })) - await expect(GetGameById(game.appid)).resolves.toEqual(game) + await expect(GetGameById(fullGame.appid)).resolves.toEqual(fullGame) expect(global.fetch).toHaveBeenCalledTimes(1) const body = FirstRequestBody() - expect(body.variables).toEqual({ appid: game.appid }) + expect(body.variables).toEqual({ appid: fullGame.appid }) expect(body.query).toContain('game(appid: $appid)') expect(JSON.parse(values.get('game:v1:10') ?? '{}')).toEqual({ fetchedAt: expect.any(Number), - games: [game] + games: [fullGame] }) - await expect(GetGameById(game.appid)).resolves.toEqual(game) + await expect(GetGameById(fullGame.appid)).resolves.toEqual(fullGame) expect(global.fetch).toHaveBeenCalledTimes(1) }) diff --git a/Frontend/src/types/Game.ts b/Frontend/src/types/Game.ts index 7cd468e..b82ae17 100644 --- a/Frontend/src/types/Game.ts +++ b/Frontend/src/types/Game.ts @@ -21,6 +21,8 @@ export interface Game { description: string } +export type GameSummary = Omit + export type PageGame = { id: number name: string From 8c8d575047767f4de5637184c24ae8502fc904f0 Mon Sep 17 00:00:00 2001 From: catjoha04-byte Date: Thu, 19 Nov 2026 23:16:17 +0100 Subject: [PATCH 6/7] refactor: stop fetching description on wishlist and friend pages --- Frontend/src/FrontendLogic/FriendLogicFrontend.ts | 8 ++++---- Frontend/src/FrontendLogic/WishlistLogicFrontend.ts | 8 ++++---- Frontend/src/pages/FriendsPage/FriendsPage.tsx | 6 +++--- Frontend/src/pages/WishlistPage/WishlistPage.tsx | 4 ++-- Frontend/src/tests/WishlistPage.test.tsx | 7 +++---- 5 files changed, 16 insertions(+), 17 deletions(-) diff --git a/Frontend/src/FrontendLogic/FriendLogicFrontend.ts b/Frontend/src/FrontendLogic/FriendLogicFrontend.ts index 1827196..1560760 100644 --- a/Frontend/src/FrontendLogic/FriendLogicFrontend.ts +++ b/Frontend/src/FrontendLogic/FriendLogicFrontend.ts @@ -1,5 +1,5 @@ import { Gql } from './LogicConnection' -import type { Game } from '../types/Game' +import type { GameSummary } from '../types/Game' export interface Friend { id: number @@ -10,7 +10,7 @@ export interface Friend { } const FRIEND_FIELDS = 'id username description setup favouriteGame { name img }' -const GAME_FIELDS = 'appid name price initialprice discount img genre description' +const GAME_FIELDS = 'appid name price initialprice discount img genre' export async function GetFriends(userId: number): Promise { const data = await Gql<{ friends: Friend[] }>( @@ -33,8 +33,8 @@ export async function AddFriend(userId: number, friendCode: string): Promise { - const data = await Gql<{ friendWishlist: Game[] }>( +export async function GetFriendWishlist(userId: number, friendId: number): Promise { + const data = await Gql<{ friendWishlist: GameSummary[] }>( `query($userId: Int!, $friendId: Int!) { friendWishlist(userId: $userId, friendId: $friendId) { ${GAME_FIELDS} } }`, diff --git a/Frontend/src/FrontendLogic/WishlistLogicFrontend.ts b/Frontend/src/FrontendLogic/WishlistLogicFrontend.ts index 724e4bf..d7d0c25 100644 --- a/Frontend/src/FrontendLogic/WishlistLogicFrontend.ts +++ b/Frontend/src/FrontendLogic/WishlistLogicFrontend.ts @@ -1,15 +1,15 @@ -import { type Game } from '../types/Game' +import { type GameSummary } from '../types/Game' import { Gql } from './LogicConnection' import { IsString, ReadStored, WriteStored } from './Storage' const WISHLIST_KEY = 'GameStart:sortOptionWishlist' // Frontend function for calling backend to fetch wishlisted games of a user -export async function FetchWishlistFrontend(userId: number | null): Promise { - const data = await Gql<{ wishlist: Game[] }>( +export async function FetchWishlistFrontend(userId: number | null): Promise { + const data = await Gql<{ wishlist: GameSummary[] }>( `query($userId: Int!) { wishlist(userId: $userId) { - appid name price initialprice discount img genre description + appid name price initialprice discount img genre } }`, { userId } diff --git a/Frontend/src/pages/FriendsPage/FriendsPage.tsx b/Frontend/src/pages/FriendsPage/FriendsPage.tsx index fcab0af..23a029e 100644 --- a/Frontend/src/pages/FriendsPage/FriendsPage.tsx +++ b/Frontend/src/pages/FriendsPage/FriendsPage.tsx @@ -15,7 +15,7 @@ import { useEffect, useMemo, useState } from 'react' import { useDocumentTitle } from '../../hooks/useDocumentTitle.ts' import './FriendsPage.css' import WishlistGameCard from '../../components/WishlistGameCard/WishlistGameCard' -import type { Game } from '../../../../Backend/Steam' +import type { GameSummary } from '../../types/Game' import { AddFriend, GetFriends, @@ -29,7 +29,7 @@ import type { Profile } from '../../../../Backend/logic/ProfileLogicBackend' import type { GameOption } from '../../FrontendLogic/ProfileLogicFrontend' const GAMES_PER_PAGE = 5 -const NO_GAMES: Game[] = [] +const NO_GAMES: GameSummary[] = [] const errorMessage = (err: unknown, fallback: string) => err instanceof Error ? err.message : fallback @@ -63,7 +63,7 @@ export default function FriendPage() { ) const [wishlistState, setWishlistState] = useState<{ key: string | null - games: Game[] + games: GameSummary[] error: string | null }>({ key: null, games: [], error: null }) diff --git a/Frontend/src/pages/WishlistPage/WishlistPage.tsx b/Frontend/src/pages/WishlistPage/WishlistPage.tsx index b19ac99..8cdf40b 100644 --- a/Frontend/src/pages/WishlistPage/WishlistPage.tsx +++ b/Frontend/src/pages/WishlistPage/WishlistPage.tsx @@ -6,7 +6,7 @@ import WishlistGameCard from '../../components/WishlistGameCard/WishlistGameCard import { FormControl, Select, MenuItem, InputLabel, Pagination, Card } from '@mui/material' import type { SelectChangeEvent } from '@mui/material' import { useState, useEffect, useMemo } from 'react' -import type { Game } from '../../../../Backend/Steam' +import type { GameSummary } from '../../types/Game' import PageHeading from '../../components/PageHeading/PageHeading' import { @@ -34,7 +34,7 @@ export default function WishlistPage() { const { user } = UseAuth() const [wishlistState, setWishlistState] = useState<{ user: typeof user - games: Game[] + games: GameSummary[] error: string | null }>({ user: null, games: [], error: null }) const [page, setPage] = useState(1) diff --git a/Frontend/src/tests/WishlistPage.test.tsx b/Frontend/src/tests/WishlistPage.test.tsx index 9ed7c97..dbc92d2 100644 --- a/Frontend/src/tests/WishlistPage.test.tsx +++ b/Frontend/src/tests/WishlistPage.test.tsx @@ -34,8 +34,7 @@ const sampleGame = { initialprice: '0', discount: '0', img: 'https://example.com/dota.jpg', - genre: 'Action', - description: 'A game' + genre: 'Action' } describe('wishlistLogicFrontend', () => { @@ -78,11 +77,11 @@ describe('wishlistLogicFrontend', () => { 'initialprice', 'discount', 'img', - 'genre', - 'description' + 'genre' ]) { expect(query).toContain(field) } + expect(query).not.toContain('description') expect(variables).toEqual({ userId: 9 }) }) From 3098e9c946f82ae4bc6b18e67d39ba933ea44a1e Mon Sep 17 00:00:00 2001 From: catjoha04-byte Date: Thu, 19 Nov 2026 23:32:31 +0100 Subject: [PATCH 7/7] test: add Reviews test Added Reviews test with above 80% line test coverage (Reviews had only 22% coverage prior to adding this test file) --- Frontend/src/tests/Reviews.test.tsx | 229 ++++++++++++++++++++++++++++ 1 file changed, 229 insertions(+) create mode 100644 Frontend/src/tests/Reviews.test.tsx diff --git a/Frontend/src/tests/Reviews.test.tsx b/Frontend/src/tests/Reviews.test.tsx new file mode 100644 index 0000000..b0c3dc9 --- /dev/null +++ b/Frontend/src/tests/Reviews.test.tsx @@ -0,0 +1,229 @@ +// @vitest-environment jsdom +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import Reviews from '../components/Reviews/Reviews' +import type { Review } from '../types/Review' + +const CURRENT_USER_ID = 7 + +const ownReview: Review = { + id: 1, + gameId: 10, + userId: CURRENT_USER_ID, + reviewer: 'Me', + rating: 4, + text: 'My own review' +} + +const otherReview: Review = { + id: 2, + gameId: 10, + userId: 99, + reviewer: 'Someone', + rating: 5, + text: 'Someone else' +} + +function RenderReviews(props: Partial[0]> = {}) { + const callbacks = { + onSubmitReview: vi.fn<(rating: number, text: string) => Promise>(), + onEditReview: vi.fn<(reviewId: number, rating: number, text: string) => Promise>(), + onDeleteReview: vi.fn<(reviewId: number) => Promise>() + } + callbacks.onSubmitReview.mockResolvedValue(undefined) + callbacks.onEditReview.mockResolvedValue(undefined) + callbacks.onDeleteReview.mockResolvedValue(undefined) + + render() + return callbacks +} + +function PickRating(value: number) { + fireEvent.click(screen.getByRole('radio', { name: `Rating ${value} out of 5` })) +} + +describe('Reviews', () => { + afterEach(() => { + cleanup() + }) + + describe('rating and list', () => { + it('shows "--" and an empty state when there are no reviews', () => { + RenderReviews() + + expect(screen.getByText('Rating: -- / 5')).toBeTruthy() + expect(screen.getByText('No reviews yet.')).toBeTruthy() + }) + + it('shows the average rating rounded to one decimal', () => { + RenderReviews({ + reviews: [ + { ...otherReview, id: 3, rating: 5 }, + { ...otherReview, id: 4, rating: 4 }, + { ...otherReview, id: 5, rating: 4 } + ] + }) + + // (5 + 4 + 4) / 3 = 4.33..., shown as 4.3 + expect(screen.getByText('Rating: 4.3 / 5')).toBeTruthy() + }) + + it('shows a whole number average without decimals', () => { + RenderReviews({ reviews: [ownReview, { ...otherReview, rating: 4 }] }) + + expect(screen.getByText('Rating: 4 / 5')).toBeTruthy() + }) + + it('renders a card for every review', () => { + RenderReviews({ reviews: [ownReview, otherReview] }) + + const list = screen.getByRole('group', { name: 'Game reviews' }) + expect(list.querySelectorAll('.reviewCard')).toHaveLength(2) + expect(screen.getByText('“Someone else”')).toBeTruthy() + }) + + it('shows the load error instead of the empty state', () => { + RenderReviews({ loadError: 'Server down' }) + + expect(screen.getByRole('alert').textContent).toBe( + 'Could not load reviews: Server down' + ) + expect(screen.queryByText('No reviews yet.')).toBeNull() + }) + }) + + describe('signed out', () => { + it('disables writing a review and explains why', () => { + RenderReviews({ currentUserId: null }) + + const writeButton = screen.getByRole('button', { name: 'Write Review' }) + expect((writeButton as HTMLButtonElement).disabled).toBe(true) + expect(screen.getByText('Sign in to submit a review.')).toBeTruthy() + }) + }) + + describe('writing a review', () => { + it('opens and closes the review form', () => { + RenderReviews() + + fireEvent.click(screen.getByRole('button', { name: 'Write Review' })) + expect(screen.getByText('Write your review')).toBeTruthy() + + fireEvent.click(screen.getByRole('button', { name: 'Close Review Form' })) + expect(screen.queryByText('Write your review')).toBeNull() + }) + + it('closes the form with the cancel button', () => { + RenderReviews() + + fireEvent.click(screen.getByRole('button', { name: 'Write Review' })) + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) + + expect(screen.queryByText('Write your review')).toBeNull() + }) + + it('submits a new review and closes the form', async () => { + const { onSubmitReview } = RenderReviews() + + fireEvent.click(screen.getByRole('button', { name: 'Write Review' })) + PickRating(3) + fireEvent.change(screen.getByLabelText('Review (optional)'), { + target: { value: 'Pretty fun' } + }) + fireEvent.click(screen.getByRole('button', { name: 'Submit Review' })) + + await waitFor(() => expect(onSubmitReview).toHaveBeenCalledWith(3, 'Pretty fun')) + await waitFor(() => expect(screen.queryByText('Write your review')).toBeNull()) + }) + + it('keeps the form open and shows the error when saving fails', async () => { + const { onSubmitReview } = RenderReviews() + onSubmitReview.mockRejectedValue(new Error('Could not reach the server.')) + + fireEvent.click(screen.getByRole('button', { name: 'Write Review' })) + PickRating(5) + fireEvent.click(screen.getByRole('button', { name: 'Submit Review' })) + + expect((await screen.findByRole('alert')).textContent).toBe( + 'Could not reach the server.' + ) + expect(screen.getByText('Write your review')).toBeTruthy() + }) + + it('shows a fallback message when saving fails with a non-error value', async () => { + const { onSubmitReview } = RenderReviews() + onSubmitReview.mockRejectedValue('weird failure') + + fireEvent.click(screen.getByRole('button', { name: 'Write Review' })) + PickRating(2) + fireEvent.click(screen.getByRole('button', { name: 'Submit Review' })) + + expect((await screen.findByRole('alert')).textContent).toBe('Could not save review.') + }) + }) + + describe('own review', () => { + it('hides "Write Review" once the user has reviewed the game', () => { + RenderReviews({ reviews: [ownReview, otherReview] }) + + expect(screen.queryByRole('button', { name: 'Write Review' })).toBeNull() + // Only the user's own review can be edited + expect(screen.getAllByRole('button', { name: 'Edit review' })).toHaveLength(1) + }) + + it('edits the review with the existing values filled in', async () => { + const { onEditReview, onSubmitReview } = RenderReviews({ reviews: [ownReview] }) + + fireEvent.click(screen.getByRole('button', { name: 'Edit review' })) + expect(screen.getByText('Edit your review')).toBeTruthy() + expect((screen.getByLabelText('Review (optional)') as HTMLTextAreaElement).value).toBe( + 'My own review' + ) + + PickRating(2) + fireEvent.click(screen.getByRole('button', { name: 'Save Changes' })) + + await waitFor(() => expect(onEditReview).toHaveBeenCalledWith(1, 2, 'My own review')) + expect(onSubmitReview).not.toHaveBeenCalled() + await waitFor(() => expect(screen.queryByText('Edit your review')).toBeNull()) + }) + + it('deletes the review', async () => { + const { onDeleteReview } = RenderReviews({ reviews: [ownReview] }) + + fireEvent.click(screen.getByRole('button', { name: 'Delete review' })) + + await waitFor(() => expect(onDeleteReview).toHaveBeenCalledWith(1)) + expect(screen.queryByRole('alert')).toBeNull() + }) + + it('closes the edit form when the review being edited is deleted', async () => { + RenderReviews({ reviews: [ownReview] }) + + fireEvent.click(screen.getByRole('button', { name: 'Edit review' })) + expect(screen.getByText('Edit your review')).toBeTruthy() + + fireEvent.click(screen.getByRole('button', { name: 'Delete review' })) + + await waitFor(() => expect(screen.queryByText('Edit your review')).toBeNull()) + }) + + it('shows the error when deleting fails', async () => { + const { onDeleteReview } = RenderReviews({ reviews: [ownReview] }) + onDeleteReview.mockRejectedValue(new Error('Delete failed')) + + fireEvent.click(screen.getByRole('button', { name: 'Delete review' })) + + expect((await screen.findByRole('alert')).textContent).toBe('Delete failed') + }) + + it('shows a fallback message when deleting fails with a non-error value', async () => { + const { onDeleteReview } = RenderReviews({ reviews: [ownReview] }) + onDeleteReview.mockRejectedValue('weird failure') + + fireEvent.click(screen.getByRole('button', { name: 'Delete review' })) + + expect((await screen.findByRole('alert')).textContent).toBe('Could not delete review.') + }) + }) +})