test: data router, one render helper, fetchRoutes in every test

This commit is contained in:
lobo committed 2026-09-29 16:15:50 +02:00
1 parent d0ea9e900d
commit 2a22789435
37 files changed
+454 -425

No files matched your search

+11 -10
View File
@@ -5,6 +5,7 @@ import {MemoryRouter} from 'react-router-dom';
import {toast} from 'sonner';
import AdminHintsPage from './AdminHintsPage.jsx';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
vi.mock('sonner', () => ({toast: {success: vi.fn(), error: vi.fn()}}));
@@ -15,7 +16,12 @@ const ACTIVE = {id: 2, textEn: 'Server update tonight', textDe: null, kind: 'DIS
createdBy: 1, createdAt: at(-1), doneCount: 3};
const ENDED = {...ACTIVE, id: 1, textEn: 'Old news', startsAt: at(-3), endsAt: at(-2), status: 'ENDED', doneCount: 0};
const answer = (status, body) => ({ok: status < 300, status, headers: new Headers(), json: async () => body});
const withRoutes = (routes) => fetchRoutes({
'GET /api/admin/hints': json(200, {results: [ACTIVE, ENDED]}),
'POST /api/admin/hints': json(201, {id: 3}),
'PUT /api/admin/hints/2/end': json(204),
...routes,
});
const calls = (method) => fetch.mock.calls.filter(([, init]) => (init?.method ?? 'GET') === method);
const renderPage = () => render(<MemoryRouter><PreferencesProvider><AdminHintsPage/></PreferencesProvider></MemoryRouter>);
@@ -23,11 +29,7 @@ const renderPage = () => render(<MemoryRouter><PreferencesProvider><AdminHintsPa
describe('AdminHintsPage', () => {
beforeEach(() => {
localStorage.setItem('tbp_session', '1');
globalThis.fetch = vi.fn(async (url, init) => {
if (init?.method === 'POST') return answer(201, {id: 3});
if (init?.method === 'PUT') return answer(204);
return answer(200, {results: [ACTIVE, ENDED]});
});
withRoutes({});
});
afterEach(() => {
@@ -68,8 +70,7 @@ describe('AdminHintsPage', () => {
});
it('explains an invalid time range', async () => {
fetch.mockImplementation(async (url, init) =>
(init?.method === 'POST' ? answer(400, {code: 'INVALID_HINT'}) : answer(200, {results: []})));
withRoutes({'GET /api/admin/hints': json(200, {results: []}), 'POST /api/admin/hints': json(400, {code: 'INVALID_HINT'})});
renderPage();
await screen.findByText('ADMIN_HINTS.EMPTY');
@@ -82,7 +83,7 @@ describe('AdminHintsPage', () => {
it('takes the status from the server, not from the browser clock', async () => {
// The server ended the hint by its own clock; by the browser clock the end is still 5 s away.
const endedOnServer = {...ACTIVE, endsAt: new Date(Date.now() + 5_000).toISOString(), status: 'ENDED'};
fetch.mockImplementation(async () => answer(200, {results: [endedOnServer]}));
withRoutes({'GET /api/admin/hints': json(200, {results: [endedOnServer]})});
renderPage();
await screen.findByText('Server update tonight');
@@ -103,7 +104,7 @@ describe('AdminHintsPage', () => {
});
it('shows "no access" to a non-admin', async () => {
fetch.mockImplementation(async () => answer(403));
withRoutes({'GET /api/admin/hints': json(403, {})});
renderPage();
expect(await screen.findByText('ADMIN_HINTS.NO_ACCESS')).toBeTruthy();
+13 -5
View File
@@ -5,6 +5,7 @@ import {MemoryRouter} from 'react-router-dom';
import {toast} from 'sonner';
import AdminUsersPage from './AdminUsersPage.jsx';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
vi.mock('sonner', () => ({toast: {success: vi.fn(), error: vi.fn()}}));
@@ -16,7 +17,12 @@ const PLAYER = {
const ADMIN = {...PLAYER, id: 1, email: 'admin@example.com', role: 'PLATFORM_ADMIN', steamLinked: false};
const page = (content, totalPages = 1) => ({content, page: 0, size: 20, totalElements: content.length, totalPages});
const answer = (status, body) => ({ok: status < 300, status, headers: new Headers(), json: async () => body});
const withRoutes = (routes) => fetchRoutes({
'GET /api/admin/users': json(200, page([ADMIN, PLAYER])),
'PUT /api/admin/users/7/blocked': json(204),
'DELETE /api/admin/users/7': json(204),
...routes,
});
const renderPage = () => render(<MemoryRouter><PreferencesProvider><AdminUsersPage/></PreferencesProvider></MemoryRouter>);
const calls = (method) => fetch.mock.calls.filter(([, init]) => (init?.method ?? 'GET') === method);
@@ -24,7 +30,7 @@ const calls = (method) => fetch.mock.calls.filter(([, init]) => (init?.method ??
describe('AdminUsersPage', () => {
beforeEach(() => {
localStorage.setItem('tbp_session', '1');
globalThis.fetch = vi.fn(async (url, init) => (init?.method ? answer(204) : answer(200, page([ADMIN, PLAYER]))));
withRoutes({});
});
afterEach(() => {
@@ -78,8 +84,10 @@ describe('AdminUsersPage', () => {
});
it('shows the reason when Auth refuses', async () => {
fetch.mockImplementation(async (url, init) => (init?.method
? answer(409, {code: 'TARGET_IS_ADMIN'}) : answer(200, page([PLAYER]))));
withRoutes({
'GET /api/admin/users': json(200, page([PLAYER])),
'PUT /api/admin/users/7/blocked': json(409, {code: 'TARGET_IS_ADMIN'}),
});
renderPage();
fireEvent.click(await screen.findByRole('button', {name: 'ADMIN.BLOCK'}));
@@ -89,7 +97,7 @@ describe('AdminUsersPage', () => {
});
it('says no access to a user without the admin role', async () => {
fetch.mockResolvedValue(answer(403, {}));
withRoutes({'GET /api/admin/users': json(403, {})});
renderPage();
expect(await screen.findByText('ADMIN.NO_ACCESS')).toBeTruthy();
+46 -56
View File
@@ -1,25 +1,39 @@
// @vitest-environment jsdom
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {cleanup, fireEvent, render, screen, waitFor} from '@testing-library/react';
import {MemoryRouter, Route, Routes, useLocation} from 'react-router-dom';
import RequireSession from '../components/RequireSession.jsx';
import {cleanup, fireEvent, screen, waitFor} from '@testing-library/react';
import Dashboard from './Dashboard.jsx';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
import {CurrentUserProvider} from '../context/CurrentUserContext.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
import {renderWithProviders} from '../test/renderWithProviders.jsx';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
vi.mock('../hooks/useLibrarySync.js', () => ({default: () => ({status: 'OK', lastSyncedAt: null, isRunning: false})}));
vi.mock('../hooks/useForceSync.js', () => ({default: () => ({trigger: vi.fn(), busy: false})}));
const current = {location: null};
const avatar = 'https://avatars.steamstatic.com/abc_full.jpg';
const games = Array.from({length: 12}, (_, i) => ({appid: 100 + i, name: `Game ${i}`, playtimeMinutes: 1000 - i}));
const empty = {content: [], total: 0, byStatus: {}};
const mostPlayed = (url) => url.includes('sort=playtimeMinutes') && !url.includes('status=');
const quietRoutes = {
'GET /api/library/summary': json(200, empty),
'GET /api/hints': json(200, {results: []}),
};
function Spy() {
current.location = useLocation();
return null;
}
// Every request of the page with a Steam ID; the test of the 401 answers all but the user with 401.
const dashboardRoutes = (settings) => ({
...quietRoutes,
'GET /api/users/me': json(200, {email: 'a@b.de', displayName: 'Lobo', steamId: '76561198000000000', settings}),
'GET /api/library/games': (url) => json(200, mostPlayed(url) ? {content: games, total: 12} : empty),
'GET /api/library/stats': json(200, {trend: null, habits: {moonTrips: 1, longestDay: null, underOneHourGames: 0, underOneHourShare: null}}),
'GET /api/library/steam-profile': json(200, {personaName: 'Lobo', avatarUrl: avatar}),
'GET /api/library/activity': json(200, {totalMinutes: 90, days: [{day: '2026-09-23', minutes: 0}, {day: '2026-09-24', minutes: 90}], recentGames: [
{appid: 1086940, name: "Baldur's Gate 3", playtimeMinutes: 900, playtime2Weeks: 90, status: 'PLAYING'}]}),
'GET /api/library/games-count': json(200, {count: 1, hasSteamId: true}),
'GET /api/library/achievements/summary': json(200, {unlocked: 24, startedGames: 4, perfectGames: 2,
averageCompletion: 71.3, pendingGames: 0, hiddenGames: 0, closest: []}),
'PUT /api/users/settings/dashboard-tiles': json(204, {}),
});
const ok = (body) => ({ok: true, status: 200, json: async () => body});
const unauthorized = () => ({ok: false, status: 401, json: async () => ({})});
const renderDashboard = () => renderWithProviders(<Dashboard/>, {entries: ['/dashboard']});
beforeEach(() => {
localStorage.setItem('tbp_session', '1');
@@ -32,45 +46,24 @@ afterEach(() => {
describe('Dashboard', () => {
it('opens the login page when the core API answers 401', async () => {
globalThis.fetch = vi.fn(async (url) =>
url.includes('/api/users/me') ? ok({email: 'a@b.de', steamId: '76561198000000000'}) : unauthorized());
render(
<MemoryRouter initialEntries={['/dashboard']}><PreferencesProvider><CurrentUserProvider>
<Routes>
<Route element={<RequireSession/>}><Route path="/dashboard" element={<><Dashboard/><Spy/></>}/></Route>
<Route path="/login" element={<Spy/>}/>
</Routes>
</CurrentUserProvider></PreferencesProvider></MemoryRouter>,
);
fetchRoutes({
...Object.fromEntries(Object.keys(dashboardRoutes()).map((key) => [key, json(401, {})])),
'GET /api/users/me': json(200, {email: 'a@b.de', steamId: '76561198000000000'}),
'POST /api/auth/refresh': json(401, {}),
});
const {router} = renderWithProviders(<Dashboard/>,
{path: '/dashboard', entries: ['/dashboard'], guarded: true, routes: {'/login': <p>login</p>}});
await waitFor(() => expect(fetch.mock.calls.length).toBeGreaterThanOrEqual(5));
await waitFor(() => expect(current.location.pathname).toBe('/login'));
expect(current.location.state).toEqual({sessionExpired: true, from: '/dashboard'});
await waitFor(() => expect(router.state.location.pathname).toBe('/login'));
expect(router.state.location.state).toEqual({sessionExpired: true, from: '/dashboard'});
expect(screen.queryByText('LIBRARY.EMPTY')).toBeNull();
});
const avatar = 'https://avatars.steamstatic.com/abc_full.jpg';
const games = Array.from({length: 12}, (_, i) => ({appid: 100 + i, name: `Game ${i}`, playtimeMinutes: 1000 - i}));
const mockDashboard = (settings) => {
globalThis.fetch = vi.fn(async (url, init) => {
if (init?.method === 'PUT') return {ok: true, status: 204, json: async () => ({})};
if (url.includes('/api/users/me')) return ok({email: 'a@b.de', displayName: 'Lobo', steamId: '76561198000000000', settings});
if (url.includes('sort=playtimeMinutes') && !url.includes('status=')) return ok({content: games, total: 12});
if (url.includes('/api/library/stats')) return ok({trend: null, habits: {moonTrips: 1, longestDay: null, underOneHourGames: 0, underOneHourShare: null}});
if (url.includes('/api/library/steam-profile')) return ok({personaName: 'Lobo', avatarUrl: avatar});
if (url.includes('/api/library/activity')) return ok({totalMinutes: 90, days: [{day: '2026-09-23', minutes: 0}, {day: '2026-09-24', minutes: 90}], recentGames: [
{appid: 1086940, name: "Baldur's Gate 3", playtimeMinutes: 900, playtime2Weeks: 90, status: 'PLAYING'}]});
if (url.includes('/api/library/games-count')) return ok({count: 1, hasSteamId: true});
if (url.includes('/api/library/achievements/summary')) return ok({unlocked: 24, startedGames: 4, perfectGames: 2,
averageCompletion: 71.3, pendingGames: 0, hiddenGames: 0, closest: []});
return ok({content: [], total: 0, byStatus: {}});
});
return render(
<MemoryRouter initialEntries={['/dashboard']}><PreferencesProvider><CurrentUserProvider>
<Dashboard/>
</CurrentUserProvider></PreferencesProvider></MemoryRouter>,
).container;
fetchRoutes(dashboardRoutes(settings));
return renderDashboard().container;
};
it('shows the Steam avatar and the most played game of the last two weeks as banner', async () => {
@@ -154,19 +147,16 @@ describe('Dashboard', () => {
});
it('shows the page when a card answers 200 without a JSON body', async () => {
// No Steam ID, so no activity and achievements are asked.
globalThis.fetch = vi.fn(async (url) => {
if (url.includes('/api/users/me')) return ok({email: 'a@b.de', displayName: 'Lobo'});
if (url.includes('/api/library/games-count')) return ok({count: 1, hasSteamId: true});
if (url.includes('sort=playtimeMinutes') && !url.includes('status=')) {
return {ok: true, status: 200, json: async () => { throw new SyntaxError('Unexpected token <'); }};
}
return ok({content: [], total: 0, byStatus: {}});
fetchRoutes({
...quietRoutes,
'GET /api/library/stats': json(200, empty),
'GET /api/users/me': json(200, {email: 'a@b.de', displayName: 'Lobo'}),
'GET /api/library/games-count': json(200, {count: 1, hasSteamId: true}),
'GET /api/library/games': (url) => (mostPlayed(url)
? {ok: true, status: 200, json: async () => { throw new SyntaxError('Unexpected token <'); }}
: json(200, empty)),
});
render(
<MemoryRouter initialEntries={['/dashboard']}><PreferencesProvider><CurrentUserProvider>
<Dashboard/>
</CurrentUserProvider></PreferencesProvider></MemoryRouter>,
);
renderDashboard();
expect(await screen.findByText(/DASHBOARD.HELLO/)).toBeTruthy();
});
+8 -11
View File
@@ -1,10 +1,9 @@
// @vitest-environment jsdom
import {afterEach, beforeEach, expect, it, vi} from 'vitest';
import {cleanup, fireEvent, render, screen, waitFor} from '@testing-library/react';
import {MemoryRouter, Route, Routes} from 'react-router-dom';
import {cleanup, fireEvent, screen, waitFor} from '@testing-library/react';
import GameDetail from './GameDetail.jsx';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
import {CurrentUserProvider} from '../context/CurrentUserContext.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
import {renderWithProviders} from '../test/renderWithProviders.jsx';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
// Stands in for a saved correction, which loads the game again.
@@ -21,8 +20,10 @@ const gameLoads = () => fetch.mock.calls.filter(([url]) => url.endsWith('/api/li
beforeEach(() => {
localStorage.setItem('tbp_session', '1');
globalThis.fetch = vi.fn(async (url) => ({ok: true, status: 200,
json: async () => (url.includes('/api/users/me') ? {role: 'AUDITOR', activeRole: 'AUDITOR'} : game)}));
fetchRoutes({
'GET /api/users/me': json(200, {role: 'AUDITOR', activeRole: 'AUDITOR'}),
'GET /api/library/games/220': json(200, game),
});
});
afterEach(() => {
@@ -31,11 +32,7 @@ afterEach(() => {
});
it('keeps unsaved notes while the game loads again after a correction', async () => {
render(
<MemoryRouter initialEntries={['/library/220']}><PreferencesProvider><CurrentUserProvider>
<Routes><Route path="/library/:appid" element={<GameDetail/>}/></Routes>
</CurrentUserProvider></PreferencesProvider></MemoryRouter>,
);
renderWithProviders(<GameDetail/>, {path: '/library/:appid', entries: ['/library/220']});
fireEvent.change(await screen.findByLabelText('BACKLOG.NOTES_LABEL'), {target: {value: 'my draft'}});
fireEvent.click(await screen.findByRole('button', {name: 'correction saved'}));
+47 -57
View File
@@ -1,10 +1,9 @@
// @vitest-environment jsdom
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {act, cleanup, fireEvent, render, screen, waitFor} from '@testing-library/react';
import {MemoryRouter, Route, Routes} from 'react-router-dom';
import {act, cleanup, fireEvent, screen, waitFor} from '@testing-library/react';
import GameDetail from './GameDetail.jsx';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
import {CurrentUserProvider} from '../context/CurrentUserContext.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
import {renderWithProviders} from '../test/renderWithProviders.jsx';
import {resetBrokenImageReports} from '../utils/brokenImages.js';
import {toast} from 'sonner';
@@ -16,20 +15,20 @@ const game = {
rating: null, notes: null, priority: null, hasAchievements: false, statsVisible: false, achievements: [],
};
const renderDetail = (appid = 220) => render(
<MemoryRouter initialEntries={[`/library/${appid}`]}><PreferencesProvider><CurrentUserProvider>
<Routes>
<Route path="/library/:appid" element={<GameDetail/>}/>
<Route path="/library" element={<p>library page</p>}/>
</Routes>
</CurrentUserProvider></PreferencesProvider></MemoryRouter>,
);
const renderDetail = (appid = 220) => renderWithProviders(<GameDetail/>,
{path: '/library/:appid', entries: [`/library/${appid}`], routes: {'/library': <p>library page</p>}});
const echo = (url, init) => json(200, JSON.parse(init.body));
// The user and the game at /library/<shown.appid>; `routes` adds or replaces answers.
const answer = (shown, routes = {}, me = {settings: {}}) => fetchRoutes({
'GET /api/users/me': json(200, me),
[`GET /api/library/games/${shown.appid}`]: json(200, shown),
...routes,
});
beforeEach(() => {
localStorage.setItem('tbp_session', '1');
globalThis.fetch = vi.fn(async (url, init) => init?.method === 'PUT'
? {ok: true, status: 200, json: async () => JSON.parse(init.body)}
: {ok: true, status: 200, json: async () => game});
});
afterEach(() => {
@@ -40,8 +39,7 @@ afterEach(() => {
describe('GameDetail', () => {
it('asks "finished?" instead of "playing?" when Core has a finished hint', async () => {
globalThis.fetch = vi.fn(async () => ({ok: true, status: 200, json: async () => ({...game, playtime2Weeks: 90,
source: 'STEAM', finishedHint: {type: 'ENDING', achievement: 'Survivor'}})}));
answer({...game, playtime2Weeks: 90, source: 'STEAM', finishedHint: {type: 'ENDING', achievement: 'Survivor'}});
renderDetail();
expect(await screen.findByRole('button', {name: 'GAME_DETAIL.SET_FINISHED'})).toBeTruthy();
@@ -49,9 +47,7 @@ describe('GameDetail', () => {
});
it('hides a Steam game and shows it again', async () => {
globalThis.fetch = vi.fn(async (url, init) => init?.method === 'PUT'
? {ok: true, status: 200, json: async () => JSON.parse(init.body)}
: {ok: true, status: 200, json: async () => ({...game, source: 'STEAM', hidden: false})});
answer({...game, source: 'STEAM', hidden: false}, {'PUT /api/library/games/220/hidden': echo});
renderDetail();
fireEvent.click(await screen.findByRole('button', {name: 'GAME_DETAIL.HIDE'}));
@@ -68,9 +64,7 @@ describe('GameDetail', () => {
});
it('keeps the game shown when Core refuses', async () => {
globalThis.fetch = vi.fn(async (url, init) => init?.method === 'PUT'
? {ok: false, status: 409, json: async () => ({code: 'MANUAL_GAME'})}
: {ok: true, status: 200, json: async () => ({...game, source: 'STEAM', hidden: false})});
answer({...game, source: 'STEAM', hidden: false}, {'PUT /api/library/games/220/hidden': json(409, {code: 'MANUAL_GAME'})});
renderDetail();
fireEvent.click(await screen.findByRole('button', {name: 'GAME_DETAIL.HIDE'}));
@@ -80,8 +74,7 @@ describe('GameDetail', () => {
});
it('offers no hide for a game added by hand', async () => {
globalThis.fetch = vi.fn(async () => ({ok: true, status: 200,
json: async () => ({...game, source: 'MANUAL', platform: 'PS5', hidden: false})}));
answer({...game, source: 'MANUAL', platform: 'PS5', hidden: false});
renderDetail();
await screen.findByText('GAME_DETAIL.OPEN_IN_STEAM');
@@ -91,11 +84,8 @@ describe('GameDetail', () => {
it('reports a broken achievement icon once and shows the empty tile', async () => {
const achievement = (apiName) => ({apiName, displayName: apiName, unlocked: false, iconUrl: `https://x/${apiName}.jpg`,
iconGrayUrl: `https://x/${apiName}_gray.jpg`});
globalThis.fetch = vi.fn(async (url, init) => init?.method === 'POST'
? {ok: true, status: 204}
: {ok: true, status: 200, json: async () => ({...game, hasAchievements: true, statsVisible: true,
achievementsTotal: 2, achievementsUnlocked: 0, completionPercent: 0,
achievements: [achievement('A'), achievement('B')]})});
answer({...game, hasAchievements: true, statsVisible: true, achievementsTotal: 2, achievementsUnlocked: 0,
completionPercent: 0, achievements: [achievement('A'), achievement('B')]}, {'POST /api/library/broken-images': json(204)});
const {container} = renderDetail();
await screen.findByText('A');
@@ -109,8 +99,7 @@ describe('GameDetail', () => {
});
it('links the speedrun.com page when Core found one', async () => {
globalThis.fetch = vi.fn(async () => ({ok: true, status: 200,
json: async () => ({...game, speedrunUrl: 'https://www.speedrun.com/hl2'})}));
answer({...game, speedrunUrl: 'https://www.speedrun.com/hl2'});
renderDetail();
const link = await screen.findByRole('link', {name: /GAME_DETAIL.OPEN_IN_SPEEDRUN/});
@@ -119,7 +108,7 @@ describe('GameDetail', () => {
it.each([null, 'https://www.speedrun.com.evil.example/hl2', 'https://evil.example/hl2', 42])(
'shows no speedrun link for %s', async (speedrunUrl) => {
globalThis.fetch = vi.fn(async () => ({ok: true, status: 200, json: async () => ({...game, speedrunUrl})}));
answer({...game, speedrunUrl});
renderDetail();
await screen.findByText('GAME_DETAIL.OPEN_IN_STEAM');
@@ -127,6 +116,7 @@ describe('GameDetail', () => {
});
it('keeps unsaved notes in the backlog card when the hint sets the game to playing', async () => {
answer(game, {'PUT /api/library/games/220/backlog': echo});
renderDetail();
const notes = await screen.findByLabelText('BACKLOG.NOTES_LABEL');
fireEvent.change(notes, {target: {value: 'my draft'}});
@@ -138,6 +128,7 @@ describe('GameDetail', () => {
});
it('uses the game as background and can remove it again', async () => {
answer(game, {'PUT /api/users/settings/appearance': echo});
renderDetail();
fireEvent.click(await screen.findByRole('button', {name: 'GAME_DETAIL.SET_BACKGROUND'}));
@@ -152,6 +143,7 @@ describe('GameDetail', () => {
});
it('uses the game as banner and goes back to the automatic banner', async () => {
answer(game, {'PUT /api/users/settings/appearance': echo});
renderDetail();
fireEvent.click(await screen.findByRole('button', {name: 'GAME_DETAIL.SET_BANNER'}));
@@ -166,6 +158,7 @@ describe('GameDetail', () => {
it('offers "use as banner" for the picked game while the banner is off, and turns it on', async () => {
localStorage.setItem('tbp_appearance', JSON.stringify({bannerAppid: 220, showBanner: false}));
answer(game, {'PUT /api/users/settings/appearance': echo});
renderDetail();
fireEvent.click(await screen.findByRole('button', {name: 'GAME_DETAIL.SET_BANNER'}));
@@ -182,10 +175,10 @@ describe('GameDetail of a game added by hand', () => {
playtime2Weeks: 0, imageUrl: 'https://images.igdb.com/z.jpg',
};
const noBody = {ok: true, status: 204, json: async () => { throw new Error('204 has no body'); }};
beforeEach(() => {
globalThis.fetch = vi.fn(async (url, init) => (init?.method === 'PUT' || init?.method === 'DELETE')
? {ok: true, status: 204, json: async () => { throw new Error('204 has no body'); }}
: {ok: true, status: 200, json: async () => manualGame});
answer(manualGame, {'PUT /api/library/games/-1025/manual': noBody, 'DELETE /api/library/games/-1025': noBody});
});
it('shows platform and IGDB picture, and offers no Steam actions', async () => {
@@ -227,7 +220,7 @@ describe('GameDetail of a game added by hand', () => {
});
it('keeps Save off for an unchanged game with 75 minutes', async () => {
globalThis.fetch = vi.fn(async () => ({ok: true, status: 200, json: async () => ({...manualGame, playtimeMinutes: 75})}));
answer({...manualGame, playtimeMinutes: 75});
renderDetail(-1025);
await screen.findByLabelText('MANUAL_GAME.HOURS');
@@ -236,7 +229,7 @@ describe('GameDetail of a game added by hand', () => {
});
it('shows no manual card for a Steam game', async () => {
globalThis.fetch = vi.fn(async () => ({ok: true, status: 200, json: async () => ({...game, source: 'STEAM'})}));
answer({...game, source: 'STEAM'});
renderDetail();
expect(await screen.findByRole('button', {name: 'GAME_DETAIL.SET_BACKGROUND'})).toBeTruthy();
@@ -245,10 +238,10 @@ describe('GameDetail of a game added by hand', () => {
it('keeps a background set in another tab when it sets the profile banner', async () => {
let backgroundAppid = null;
globalThis.fetch = vi.fn(async (url, init) => ({ok: true, status: init?.method === 'PUT' ? 204 : 200,
json: async () => (url.includes('/api/users/me')
? {role: 'USER', settings: {profileStyle: {accent: 'red', corners: 'round', backgroundAppid}}}
: {...game, source: 'STEAM'})}));
answer({...game, source: 'STEAM'}, {
'GET /api/users/me': () => json(200, {role: 'USER', settings: {profileStyle: {accent: 'red', corners: 'round', backgroundAppid}}}),
'PUT /api/users/settings/profile-style': json(204),
});
renderDetail();
const menu = await screen.findByRole('button', {name: 'GAME_DETAIL.PROFILE_ART'});
@@ -264,10 +257,10 @@ describe('GameDetail of a game added by hand', () => {
it('keeps a banner picked in another tab when it sets this game as banner', async () => {
let bannerAppid = 220;
globalThis.fetch = vi.fn(async (url, init) => ({ok: true, status: init?.method === 'PUT' ? 204 : 200,
json: async () => (url.includes('/api/users/me')
? {role: 'USER', settings: {profileStyle: {bannerAppid}}}
: {...game, source: 'STEAM'})}));
answer({...game, source: 'STEAM'}, {
'GET /api/users/me': () => json(200, {role: 'USER', settings: {profileStyle: {bannerAppid}}}),
'PUT /api/users/settings/profile-style': json(204),
});
renderDetail();
const menu = await screen.findByRole('button', {name: 'GAME_DETAIL.PROFILE_ART'});
@@ -282,12 +275,12 @@ describe('GameDetail of a game added by hand', () => {
it('uses the art as profile banner and removes it on the second click', async () => {
let stored = {accent: 'red', corners: 'round'};
globalThis.fetch = vi.fn(async (url, init) => {
if (init?.method === 'PUT') stored = JSON.parse(init.body);
return {ok: true, status: init?.method === 'PUT' ? 204 : 200,
json: async () => (url.includes('/api/users/me')
? {role: 'USER', settings: {profileStyle: stored}}
: {...game, source: 'STEAM'})};
answer({...game, source: 'STEAM'}, {
'GET /api/users/me': () => json(200, {role: 'USER', settings: {profileStyle: stored}}),
'PUT /api/users/settings/profile-style': (url, init) => {
stored = JSON.parse(init.body);
return json(204);
},
});
const styleBodies = () => fetch.mock.calls.filter(([url, init]) => init?.method === 'PUT' && url.endsWith('/profile-style'))
.map(([, init]) => JSON.parse(init.body));
@@ -308,10 +301,7 @@ describe('GameDetail of a game added by hand', () => {
});
describe('corrections', () => {
const loggedInAs = (me) => {
globalThis.fetch = vi.fn(async (url) => ({ok: true, status: 200,
json: async () => (url.includes('/api/users/me') ? me : game)}));
};
const loggedInAs = (me) => answer(game, {}, me);
it('offers "correct data" to an active auditor', async () => {
loggedInAs({role: 'AUDITOR', activeRole: 'AUDITOR'});
@@ -359,7 +349,7 @@ describe('GameDetail confetti', () => {
});
const opened = async (entry) => {
globalThis.fetch = vi.fn(async () => ({ok: true, status: 200, json: async () => ({...game, ...entry})}));
answer({...game, ...entry});
const {container} = renderDetail();
await screen.findByText('Half-Life 2');
return container.querySelector('canvas[data-size]');
+22 -20
View File
@@ -1,9 +1,10 @@
// @vitest-environment jsdom
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {act, cleanup, fireEvent, render, screen, waitFor} from '@testing-library/react';
import {MemoryRouter, Route, Routes, useLocation, useNavigate} from 'react-router-dom';
import {createMemoryRouter, RouterProvider, useLocation, useNavigate} from 'react-router-dom';
import GameLibrary from './GameLibrary.jsx';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
vi.mock('../hooks/useLibrarySync.js', () => ({default: () => ({status: 'OK', lastSyncedAt: null, isRunning: false})}));
@@ -12,9 +13,14 @@ vi.mock('../hooks/useForceSync.js', () => ({default: () => ({trigger: vi.fn(), b
const DEBOUNCE_WAIT_MS = 700;
const page = {content: [{appid: 220, name: 'Half-Life 2', playtimeMinutes: 0, status: 'BACKLOG'}], page: 0, size: 20, totalElements: 1, totalPages: 1};
const answer = (games = page.content, hasSteamId = true) => fetchRoutes({
'GET /api/library/games': json(200, {...page, content: games, totalElements: games.length, totalPages: games.length ? 1 : 0}),
'GET /api/library/games-count': json(200, {count: games.length, hasSteamId}),
});
const wait = (ms) => act(() => new Promise((resolve) => setTimeout(resolve, ms)));
// MemoryRouter, not createMemoryRouter: it pushes like the BrowserRouter in main.jsx, also for an unchanged URL.
// A data router like main.jsx: a navigation to the same URL replaces the entry.
function renderLibrary(initialEntry = '/library') {
const lib = {navigations: 0, location: null, navigate: null};
function Spy() {
@@ -26,11 +32,11 @@ function renderLibrary(initialEntry = '/library') {
}
return null;
}
render(
<MemoryRouter initialEntries={[initialEntry]}><PreferencesProvider>
<Routes><Route path="/library" element={<><GameLibrary/><Spy/></>}/></Routes>
</PreferencesProvider></MemoryRouter>,
);
const router = createMemoryRouter([{
path: '/library',
element: <PreferencesProvider><GameLibrary/><Spy/></PreferencesProvider>,
}], {initialEntries: [initialEntry]});
render(<RouterProvider router={router}/>);
return {
navigations: () => lib.navigations,
params: () => new URLSearchParams(lib.location.search),
@@ -42,7 +48,7 @@ const typeInto = (value) => fireEvent.change(screen.getByRole('searchbox'), {tar
beforeEach(() => {
localStorage.setItem('tbp_session', '1');
globalThis.fetch = vi.fn(async () => ({ok: true, status: 200, json: async () => page}));
answer();
});
afterEach(() => {
@@ -52,10 +58,10 @@ afterEach(() => {
describe('GameLibrary search', () => {
it('shows the achievement progress of a game when it is known', async () => {
globalThis.fetch = vi.fn(async () => ({ok: true, status: 200, json: async () => ({...page, content: [
answer([
{...page.content[0], achievementsUnlocked: 3, achievementsTotal: 4},
{appid: 620, name: 'Portal 2', playtimeMinutes: 0, status: 'BACKLOG', achievementsUnlocked: null, achievementsTotal: 5},
]})}));
]);
renderLibrary();
expect(await screen.findByText('3/4')).toBeTruthy();
@@ -100,7 +106,7 @@ describe('GameLibrary search', () => {
typeInto('half');
await waitFor(() => expect(lib.params().get('q')).toBe('half'));
act(() => lib.back());
await act(async () => lib.back());
await waitFor(() => expect(screen.getByRole('searchbox').value).toBe(''));
});
@@ -161,7 +167,7 @@ describe('GameLibrary short games', () => {
});
it('says so when no game is hidden', async () => {
globalThis.fetch = vi.fn(async () => ({ok: true, status: 200, json: async () => ({...page, content: [], totalElements: 0, totalPages: 0})}));
answer([]);
renderLibrary('/library?hidden=true');
expect(await screen.findByText('LIBRARY.NO_HIDDEN')).toBeTruthy();
@@ -169,15 +175,11 @@ describe('GameLibrary short games', () => {
});
describe('GameLibrary with games added by hand', () => {
const answer = (games, hasSteamId) => vi.fn(async (url) => ({
ok: true, status: 200,
json: async () => (String(url).includes('/games-count') ? {count: games.length, hasSteamId} : {...page, content: games}),
}));
const zelda = {appid: -1025, name: 'Zelda', playtimeMinutes: 90, status: 'BACKLOG', source: 'MANUAL',
platform: 'Nintendo Switch', imageUrl: 'https://images.igdb.com/z.jpg'};
it('shows the platform and the IGDB picture of a manual game', async () => {
globalThis.fetch = answer([zelda], true);
answer([zelda], true);
renderLibrary();
expect(await screen.findByText('Nintendo Switch')).toBeTruthy();
@@ -185,7 +187,7 @@ describe('GameLibrary with games added by hand', () => {
});
it('shows Steam as the platform of a Steam game, and links the import', async () => {
globalThis.fetch = answer([{appid: 220, name: 'Half-Life 2', playtimeMinutes: 0, status: 'BACKLOG', source: 'STEAM',
answer([{appid: 220, name: 'Half-Life 2', playtimeMinutes: 0, status: 'BACKLOG', source: 'STEAM',
platform: null}], true);
renderLibrary();
@@ -194,7 +196,7 @@ describe('GameLibrary with games added by hand', () => {
});
it('hides the Steam sync for a user without a Steam ID but still offers adding a game', async () => {
globalThis.fetch = answer([zelda], false);
answer([zelda], false);
renderLibrary();
await screen.findByText('Zelda');
@@ -203,7 +205,7 @@ describe('GameLibrary with games added by hand', () => {
});
it('opens the add panel', async () => {
globalThis.fetch = answer([zelda], true);
answer([zelda], true);
renderLibrary();
fireEvent.click(await screen.findByRole('button', {name: 'MANUAL_GAME.ADD_BUTTON'}));
+7 -3
View File
@@ -3,6 +3,7 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {cleanup, fireEvent, render, screen, waitFor} from '@testing-library/react';
import {MemoryRouter, Route, Routes, useLocation} from 'react-router-dom';
import LoginPage from './LoginPage.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
@@ -22,6 +23,9 @@ function renderLogin(state) {
);
}
// The page reads Retry-After from a refusal.
const refused = (status, code) => ({...json(status, {code}), headers: new Headers()});
function submit() {
fireEvent.change(screen.getByLabelText('LOGIN.EMAIL'), {target: {value: 'a@b.de'}});
fireEvent.change(screen.getByLabelText('LOGIN.PASSWORD'), {target: {value: 'secret'}});
@@ -30,7 +34,7 @@ function submit() {
describe('LoginPage', () => {
beforeEach(() => {
globalThis.fetch = vi.fn(async () => ({ok: true, status: 200, json: async () => ({message: 'Login successful'})}));
fetchRoutes({'POST /api/auth/login': json(200, {message: 'Login successful'})});
});
afterEach(() => {
@@ -72,7 +76,7 @@ describe('LoginPage', () => {
});
it('hides the expired message once a login attempt fails', async () => {
fetch.mockResolvedValueOnce({ok: false, status: 401, headers: new Headers(), json: async () => ({code: 'INVALID_CREDENTIALS'})});
fetchRoutes({'POST /api/auth/login': refused(401, 'INVALID_CREDENTIALS')});
renderLogin({sessionExpired: true, from: '/library'});
submit();
@@ -82,7 +86,7 @@ describe('LoginPage', () => {
});
it('says that a blocked account is blocked', async () => {
fetch.mockResolvedValueOnce({ok: false, status: 403, headers: new Headers(), json: async () => ({code: 'ACCOUNT_BLOCKED'})});
fetchRoutes({'POST /api/auth/login': refused(403, 'ACCOUNT_BLOCKED')});
renderLogin();
submit();
+2 -1
View File
@@ -3,6 +3,7 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {cleanup, render, screen, waitFor} from '@testing-library/react';
import {MemoryRouter} from 'react-router-dom';
import PlayNextPage from './PlayNextPage.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
// react-i18next hands out a new `t` on every language change; this mock does the same on demand.
@@ -19,7 +20,7 @@ describe('PlayNextPage on a language change', () => {
beforeEach(() => {
localStorage.setItem('tbp_session', '1');
i18n.t = (key) => key;
globalThis.fetch = vi.fn(async () => ({ok: true, status: 200, json: async () => ({games: [game(1)]})}));
fetchRoutes({'GET /api/library/picker': json(200, {games: [game(1)]})});
});
afterEach(() => {
+11 -17
View File
@@ -4,6 +4,7 @@ import {cleanup, fireEvent, render, screen, waitFor} from '@testing-library/reac
import {MemoryRouter} from 'react-router-dom';
import PlayNextPage from './PlayNextPage.jsx';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
vi.mock('sonner', () => ({toast: {success: vi.fn(), error: vi.fn()}}));
@@ -13,15 +14,13 @@ const game = (appid, extra = {}) => ({
timeToBeatMinutes: 600, ...extra,
});
const json = (body, status = 200) => ({ok: status < 400, status, json: async () => body});
// Answers each picker call with the next list and records every request.
function mockBackend(pickerAnswers, detail = null) {
// Answers each picker call with the next list.
function mockBackend(pickerAnswers, routes = {}) {
const answers = [...pickerAnswers];
globalThis.fetch = vi.fn(async (url, options = {}) => {
if (url.includes('/api/library/picker')) return json({games: answers.shift() ?? []});
if (options.method === 'PUT') return json(JSON.parse(options.body));
return json(detail);
fetchRoutes({
'GET /api/library/picker': () => json(200, {games: answers.shift() ?? []}),
'PUT /api/library/games/7/status': (url, init) => json(200, JSON.parse(init.body)),
...routes,
});
}
@@ -135,10 +134,8 @@ describe('PlayNextPage', () => {
});
it('drops the old picks when a new budget fails to load', async () => {
mockBackend([[game(1)]]);
const pickerFetch = globalThis.fetch;
globalThis.fetch = vi.fn(async (url, options) =>
(url.includes('maxMinutes=300') ? json({}, 500) : pickerFetch(url, options)));
mockBackend([], {'GET /api/library/picker': (url) =>
(url.includes('maxMinutes=300') ? json(500, {}) : json(200, {games: [game(1)]}))});
renderPage();
await screen.findByText('Game 1');
@@ -195,10 +192,7 @@ describe('PlayNextPage', () => {
});
it('lets the user try again when saving fails', async () => {
mockBackend([[game(7)]]);
const pickerFetch = globalThis.fetch;
globalThis.fetch = vi.fn(async (url, options) =>
(options?.method === 'PUT' ? json({}, 500) : pickerFetch(url, options)));
mockBackend([[game(7)]], {'PUT /api/library/games/7/status': json(500, {})});
renderPage();
await screen.findByText('Game 7');
@@ -224,7 +218,7 @@ describe('PlayNextPage', () => {
});
it('offers a retry when the first load fails', async () => {
globalThis.fetch = vi.fn(async () => { throw new TypeError('Failed to fetch'); });
mockBackend([], {'GET /api/library/picker': () => { throw new TypeError('Failed to fetch'); }});
renderPage();
await screen.findByText('INFO.ERROR.NETWORK_FAILURE');
+15 -19
View File
@@ -1,10 +1,9 @@
// @vitest-environment jsdom
import {afterEach, describe, expect, it, vi} from 'vitest';
import {cleanup, fireEvent, render, screen, waitFor} from '@testing-library/react';
import {MemoryRouter, Route, Routes} from 'react-router-dom';
import {cleanup, fireEvent, screen, waitFor} from '@testing-library/react';
import PublicProfilePage from './PublicProfilePage.jsx';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
import {CurrentUserProvider} from '../context/CurrentUserContext.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
import {renderWithProviders} from '../test/renderWithProviders.jsx';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
@@ -15,29 +14,26 @@ const library = {
finished: [{appid: 620, name: 'Portal 2', playtimeMinutes: 900, status: 'COMPLETED', rating: 5}],
};
function mockBackends({profileStatus = 200, libraryStatus = 200, style, answer = library, me} = {}) {
globalThis.fetch = vi.fn(async (url, init) => {
if (init?.method === 'PUT') return {ok: true, status: 204, json: async () => ({})};
if (url.includes('/api/users/me')) return {ok: !!me, status: me ? 200 : 401, json: async () => me};
if (url.includes('/api/public/profiles/library')) {
return {ok: libraryStatus === 200, status: libraryStatus, json: async () => answer};
}
return {ok: profileStatus === 200, status: profileStatus,
json: async () => ({displayName: 'Lobo', memberSince: '2026-03-02', ticket: 'the-ticket', style})};
// `me` only for a test with a session: without one the page asks nothing about the viewer.
function mockBackends({name = 'Lobo', profileStatus = 200, libraryStatus = 200, style, answer = library, me} = {}) {
fetchRoutes({
[`GET /api/public/profiles/${encodeURIComponent(name)}`]:
json(profileStatus, {displayName: 'Lobo', memberSince: '2026-03-02', ticket: 'the-ticket', style}),
'GET /api/public/profiles/library': json(libraryStatus, answer),
...(me && {
'GET /api/users/me': json(200, me),
'PUT /api/users/settings/profile-tiles': json(204, {}),
}),
});
}
const renderPage = (name = 'Lobo') => render(
<MemoryRouter initialEntries={[`/u/${name}`]}><PreferencesProvider><CurrentUserProvider>
<Routes><Route path="/u/:name" element={<PublicProfilePage/>}/></Routes>
</CurrentUserProvider></PreferencesProvider></MemoryRouter>,
);
const renderPage = (name = 'Lobo') => renderWithProviders(<PublicProfilePage/>, {path: '/u/:name', entries: [`/u/${name}`]});
describe('PublicProfilePage', () => {
afterEach(cleanup);
it('asks Auth for the ticket, then Core for the library with it', async () => {
mockBackends();
mockBackends({name: 'Lo bo'});
renderPage('Lo bo');
expect(await screen.findByText('Portal 2')).toBeTruthy();
+9 -12
View File
@@ -3,6 +3,7 @@ import {afterEach, describe, expect, it, vi} from 'vitest';
import {cleanup, fireEvent, render, screen} from '@testing-library/react';
import {MemoryRouter} from 'react-router-dom';
import RegistrationPage from './RegistrationPage.jsx';
import {fetchRoutes} from '../test/fetchRoutes.js';
// Own mock: the shared one drops the {{minutes}} value this test checks.
vi.mock('react-i18next', () => ({
@@ -12,14 +13,10 @@ vi.mock('react-i18next', () => ({
}),
}));
function errorResponse(status, code, headers = {}, message = undefined) {
return {
ok: false,
status,
headers: new Headers(headers),
json: async () => ({code, message}),
};
}
// Not `json` from fetchRoutes: the page reads Retry-After from the headers.
const answerRegistration = (status, code, headers = {}, message = undefined) => fetchRoutes({
'POST /api/registration/new': {ok: false, status, headers: new Headers(headers), json: async () => ({code, message})},
});
function submitValidForm() {
render(<MemoryRouter><RegistrationPage/></MemoryRouter>);
@@ -36,7 +33,7 @@ describe('RegistrationPage', () => {
});
it('shows the wait time when the IP is blocked', async () => {
globalThis.fetch = vi.fn(async () => errorResponse(429, 'TOO_MANY_ATTEMPTS', {'Retry-After': '900'}));
answerRegistration(429, 'TOO_MANY_ATTEMPTS', {'Retry-After': '900'});
submitValidForm();
@@ -44,7 +41,7 @@ describe('RegistrationPage', () => {
});
it('asks for no Steam ID and sends none', async () => {
globalThis.fetch = vi.fn(async () => errorResponse(400, 'INVALID_INVITATION_CODE'));
answerRegistration(400, 'INVALID_INVITATION_CODE');
submitValidForm();
@@ -54,7 +51,7 @@ describe('RegistrationPage', () => {
});
it('maps a known backend error to its message', async () => {
globalThis.fetch = vi.fn(async () => errorResponse(400, 'INVALID_INVITATION_CODE'));
answerRegistration(400, 'INVALID_INVITATION_CODE');
submitValidForm();
@@ -62,7 +59,7 @@ describe('RegistrationPage', () => {
});
it('shows its own text, not the English one of the server, for a refused input', async () => {
globalThis.fetch = vi.fn(async () => errorResponse(400, 'VALIDATION_FAILED', {}, 'The request is not valid'));
answerRegistration(400, 'VALIDATION_FAILED', {}, 'The request is not valid');
submitValidForm();
+13 -13
View File
@@ -1,11 +1,10 @@
// @vitest-environment jsdom
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {cleanup, fireEvent, render, screen, waitFor} from '@testing-library/react';
import {MemoryRouter} from 'react-router-dom';
import {cleanup, fireEvent, screen, waitFor} from '@testing-library/react';
import {toast} from 'sonner';
import SettingsPage from './SettingsPage.jsx';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
import {CurrentUserProvider} from '../context/CurrentUserContext.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
import {renderWithProviders} from '../test/renderWithProviders.jsx';
vi.mock('react-i18next', async () => {
const mock = await import('../test/i18n-mock.js');
@@ -23,17 +22,18 @@ const profile = (overrides = {}) => ({
const calls = (method) => fetch.mock.calls.filter(([, init]) => init?.method === method);
const noBody = {ok: true, status: 204, json: async () => { throw new SyntaxError('no body'); }};
function renderPage(me, {redirectUrl = STEAM_URL, entry = '/settings'} = {}) {
globalThis.fetch = vi.fn(async (url, init) => {
if (init?.method === 'POST' && url.endsWith('/api/users/steam-link')) {
return {ok: true, status: 200, json: async () => ({redirectUrl})};
}
if (init?.method && init.method !== 'GET') {
return {ok: true, status: 204, json: async () => { throw new SyntaxError('no body'); }};
}
return {ok: true, status: 200, json: async () => me};
fetchRoutes({
'GET /api/users/me': json(200, me),
'POST /api/users/steam-link': json(200, {redirectUrl}),
'DELETE /api/users/steam-link': noBody,
'PUT /api/users/settings': noBody,
'POST /api/auth/refresh': noBody,
'GET /api/version': json(404, {}),
});
render(<MemoryRouter initialEntries={[entry]}><PreferencesProvider><CurrentUserProvider><SettingsPage/></CurrentUserProvider></PreferencesProvider></MemoryRouter>);
renderWithProviders(<SettingsPage/>, {path: '/settings', entries: [entry]});
}
describe('SettingsPage Steam account', () => {
+9 -8
View File
@@ -1,11 +1,10 @@
// @vitest-environment jsdom
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {act, cleanup, render, screen} from '@testing-library/react';
import {MemoryRouter} from 'react-router-dom';
import {act, cleanup, screen} from '@testing-library/react';
import {toast} from 'sonner';
import SettingsPage from './SettingsPage.jsx';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
import {CurrentUserProvider} from '../context/CurrentUserContext.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
import {renderWithProviders} from '../test/renderWithProviders.jsx';
// Like react-i18next: a language change re-renders every subscriber with a fresh `t`.
vi.mock('react-i18next', async () => {
@@ -33,9 +32,11 @@ const profile = {
describe('SettingsPage Steam toast', () => {
beforeEach(() => {
localStorage.setItem('tbp_session', '1');
globalThis.fetch = vi.fn(async (url, init) => (init?.method && init.method !== 'GET'
? {ok: true, status: 204, json: async () => { throw new SyntaxError('no body'); }}
: {ok: true, status: 200, json: async () => profile}));
fetchRoutes({
'GET /api/users/me': json(200, profile),
'POST /api/auth/refresh': {ok: true, status: 204, json: async () => { throw new SyntaxError('no body'); }},
'GET /api/version': json(404, {}),
});
});
afterEach(() => {
@@ -45,7 +46,7 @@ describe('SettingsPage Steam toast', () => {
});
it('shows the linked toast once, also after a language change', async () => {
render(<MemoryRouter initialEntries={['/settings?steam=linked']}><PreferencesProvider><CurrentUserProvider><SettingsPage/></CurrentUserProvider></PreferencesProvider></MemoryRouter>);
renderWithProviders(<SettingsPage/>, {path: '/settings', entries: ['/settings?steam=linked']});
await screen.findByText('SETTINGS.STEAM_LINK.VERIFIED');
expect(toast.success).toHaveBeenCalledTimes(1);
+23 -15
View File
@@ -1,10 +1,9 @@
// @vitest-environment jsdom
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {act, cleanup, fireEvent, render, screen, waitFor, within} from '@testing-library/react';
import {MemoryRouter} from 'react-router-dom';
import {act, cleanup, fireEvent, screen, waitFor, within} from '@testing-library/react';
import SettingsPage from './SettingsPage.jsx';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
import {CurrentUserProvider} from '../context/CurrentUserContext.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
import {renderWithProviders} from '../test/renderWithProviders.jsx';
vi.mock('react-i18next', async () => {
const mock = await import('../test/i18n-mock.js');
@@ -22,12 +21,21 @@ const appearanceCard = () => within(screen.getByText('SETTINGS.APPEARANCE').clos
const puts = () => fetch.mock.calls.filter(([, init]) => init?.method === 'PUT').map(([, init]) => JSON.parse(init.body));
// Every PUT answers 204 without a body, like Auth does.
const noBody = {ok: true, status: 204, json: async () => { throw new SyntaxError('no body'); }};
const authRoutes = (me) => ({
'GET /api/users/me': () => json(200, me()),
'PUT /api/users/settings': noBody,
'PUT /api/users/settings/appearance': noBody,
'PUT /api/users/settings/profile-style': noBody,
'PUT /api/users/settings/favorite-platform': noBody,
'GET /api/version': json(404, {}),
});
function renderPage(me) {
globalThis.fetch = vi.fn(async (url, init) => (init?.method === 'PUT'
// Both PUTs answer 204 without a body, like Auth does.
? {ok: true, status: 204, json: async () => { throw new SyntaxError('no body'); }}
: {ok: true, status: 200, json: async () => me}));
render(<MemoryRouter><PreferencesProvider><CurrentUserProvider><SettingsPage/></CurrentUserProvider></PreferencesProvider></MemoryRouter>);
fetchRoutes(authRoutes(() => me));
renderWithProviders(<SettingsPage/>);
}
/**
@@ -36,14 +44,14 @@ function renderPage(me) {
function fakeAuth(me) {
const saved = structuredClone(me);
const open = [];
globalThis.fetch = vi.fn((url, init) => {
if (init?.method !== 'PUT') return Promise.resolve({ok: true, status: 200, json: async () => structuredClone(saved)});
return new Promise((resolve) => open.push(() => {
fetchRoutes({
...authRoutes(() => structuredClone(saved)),
'PUT /api/users/settings': (url, init) => new Promise((resolve) => open.push(() => {
const body = JSON.parse(init.body);
saved.displayName = body.displayName;
Object.assign(saved.settings, {useDarkTheme: body.useDarkTheme, language: body.language, publicProfile: body.publicProfile});
resolve({ok: true, status: 204, json: async () => { throw new SyntaxError('no body'); }});
}));
resolve(noBody);
})),
});
return {answer: () => open.shift()()};
}
@@ -67,7 +75,7 @@ describe('SettingsPage public profile', () => {
it('builds a save on the one before it, also while that one is still open', async () => {
const auth = fakeAuth(profile());
render(<MemoryRouter><PreferencesProvider><CurrentUserProvider><SettingsPage/></CurrentUserProvider></PreferencesProvider></MemoryRouter>);
renderWithProviders(<SettingsPage/>);
fireEvent.click(await screen.findByRole('switch', {name: 'SETTINGS.PUBLIC_PROFILE'}));
await waitFor(() => expect(puts()).toHaveLength(1));
+5 -4
View File
@@ -4,10 +4,11 @@ import {cleanup, fireEvent, render, screen, waitFor} from '@testing-library/reac
import {MemoryRouter} from 'react-router-dom';
import StatsPage from './StatsPage.jsx';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
const json = (body, status = 200) => ({ok: status < 400, status, json: async () => body});
const answerStats = (answer) => fetchRoutes({'GET /api/library/stats': answer});
const stats = (extra = {}) => ({
overview: {totalGames: 12, totalPlaytimeMinutes: 6000, playedGames: 8, neverStarted: 4,
@@ -38,7 +39,7 @@ describe('StatsPage', () => {
});
it('asks for every group once and shows each of them', async () => {
globalThis.fetch = vi.fn(async () => json(stats()));
answerStats(json(200, stats()));
renderPage();
expect(await screen.findByText('STATS.OVERVIEW.TITLE')).toBeTruthy();
@@ -56,7 +57,7 @@ describe('StatsPage', () => {
it('shows the empty texts of a new library', async () => {
const empty = stats();
globalThis.fetch = vi.fn(async () => json({
answerStats(json(200, {
...empty,
pile: {...empty.pile, paceWeeks: null, oldestUnplayed: null},
topGames: {mostPlayed: [], mostLoyal: null},
@@ -77,7 +78,7 @@ describe('StatsPage', () => {
});
it('offers a retry when the stats could not be loaded', async () => {
globalThis.fetch = vi.fn(async () => json({}, 500));
answerStats(json(500, {}));
renderPage();
fireEvent.click(await screen.findByRole('button', {name: /DASHBOARD.RETRY/}));
+14 -20
View File
@@ -1,10 +1,9 @@
// @vitest-environment jsdom
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {cleanup, fireEvent, render, screen, waitFor} from '@testing-library/react';
import {MemoryRouter, Route, Routes, useLocation} from 'react-router-dom';
import RequireSession from '../components/RequireSession.jsx';
import {cleanup, fireEvent, screen, waitFor} from '@testing-library/react';
import WishlistPage from './WishlistPage.jsx';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
import {renderWithProviders} from '../test/renderWithProviders.jsx';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
@@ -13,23 +12,15 @@ const wishlist = {games: [
{appid: 3012600, name: 'Coming Soon', addedAt: '2025-06-01T00:00:00Z', price: null, originalPrice: null, discountPct: 0},
]};
function LoginState() {
return <div data-testid="login">{JSON.stringify(useLocation().state)}</div>;
}
// The providers load the user and the preferences; this page does not use them.
const withAuth = (routes) => fetchRoutes({'GET /api/users/me': json(200, {settings: {}}), ...routes});
const renderPage = () => render(
<MemoryRouter initialEntries={['/wishlist']}><PreferencesProvider>
<Routes>
<Route element={<RequireSession/>}><Route path="/wishlist" element={<WishlistPage/>}/></Route>
<Route path="/login" element={<LoginState/>}/>
</Routes>
</PreferencesProvider></MemoryRouter>,
);
const renderPage = () => renderWithProviders(<WishlistPage/>,
{path: '/wishlist', entries: ['/wishlist'], guarded: true, routes: {'/login': <p>login</p>}});
describe('WishlistPage', () => {
beforeEach(() => {
localStorage.setItem('tbp_session', '1');
globalThis.fetch = vi.fn(async () => ({ok: true, status: 200, json: async () => wishlist}));
});
afterEach(() => {
@@ -38,6 +29,7 @@ describe('WishlistPage', () => {
});
it('shows each game with its price, and the discount for games on sale', async () => {
withAuth({'GET /api/library/wishlist': json(200, wishlist)});
renderPage();
expect(await screen.findByText('Prison Architect 2')).toBeTruthy();
@@ -49,6 +41,7 @@ describe('WishlistPage', () => {
});
it('can show only the games on sale', async () => {
withAuth({'GET /api/library/wishlist': json(200, wishlist)});
renderPage();
await screen.findByText('Coming Soon');
@@ -59,16 +52,17 @@ describe('WishlistPage', () => {
});
it('explains an empty or private wishlist', async () => {
fetch.mockResolvedValueOnce({ok: true, status: 200, json: async () => ({games: []})});
withAuth({'GET /api/library/wishlist': json(200, {games: []})});
renderPage();
expect(await screen.findByText('WISHLIST.EMPTY')).toBeTruthy();
});
it('opens the login page on a 401 that the refresh cannot fix', async () => {
fetch.mockResolvedValue({ok: false, status: 401, json: async () => ({})});
renderPage();
withAuth({'GET /api/library/wishlist': json(401, {}), 'POST /api/auth/refresh': json(401, {})});
const {router} = renderPage();
await waitFor(() => expect(JSON.parse(screen.getByTestId('login').textContent).sessionExpired).toBe(true));
await waitFor(() => expect(router.state.location.pathname).toBe('/login'));
expect(router.state.location.state.sessionExpired).toBe(true);
});
});
+11 -8
View File
@@ -3,6 +3,7 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {cleanup, render, screen} from '@testing-library/react';
import {MemoryRouter, Route, Routes} from 'react-router-dom';
import {switchLanguage} from '../test/i18n-mock.js';
import {fetchRoutes, json} from '../test/fetchRoutes.js';
import {PreferencesProvider} from '../context/PreferencesContext.jsx';
import {CurrentUserProvider} from '../context/CurrentUserContext.jsx';
import Dashboard from './Dashboard.jsx';
@@ -14,19 +15,20 @@ import WishlistPage from './WishlistPage.jsx';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
// The last column: what the page loads besides GET /api/users/me of the provider.
const pages = [
['Dashboard', '/', '/', Dashboard, 'INFO.ERROR.LOAD_PROFILE'],
['GameDetail', '/games/:appid', '/games/220', GameDetail, 'GAME_DETAIL.ERROR_LOAD'],
['GameLibrary', '/library', '/library', GameLibrary, 'LIBRARY.ERROR_LOAD'],
['PublicProfilePage', '/u/:name', '/u/Lobo', PublicProfilePage, 'PROFILE.ERROR_LOAD'],
['SettingsPage', '/settings', '/settings', SettingsPage, 'INFO.ERROR.LOAD_PROFILE'],
['WishlistPage', '/wishlist', '/wishlist', WishlistPage, 'WISHLIST.ERROR_LOAD'],
['Dashboard', '/', '/', Dashboard, 'INFO.ERROR.LOAD_PROFILE', []],
['GameDetail', '/games/:appid', '/games/220', GameDetail, 'GAME_DETAIL.ERROR_LOAD', ['/api/library/games/220']],
['GameLibrary', '/library', '/library', GameLibrary, 'LIBRARY.ERROR_LOAD',
['/api/library/games', '/api/library/games-count', '/api/library/sync-status']],
['PublicProfilePage', '/u/:name', '/u/Lobo', PublicProfilePage, 'PROFILE.ERROR_LOAD', ['/api/public/profiles/Lobo']],
['SettingsPage', '/settings', '/settings', SettingsPage, 'INFO.ERROR.LOAD_PROFILE', []],
['WishlistPage', '/wishlist', '/wishlist', WishlistPage, 'WISHLIST.ERROR_LOAD', ['/api/library/wishlist']],
];
beforeEach(() => {
localStorage.setItem('tbp_session', '1');
switchLanguage('de');
globalThis.fetch = vi.fn(async () => ({ok: false, status: 500, json: async () => ({})}));
});
afterEach(() => {
@@ -35,7 +37,8 @@ afterEach(() => {
});
describe('a language change', () => {
it.each(pages)('%s: loads nothing again and shows the error in the new language', async (name, path, url, Page, errorKey) => {
it.each(pages)('%s: loads nothing again and shows the error in the new language', async (name, path, url, Page, errorKey, loads) => {
fetchRoutes(Object.fromEntries(['/api/users/me', ...loads].map((load) => [`GET ${load}`, json(500, {})])));
const tree = () => (
<MemoryRouter initialEntries={[url]}>
<PreferencesProvider><CurrentUserProvider><Routes><Route path={path} element={<Page/>}/></Routes></CurrentUserProvider></PreferencesProvider>