Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
37 changes: 18 additions & 19 deletions frontend/app/components/BookCard/BookCard.test.tsx
Original file line number Diff line number Diff line change
@@ -1,41 +1,40 @@
import { describe, expect, it } from "vitest";
import { render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { screen } from "@testing-library/react";
import { BookCard } from "~/components/BookCard/BookCard";
import { bookWithCover as book } from "~/test/fixtures/books";
import { createRoutesStub } from "react-router";
import { renderRoutes } from "~/test/renderRoutes";
import { loggedOut } from "~/test/session";

const Stub = createRoutesStub([
{
path: "/",
Component: () => <BookCard book={book} />,
},
]);
// BookCard contains FavoriteButton, which reads the session. Logged out, it
// sends no GraphQL requests, so no Apollo mocks are needed here.
vi.mock("~/api/auth", () => ({
authClient: { useSession: vi.fn(() => loggedOut) },
}));

const routes = [{ path: "/", Component: () => <BookCard book={book} /> }];

describe("BookCard", () => {
it("shows title, authors and year from the book prop", () => {
render(<Stub />);
renderRoutes(routes);

expect(
screen.getByRole("heading", { name: "The Blade Itself" }),
).toBeInTheDocument();
expect(screen.getByText("The Blade Itself")).toBeInTheDocument();
expect(screen.getByText("Joe Abercrombie")).toBeInTheDocument();
expect(screen.getByText("2001")).toBeInTheDocument();
});

it("links to the book's details page, keeping the current search", () => {
render(<Stub initialEntries={["/?q=fantasy"]} />);
renderRoutes(routes, { initialEntries: ["/?q=fantasy"] });

expect(screen.getByRole("link")).toHaveAttribute(
"href",
`/book/${book.id}?q=fantasy`,
);
expect(
screen.getByRole("link", { name: "View details for The Blade Itself" }),
).toHaveAttribute("href", `/book/${book.id}?q=fantasy`);
});

// Snapshot test: the rendered HTML is saved in __snapshots__/ the first time
// the test runs. Later runs fail if the markup changes unexpectedly.
// Run `pnpm test -u` to update the snapshot when a change is intended.
it("matches the snapshot", () => {
const { container } = render(<Stub />);
const { container } = renderRoutes(routes);

expect(container).toMatchSnapshot();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,79 @@

exports[`BookCard > matches the snapshot 1`] = `
<div>
<article
class="relative flex flex-col h-full box-border bg-card rounded-md border-2 border-transparent hover:border-border"
<div
class="group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl group relative h-full bg-card p-0 transition-all duration-200 hover:shadow-xl has-[a:focus-visible]:border-ring has-[a:focus-visible]:ring-[3px] has-[a:focus-visible]:ring-ring/50"
data-size="default"
data-slot="card"
>
<button
aria-label="Add The Blade Itself to favorites"
aria-pressed="false"
class="absolute right-2 top-2 flex items-center justify-center h-8 w-8 cursor-pointer text-2xl rounded-md border "
type="button"
>
+
</button>
<a
aria-label="View details for The Blade Itself"
class="flex flex-1 flex-col h-full w-full cursor-pointer box-border rounded-md p-6"
class="flex h-full flex-col cursor-pointer p-6 rounded-xl"
data-discover="true"
href="/book/OL8400950W"
href="/book/1"
>
<img
alt="Book cover of The Blade Itself"
class="w-full object-contain px-6 py-3"
src="https://covers.openlibrary.org/b/id/14543422-M.jpg?default=false"
/>
<section
class="mt-4 text-[0.9rem]"
<figure
class="mx-6 my-3 aspect-2/3 contain-content"
>
<picture
class="block h-full overflow-hidden"
>
<img
alt="Book cover of The Blade Itself"
class="size-full object-cover transition-transform duration-200 group-hover:scale-103"
src="https://covers.openlibrary.org/b/id/14543422-M.jpg?default=false"
/>
</picture>
</figure>
<div
class="group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing) mt-4"
data-slot="card-header"
>
<h3
class="mb-2 text-base"
<div
class="font-heading text-base leading-snug group-data-[size=sm]/card:text-sm font-bold"
data-slot="card-title"
>
The Blade Itself
</h3>
</div>
</div>
<div
class="px-(--card-spacing) mt-2"
data-slot="card-content"
>
<p>
Joe Abercrombie
</p>
<p>
2001
</p>
</section>
</div>
</a>
</article>
<button
aria-label="Add The Blade Itself to favorites"
aria-pressed="false"
class="group/button inline-flex shrink-0 items-center justify-center rounded-lg border bg-clip-padding font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 not-disabled:cursor-pointer border-border hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50 size-8 absolute right-2 top-2 z-10 bg-favorite-button text-xl"
data-slot="button"
tabindex="0"
type="button"
>
<svg
aria-hidden="true"
class="lucide lucide-heart"
fill="none"
height="24"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"
/>
</svg>
</button>
</div>
</div>
`;
31 changes: 23 additions & 8 deletions frontend/app/components/BookPagination/BookPagination.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,26 @@ const Stub = createRoutesStub([
},
]);

const currentPage = () =>
screen.getByRole("link", { current: "page" }).textContent;

describe("BookPagination", () => {
it("disables Previous on the first page and Next on the last page", () => {
const { unmount } = render(<Stub />);

expect(screen.getByRole("button", { name: "Previous" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Next" })).toBeEnabled();
const previous = () =>
screen.getByRole("link", { name: "Go to previous page" });
const next = () => screen.getByRole("link", { name: "Go to next page" });

expect(previous()).toHaveAttribute("aria-disabled", "true");
expect(next()).toHaveAttribute("aria-disabled", "false");

// A fresh render is needed because the page comes from the URL.
unmount();
render(<Stub initialEntries={["/?page=5"]} />);

expect(screen.getByRole("button", { name: "Previous" })).toBeEnabled();
expect(screen.getByRole("button", { name: "Next" })).toBeDisabled();
expect(previous()).toHaveAttribute("aria-disabled", "false");
expect(next()).toHaveAttribute("aria-disabled", "true");
});

it("moves to the next or previous page and scrolls to the top", async () => {
Expand All @@ -33,12 +40,20 @@ describe("BookPagination", () => {
const user = userEvent.setup();
render(<Stub initialEntries={["/?page=3"]} />);

await user.click(screen.getByRole("button", { name: "Next" }));
await waitFor(() => expect(screen.getByText("4 of 5")).toBeInTheDocument());
await user.click(screen.getByRole("link", { name: "Go to next page" }));
await waitFor(() => expect(currentPage()).toBe("4"));

await user.click(screen.getByRole("button", { name: "Previous" }));
await waitFor(() => expect(screen.getByText("3 of 5")).toBeInTheDocument());
await user.click(screen.getByRole("link", { name: "Go to previous page" }));
await waitFor(() => expect(currentPage()).toBe("3"));

expect(scrollTo).toHaveBeenCalledTimes(2);
});

it("keeps the search and filters when changing page", () => {
render(<Stub initialEntries={["/?q=blade&genres=Fantasy&page=2"]} />);

expect(
screen.getByRole("link", { name: "Go to next page" }),
).toHaveAttribute("href", "/?q=blade&genres=Fantasy&page=3");
});
});
146 changes: 119 additions & 27 deletions frontend/app/components/FavoriteButton/FavoriteButton.test.tsx
Original file line number Diff line number Diff line change
@@ -1,48 +1,140 @@
import { describe, expect, it } from "vitest";
import { render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { authClient } from "~/api/auth";
import { FavoriteButton } from "~/components/FavoriteButton/FavoriteButton";
import { Toaster } from "~/components/ui/Toast";
import {
ADD_FAVORITE_BOOK,
FAVORITE_BOOK_IDS,
REMOVE_FAVORITE_BOOK,
} from "~/hooks/useFavoriteBooks";
import { bookWithCover as book } from "~/test/fixtures/books";
import { renderRoutes } from "~/test/renderRoutes";
import { loggedIn, loggedOut } from "~/test/session";

describe("FavoriteButton", () => {
it("is not pressed when the book is not a favorite", () => {
render(<FavoriteButton book={book} />);
vi.mock("~/api/auth", () => ({
authClient: { useSession: vi.fn(() => loggedOut) },
}));

const button = screen.getByRole("button", {
name: "Add The Blade Itself to favorites",
});
expect(button).toHaveAttribute("aria-pressed", "false");
});
const routes = [
{
path: "/",
Component: () => (
<>
<FavoriteButton book={book} />
<Toaster />
</>
),
},
];

// The favorites are stored in the backend. The button reads the ids of the
// user's favorite books, and reads them again after adding or removing one.
const favoriteIds = (ids: number[]) => ({
request: { query: FAVORITE_BOOK_IDS },
result: { data: { favoriteBookIds: ids } },
});

it("adds and removes the book in localStorage when clicked", async () => {
describe("FavoriteButton", () => {
it("asks a logged out user to log in instead of saving", async () => {
const user = userEvent.setup();
render(<FavoriteButton book={book} />);
const button = screen.getByRole("button");
renderRoutes(routes);

await user.click(button);
await user.click(
screen.getByRole("button", { name: "Add The Blade Itself to favorites" }),
);

expect(button).toHaveAttribute("aria-pressed", "true");
expect(button).toHaveAccessibleName(
"Remove The Blade Itself from favorites",
expect(
await screen.findByRole("alertdialog", {
name: "Log in to save favorites",
}),
).toBeInTheDocument();
expect(screen.getByRole("link", { name: "Log in" })).toHaveAttribute(
"href",
"/login",
);
});

const favorites = localStorage.getItem("favorites")!;
it("adds the book to the user's favorites", async () => {
vi.mocked(authClient.useSession).mockReturnValue(loggedIn);
const user = userEvent.setup();
renderRoutes(routes, {
mocks: [
favoriteIds([]),
{
request: { query: ADD_FAVORITE_BOOK, variables: { bookId: 1 } },
result: {
data: { addFavoriteBook: { __typename: "Book", id: 1 } },
},
},
favoriteIds([1]),
],
});

expect(JSON.parse(favorites)).toEqual([book.id]);
await user.click(
screen.getByRole("button", { name: "Add The Blade Itself to favorites" }),
);

await user.click(button);
expect(
await screen.findByRole("button", {
name: "Remove The Blade Itself from favorites",
}),
).toHaveAttribute("aria-pressed", "true");
});

const updatedFavorites = localStorage.getItem("favorites")!;
it("removes a favorite book from the user's favorites", async () => {
vi.mocked(authClient.useSession).mockReturnValue(loggedIn);
const user = userEvent.setup();
renderRoutes(routes, {
mocks: [
favoriteIds([1]),
{
request: { query: REMOVE_FAVORITE_BOOK, variables: { bookId: 1 } },
result: { data: { removeFavoriteBook: true } },
},
favoriteIds([]),
],
});

expect(button).toHaveAttribute("aria-pressed", "false");
expect(JSON.parse(updatedFavorites)).toEqual([]);
// Shown as a favorite once the user's favorites have loaded.
await user.click(
await screen.findByRole("button", {
name: "Remove The Blade Itself from favorites",
}),
);

expect(
await screen.findByRole("button", {
name: "Add The Blade Itself to favorites",
}),
).toHaveAttribute("aria-pressed", "false");
});

it("reads favorites saved in localStorage when it mounts", () => {
localStorage.setItem("favorites", JSON.stringify([book.id]));
it("shows an error message when saving fails", async () => {
vi.mocked(authClient.useSession).mockReturnValue(loggedIn);
const user = userEvent.setup();
renderRoutes(routes, {
mocks: [
favoriteIds([]),
{
request: { query: ADD_FAVORITE_BOOK, variables: { bookId: 1 } },
error: new Error("Network error"),
},
],
});

render(<FavoriteButton book={book} />);
await user.click(
screen.getByRole("button", { name: "Add The Blade Itself to favorites" }),
);

expect(screen.getByRole("button")).toHaveAttribute("aria-pressed", "true");
expect(
await screen.findByText(
"Could not update your favorites. Please try again.",
),
).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Add The Blade Itself to favorites" }),
).toHaveAttribute("aria-pressed", "false");
});
});
Loading