1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
|
/**
* @vitest-environment jsdom
*/
import { QueryClient } from "@tanstack/query-core";
import { cleanup, render, screen } from "@testing-library/react";
import { createStore, Provider } from "jotai";
import { queryClientAtom } from "jotai-tanstack-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Route, Router } from "wouter";
import { memoryLocation } from "wouter/memory-location";
import { authLoadingAtom, type Card, type Deck } from "../atoms";
import { CardState } from "../db";
import { DeckDetailPage } from "./DeckDetailPage";
const mockDeckGet = vi.fn();
const mockCardsGet = vi.fn();
const mockHandleResponse = vi.fn();
vi.mock("../api/client", () => ({
apiClient: {
login: vi.fn(),
logout: vi.fn(),
isAuthenticated: vi.fn(),
getTokens: vi.fn(),
getAuthHeader: vi.fn(),
onSessionExpired: vi.fn(() => vi.fn()),
rpc: {
api: {
decks: {
":id": {
$get: (args: unknown) => mockDeckGet(args),
},
":deckId": {
cards: {
$get: (args: unknown) => mockCardsGet(args),
},
},
},
},
},
handleResponse: (res: unknown) => mockHandleResponse(res),
},
ApiClientError: class ApiClientError extends Error {
constructor(
message: string,
public status: number,
public code?: string,
) {
super(message);
this.name = "ApiClientError";
}
},
}));
import { apiClient } from "../api/client";
let testQueryClient: QueryClient;
const mockDeck = {
id: "deck-1",
name: "Japanese Vocabulary",
description: "Common Japanese words",
defaultNoteTypeId: null,
dueCardCount: 0,
newCardCount: 0,
totalCardCount: 0,
reviewCardCount: 0,
createdAt: "2024-01-01T00:00:00Z",
updatedAt: "2024-01-01T00:00:00Z",
};
const mockCards = [
{
id: "card-1",
deckId: "deck-1",
noteId: "note-1",
isReversed: false,
front: "Hello",
back: "こんにちは",
state: CardState.New,
due: "2099-01-01T00:00:00Z", // Not due yet (future date)
stability: 0,
difficulty: 0,
elapsedDays: 0,
scheduledDays: 0,
reps: 0,
lapses: 0,
lastReview: null,
createdAt: "2024-01-01T00:00:00Z",
updatedAt: "2024-01-01T00:00:00Z",
deletedAt: null,
syncVersion: 0,
},
{
id: "card-2",
deckId: "deck-1",
noteId: "note-2",
isReversed: false,
front: "Goodbye",
back: "さようなら",
state: CardState.Review,
due: new Date().toISOString(), // Due now
stability: 5.5,
difficulty: 5.0,
elapsedDays: 1,
scheduledDays: 7,
reps: 5,
lapses: 1,
lastReview: "2024-01-01T00:00:00Z",
createdAt: "2024-01-01T00:00:00Z",
updatedAt: "2024-01-01T00:00:00Z",
deletedAt: null,
syncVersion: 0,
},
];
interface RenderOptions {
path?: string;
initialDeck?: Deck;
initialCards?: Card[];
}
function renderWithProviders({
path = "/decks/deck-1",
initialDeck,
initialCards,
}: RenderOptions = {}) {
const { hook } = memoryLocation({ path, static: true });
const store = createStore();
store.set(authLoadingAtom, false);
store.set(queryClientAtom, testQueryClient);
// Extract deckId from path
const deckIdMatch = path.match(/\/decks\/([^/]+)/);
const deckId = deckIdMatch?.[1] ?? "deck-1";
// Seed query cache if initial data provided
if (initialDeck !== undefined) {
testQueryClient.setQueryData(["decks", deckId], initialDeck);
}
if (initialCards !== undefined) {
testQueryClient.setQueryData(["decks", deckId, "cards"], initialCards);
}
return render(
<Provider store={store}>
<Router hook={hook}>
<Route path="/decks/:deckId">
<DeckDetailPage />
</Route>
</Router>
</Provider>,
);
}
describe("DeckDetailPage", () => {
beforeEach(() => {
vi.clearAllMocks();
testQueryClient = new QueryClient({
defaultOptions: {
queries: { staleTime: Number.POSITIVE_INFINITY, retry: false },
},
});
vi.mocked(apiClient.getTokens).mockReturnValue({
accessToken: "access-token",
refreshToken: "refresh-token",
});
vi.mocked(apiClient.isAuthenticated).mockReturnValue(true);
vi.mocked(apiClient.getAuthHeader).mockReturnValue({
Authorization: "Bearer access-token",
});
mockHandleResponse.mockImplementation(async (res) => {
if (res.ok === undefined && res.status === undefined) {
return res;
}
if (!res.ok) {
const body = await res.json?.().catch(() => ({}));
throw new Error(
body?.error || `Request failed with status ${res.status}`,
);
}
return typeof res.json === "function" ? res.json() : res;
});
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
testQueryClient.clear();
});
it("renders back link and deck name", () => {
renderWithProviders({
initialDeck: mockDeck,
initialCards: mockCards,
});
expect(
screen.getByRole("heading", { name: "Japanese Vocabulary" }),
).toBeDefined();
expect(screen.getByText(/Back to Decks/)).toBeDefined();
expect(screen.getByText("Common Japanese words")).toBeDefined();
});
it("shows loading state while fetching data", async () => {
mockDeckGet.mockImplementation(() => new Promise(() => {}));
mockCardsGet.mockImplementation(() => new Promise(() => {}));
renderWithProviders();
expect(document.querySelector(".animate-spin")).toBeDefined();
});
it("does not show description if deck has none", () => {
const deckWithoutDescription = { ...mockDeck, description: null };
renderWithProviders({
initialDeck: deckWithoutDescription,
initialCards: [],
});
expect(
screen.getByRole("heading", { name: "Japanese Vocabulary" }),
).toBeDefined();
expect(screen.queryByText("Common Japanese words")).toBeNull();
});
it("displays Study Now button", () => {
renderWithProviders({
initialDeck: mockDeck,
initialCards: mockCards,
});
const studyButton = screen.getByRole("link", { name: /Study Now/ });
expect(studyButton).toBeDefined();
expect(studyButton.getAttribute("href")).toBe("/decks/deck-1/study");
});
it("displays View Cards link", () => {
renderWithProviders({
initialDeck: mockDeck,
initialCards: mockCards,
});
const viewCardsLink = screen.getByRole("link", { name: /View Cards/ });
expect(viewCardsLink).toBeDefined();
expect(viewCardsLink.getAttribute("href")).toBe("/decks/deck-1/cards");
});
it("displays total card count", () => {
renderWithProviders({
initialDeck: mockDeck,
initialCards: mockCards,
});
const totalCardsLabel = screen.getByText("Total");
expect(totalCardsLabel).toBeDefined();
// Find the count within the same container
const totalCardsContainer = totalCardsLabel.parentElement;
expect(totalCardsContainer?.querySelector(".text-ink")?.textContent).toBe(
"2",
);
});
it("displays due card count from deck data", () => {
renderWithProviders({
initialDeck: { ...mockDeck, dueCardCount: 5 },
initialCards: mockCards,
});
const dueLabel = screen.getByText("Due");
expect(dueLabel).toBeDefined();
const dueContainer = dueLabel.parentElement;
expect(dueContainer?.querySelector(".text-primary")?.textContent).toBe("5");
});
it("does not display card list (cards are hidden)", () => {
renderWithProviders({
initialDeck: mockDeck,
initialCards: mockCards,
});
// Card content should NOT be visible on deck detail page
expect(screen.queryByText("Hello")).toBeNull();
expect(screen.queryByText("こんにちは")).toBeNull();
expect(screen.queryByText("Goodbye")).toBeNull();
});
});
|