Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 73 additions & 20 deletions src/App.test.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
import { beforeEach, describe, expect, it } from "vitest";
import { describe, expect, it } from "vitest";
import { http, HttpResponse, delay } from "msw";
import { fireEvent, screen, waitFor } from "@testing-library/react";
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import App from "./App";
import { withProviders } from "./test/utils";
import { server } from "./test/server";
import {
emptySearchHandler,
failingSearchHandler,
fixtureDocs,
getSearchRequestCount,
resetSearchRequestCount,
} from "./test/handlers";

describe("App", () => {
beforeEach(() => {
sessionStorage.clear();
resetSearchRequestCount();
function subjectCapturingHandler(subjects: string[]) {
return http.get("https://openlibrary.org/search.json", ({ request }) => {
subjects.push(new URL(request.url).searchParams.get("subject") ?? "");
return HttpResponse.json({ numFound: fixtureDocs.length, start: 0, docs: fixtureDocs });
});
}

describe("App", () => {
it("shows a loading indicator while the request is in flight", async () => {
server.use(
http.get("https://openlibrary.org/search.json", async () => {
Expand Down Expand Up @@ -47,32 +51,81 @@ describe("App", () => {
expect(await screen.findByText(/No books found/)).toBeInTheDocument();
});

it("fetches once more when the subject changes", async () => {
it("navigates to the next and previous book with the controls", async () => {
const user = userEvent.setup();
withProviders(<App />);
await screen.findByRole("heading", { name: "The Hobbit" });

fireEvent.change(screen.getByRole("combobox", { name: "Subject" }), {
target: { value: "mystery" },
});
await user.click(screen.getByRole("button", { name: "Show next book" }));
expect(
await screen.findByRole("heading", { name: "A Wizard of Earthsea" }),
).toBeInTheDocument();
expect(screen.getByText("2 / 3")).toBeInTheDocument();

await waitFor(() => expect(getSearchRequestCount()).toBe(2));
expect(JSON.parse(sessionStorage.getItem("t19.preferences") ?? "{}")).toMatchObject({
subject: "mystery",
});
await user.click(screen.getByRole("button", { name: "Show previous book" }));
expect(await screen.findByRole("heading", { name: "The Hobbit" })).toBeInTheDocument();
expect(screen.getByText("1 / 3")).toBeInTheDocument();
});

it("restores the selected subject from session storage", async () => {
sessionStorage.setItem("t19.preferences", JSON.stringify({ subject: "mystery" }));
it("jumps directly to a book from the list", async () => {
const user = userEvent.setup();
withProviders(<App />);
await screen.findByRole("heading", { name: "The Hobbit" });

expect(screen.getByRole("combobox", { name: "Subject" })).toHaveValue("mystery");
await waitFor(() => expect(getSearchRequestCount()).toBe(1));
await user.selectOptions(screen.getByLabelText("Jump to book"), "2");
expect(
await screen.findByRole("heading", { name: "The Left Hand of Darkness" }),
).toBeInTheDocument();
expect(screen.getByText("3 / 3")).toBeInTheDocument();
});

it("uses the default subject when stored preferences are corrupt", () => {
sessionStorage.setItem("t19.preferences", "not valid json");
it("does not refetch while navigating between books", async () => {
resetSearchRequestCount();
const user = userEvent.setup();
withProviders(<App />);
await screen.findByRole("heading", { name: "The Hobbit" });

await user.click(screen.getByRole("button", { name: "Show next book" }));
await screen.findByRole("heading", { name: "A Wizard of Earthsea" });
await user.click(screen.getByRole("button", { name: "Show previous book" }));
await screen.findByRole("heading", { name: "The Hobbit" });
await user.selectOptions(screen.getByLabelText("Jump to book"), "2");
await screen.findByRole("heading", { name: "The Left Hand of Darkness" });

expect(getSearchRequestCount()).toBe(1);
});

it("changes the subject, refetches once, and resets to the first book", async () => {
const subjects: string[] = [];
server.use(subjectCapturingHandler(subjects));
const user = userEvent.setup();
withProviders(<App />);
await screen.findByRole("heading", { name: "The Hobbit" });

await user.selectOptions(screen.getByRole("combobox", { name: "Subject" }), "mystery");
expect(await screen.findByRole("heading", { name: "The Hobbit" })).toBeInTheDocument();
expect(subjects).toEqual(["fantasy", "mystery"]);
});

it("restores the subject from sessionStorage", async () => {
const subjects: string[] = [];
server.use(subjectCapturingHandler(subjects));
sessionStorage.setItem("t19.preferences", JSON.stringify({ subject: "mystery" }));

withProviders(<App />);
await screen.findByRole("heading", { name: "The Hobbit" });
expect(subjects).toEqual(["mystery"]);
expect(screen.getByRole("combobox", { name: "Subject" })).toHaveValue("mystery");
});

it("falls back to the default subject on corrupt sessionStorage", async () => {
const subjects: string[] = [];
server.use(subjectCapturingHandler(subjects));
sessionStorage.setItem("t19.preferences", "{not valid json");

withProviders(<App />);
await screen.findByRole("heading", { name: "The Hobbit" });
expect(subjects).toEqual(["fantasy"]);
expect(screen.getByRole("combobox", { name: "Subject" })).toHaveValue("fantasy");
});

Expand Down
25 changes: 23 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { useState } from "react";
import { BookCard } from "./components/BookCard";
import { BookJumpList } from "./components/BookJumpList";
import { NavigationControls } from "./components/NavigationControls";
import { SubjectFilter } from "./components/SubjectFilter";
import { useBooks } from "./hooks/useBooks";
import { usePreferences } from "./hooks/usePreferences";
Expand All @@ -7,7 +10,14 @@ import "./App.css";
function App() {
const { subject, setSubject } = usePreferences();
const { books, isLoading, isError } = useBooks(subject);
const current = books[0];
const [index, setIndex] = useState(0);
const safeIndex = books.length > 0 ? Math.min(index, books.length - 1) : 0;
const current = books[safeIndex];

function handleSubjectChange(nextSubject: string) {
setSubject(nextSubject);
setIndex(0);
}

return (
<div className="app">
Expand All @@ -16,7 +26,7 @@ function App() {
<p>Browse reading material from OpenLibrary, one book at a time.</p>
</header>
<main className="app-main">
<SubjectFilter subject={subject} onSubjectChange={setSubject} />
<SubjectFilter subject={subject} onSubjectChange={handleSubjectChange} />
{isLoading && <p role="status">Loading books…</p>}
{isError && <p role="alert">Could not load books. Please try refreshing the page.</p>}
{!isLoading && !isError && books.length === 0 && (
Expand All @@ -25,6 +35,17 @@ function App() {
{current && (
<section className="book-viewer" aria-label="Book viewer">
<BookCard book={current} />
<NavigationControls
currentIndex={safeIndex}
totalCount={books.length}
onPrevious={() => setIndex(Math.max(0, safeIndex - 1))}
onNext={() => setIndex(Math.min(books.length - 1, safeIndex + 1))}
/>
<BookJumpList
titles={books.map((book) => book.title)}
currentIndex={safeIndex}
onSelect={setIndex}
/>
</section>
)}
</main>
Expand Down
51 changes: 51 additions & 0 deletions src/__snapshots__/App.test.tsx.snap
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,57 @@ exports[`App > matches the snapshot 1`] = `
</ul>
</div>
</article>
<nav
aria-label="Book navigation"
class="navigation-controls"
>
<button
aria-label="Show previous book"
disabled=""
type="button"
>
Previous
</button>
<p
aria-live="polite"
class="navigation-progress"
>
1
/
3
</p>
<button
aria-label="Show next book"
type="button"
>
Next
</button>
</nav>
<label
class="book-jump-list"
for="book-jump-list"
>
Jump to book
<select
id="book-jump-list"
>
<option
value="0"
>
The Hobbit
</option>
<option
value="1"
>
A Wizard of Earthsea
</option>
<option
value="2"
>
The Left Hand of Darkness
</option>
</select>
</label>
</section>
</main>
<footer
Expand Down
2 changes: 2 additions & 0 deletions src/test/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ beforeAll(() => server.listen({ onUnhandledRequest: "error" }));

afterEach(() => {
cleanup();
sessionStorage.clear();
localStorage.clear();
server.resetHandlers();
});

Expand Down