From ff4d6a940536ce61d8972de0c57d9ba062572d54 Mon Sep 17 00:00:00 2001 From: Johannes Horn Date: Tue, 3 Nov 2026 14:12:51 +0100 Subject: [PATCH] test: rewrite tests with Apollo MockedProvider Fix outdated component tests (genres param, link-based pagination, favorites stored in the backend) and add page tests for the home and book pages. Closes #33. --- .../app/components/BookCard/BookCard.test.tsx | 37 +++-- .../__snapshots__/BookCard.test.tsx.snap | 83 +++++++--- .../BookPagination/BookPagination.test.tsx | 31 +++- .../FavoriteButton/FavoriteButton.test.tsx | 146 ++++++++++++++---- .../home/BookFilters/BookFilters.test.tsx | 4 +- .../home/SearchBar/SearchBar.test.tsx | 2 +- frontend/app/hooks/useBook.ts | 2 +- frontend/app/hooks/useSearchBooks.ts | 2 +- .../app/routes/book/selectedBook.test.tsx | 73 +++++++++ frontend/app/routes/home.test.tsx | 138 +++++++++++++++++ frontend/app/test/fixtures/books.ts | 56 ++++++- frontend/app/test/mocks.ts | 45 ++++++ frontend/app/test/renderRoutes.tsx | 31 ++++ frontend/app/test/session.ts | 23 +++ 14 files changed, 587 insertions(+), 86 deletions(-) create mode 100644 frontend/app/routes/book/selectedBook.test.tsx create mode 100644 frontend/app/routes/home.test.tsx create mode 100644 frontend/app/test/mocks.ts create mode 100644 frontend/app/test/renderRoutes.tsx create mode 100644 frontend/app/test/session.ts diff --git a/frontend/app/components/BookCard/BookCard.test.tsx b/frontend/app/components/BookCard/BookCard.test.tsx index b2e35056..72a9490e 100644 --- a/frontend/app/components/BookCard/BookCard.test.tsx +++ b/frontend/app/components/BookCard/BookCard.test.tsx @@ -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 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: () => }]; describe("BookCard", () => { it("shows title, authors and year from the book prop", () => { - render(); + 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(); + 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(); + const { container } = renderRoutes(routes); expect(container).toMatchSnapshot(); }); diff --git a/frontend/app/components/BookCard/__snapshots__/BookCard.test.tsx.snap b/frontend/app/components/BookCard/__snapshots__/BookCard.test.tsx.snap index 264b3505..5b76b799 100644 --- a/frontend/app/components/BookCard/__snapshots__/BookCard.test.tsx.snap +++ b/frontend/app/components/BookCard/__snapshots__/BookCard.test.tsx.snap @@ -2,44 +2,79 @@ exports[`BookCard > matches the snapshot 1`] = ` +

Joe Abercrombie

2001

- +
- + + `; diff --git a/frontend/app/components/BookPagination/BookPagination.test.tsx b/frontend/app/components/BookPagination/BookPagination.test.tsx index 2995348d..8aabf9fa 100644 --- a/frontend/app/components/BookPagination/BookPagination.test.tsx +++ b/frontend/app/components/BookPagination/BookPagination.test.tsx @@ -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(); - 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(); - 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 () => { @@ -33,12 +40,20 @@ describe("BookPagination", () => { const user = userEvent.setup(); render(); - 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(); + + expect( + screen.getByRole("link", { name: "Go to next page" }), + ).toHaveAttribute("href", "/?q=blade&genres=Fantasy&page=3"); + }); }); diff --git a/frontend/app/components/FavoriteButton/FavoriteButton.test.tsx b/frontend/app/components/FavoriteButton/FavoriteButton.test.tsx index 1021addb..7c29c9f1 100644 --- a/frontend/app/components/FavoriteButton/FavoriteButton.test.tsx +++ b/frontend/app/components/FavoriteButton/FavoriteButton.test.tsx @@ -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(); +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: () => ( + <> + + + + ), + }, +]; + +// 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(); - 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(); + 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"); }); }); diff --git a/frontend/app/components/home/BookFilters/BookFilters.test.tsx b/frontend/app/components/home/BookFilters/BookFilters.test.tsx index 6cacb257..28eac5a2 100644 --- a/frontend/app/components/home/BookFilters/BookFilters.test.tsx +++ b/frontend/app/components/home/BookFilters/BookFilters.test.tsx @@ -42,7 +42,7 @@ const Stub = createRoutesStub([ describe("FilterBooksSection", () => { it("shows the selected genres from the URL", () => { - render(); + render(); expect(screen.getByText("Fantasy")).toBeInTheDocument(); expect(screen.getByText("Romance")).toBeInTheDocument(); @@ -50,7 +50,7 @@ describe("FilterBooksSection", () => { it("adds a selected genre to the URL", async () => { const user = userEvent.setup(); - render(); + render(); await user.type(screen.getByLabelText("Genres"), "Sci"); await user.click( diff --git a/frontend/app/components/home/SearchBar/SearchBar.test.tsx b/frontend/app/components/home/SearchBar/SearchBar.test.tsx index 9140bce5..5bea8f69 100644 --- a/frontend/app/components/home/SearchBar/SearchBar.test.tsx +++ b/frontend/app/components/home/SearchBar/SearchBar.test.tsx @@ -51,7 +51,7 @@ describe("SearchBar", () => { }); it("shows the number of active filters", () => { - render(); + render(); expect( screen.getByRole("button", { name: "Filter books" }), diff --git a/frontend/app/hooks/useBook.ts b/frontend/app/hooks/useBook.ts index 6e0bcb22..3c3b5e90 100644 --- a/frontend/app/hooks/useBook.ts +++ b/frontend/app/hooks/useBook.ts @@ -60,4 +60,4 @@ function useBook({ id }: { id: string }) { type Book = NonNullable["book"]>; -export { useBook, type Book }; +export { useBook, BOOK, type Book }; diff --git a/frontend/app/hooks/useSearchBooks.ts b/frontend/app/hooks/useSearchBooks.ts index f923cead..13425f89 100644 --- a/frontend/app/hooks/useSearchBooks.ts +++ b/frontend/app/hooks/useSearchBooks.ts @@ -107,4 +107,4 @@ type SearchBook = NonNullable< ReturnType["books"] >[number]; -export { useSearchBooks, type SearchBook }; +export { useSearchBooks, SEARCH_BOOKS, type SearchBook }; diff --git a/frontend/app/routes/book/selectedBook.test.tsx b/frontend/app/routes/book/selectedBook.test.tsx new file mode 100644 index 00000000..d83c0f1b --- /dev/null +++ b/frontend/app/routes/book/selectedBook.test.tsx @@ -0,0 +1,73 @@ +import { describe, expect, it, vi } from "vitest"; +import { screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import SelectedBookPage from "~/routes/book/selectedBook"; +import { apiBook } from "~/test/fixtures/books"; +import { bookMock, searchBooksMock } from "~/test/mocks"; +import { renderRoutes } from "~/test/renderRoutes"; +import { loggedOut } from "~/test/session"; + +// FavoriteButton reads the session. Logged out, it sends no GraphQL requests. +vi.mock("~/api/auth", () => ({ + authClient: { useSession: vi.fn(() => loggedOut) }, +})); + +const routes = [{ path: "/book/:bookId", Component: SelectedBookPage }]; + +describe("SelectedBookPage", () => { + // The page loads the book itself, and the current search results so the + // user can browse to the previous and next book. + it("shows the book's details from the API", async () => { + renderRoutes(routes, { + initialEntries: ["/book/1"], + mocks: [bookMock(1, apiBook), searchBooksMock()], + }); + + expect(await screen.findByText(/Logen Ninefingers/)).toBeInTheDocument(); + // The title is shown both in the breadcrumb and on the page. + expect(screen.getAllByText("The Blade Itself")).toHaveLength(2); + expect(screen.getByText("Joe Abercrombie")).toBeInTheDocument(); + expect(screen.getByText("Published: 2006")).toBeInTheDocument(); + expect(screen.getByText("Language: English")).toBeInTheDocument(); + expect(screen.getByText("ISBN: 9781591025948")).toBeInTheDocument(); + }); + + it("shows a message when the book does not exist", async () => { + renderRoutes(routes, { + initialEntries: ["/book/999"], + mocks: [bookMock(999, null), searchBooksMock()], + }); + + expect( + await screen.findByRole("heading", { name: "Book Not Found" }), + ).toBeInTheDocument(); + }); + + it("browses to the next book in the search results", async () => { + const user = userEvent.setup(); + renderRoutes(routes, { + initialEntries: ["/book/1"], + mocks: [ + bookMock(1, apiBook), + searchBooksMock(), + bookMock(2, { + ...apiBook, + id: 2, + title: "Before They Are Hanged", + description: "The second book in The First Law trilogy.", + }), + ], + }); + + // The Blade Itself is the first search result, so there is no previous book. + expect( + await screen.findByRole("link", { name: "Go to previous book" }), + ).toHaveAttribute("aria-disabled", "true"); + + await user.click(screen.getByRole("link", { name: "Go to next book" })); + + expect( + await screen.findByText("The second book in The First Law trilogy."), + ).toBeInTheDocument(); + }); +}); diff --git a/frontend/app/routes/home.test.tsx b/frontend/app/routes/home.test.tsx new file mode 100644 index 00000000..b6a96ad2 --- /dev/null +++ b/frontend/app/routes/home.test.tsx @@ -0,0 +1,138 @@ +import { describe, expect, it, vi } from "vitest"; +import { screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import HomePage from "~/routes/home"; +import SelectedBookPage from "~/routes/book/selectedBook"; +import { SEARCH_BOOKS } from "~/hooks/useSearchBooks"; +import { apiBook } from "~/test/fixtures/books"; +import { bookMock, searchBooksMock } from "~/test/mocks"; +import { renderRoutes } from "~/test/renderRoutes"; +import { loggedOut } from "~/test/session"; + +// FavoriteButton on each book card reads the session. Logged out, it sends +// no GraphQL requests. +vi.mock("~/api/auth", () => ({ + authClient: { useSession: vi.fn(() => loggedOut) }, +})); + +// Every book card is a link to the book's details page. +const findBookLinks = () => + screen.findAllByRole("link", { name: /View details for/ }); + +const routes = [ + { path: "/", Component: HomePage }, + { path: "/book/:bookId", Component: SelectedBookPage }, +]; + +describe("HomePage", () => { + it("shows the books and the number of results from the API", async () => { + renderRoutes(routes, { mocks: [searchBooksMock()] }); + + expect(await findBookLinks()).toHaveLength(3); + expect(screen.getByText("Good Omens")).toBeInTheDocument(); + expect( + screen.getByText("Terry Pratchett, Neil Gaiman"), + ).toBeInTheDocument(); + expect(screen.getByText("3 results")).toBeInTheDocument(); + }); + + // Searching, filtering and sorting happen in the backend on the whole + // result set, so the page has to pass all of it on to the API. The mock + // only answers a request with exactly these variables. + it("sends the search, filters, sort and page from the URL to the API", async () => { + renderRoutes(routes, { + initialEntries: [ + "/?q=blade&genres=Fantasy&genres=Romance&language=English" + + "&bookFormat=Paperback&minPages=100&maxPages=500" + + "&sort=rating_desc&page=2", + ], + mocks: [ + searchBooksMock( + { + title: "blade", + genres: ["Fantasy", "Romance"], + language: "English", + bookFormat: "Paperback", + minPages: 100, + maxPages: 500, + sortBy: "RATING", + sortDirection: "DESC", + limit: 12, + offset: 12, + }, + undefined, + 15, + ), + ], + }); + + expect(await screen.findByText("15 results")).toBeInTheDocument(); + expect(screen.getByRole("link", { current: "page" })).toHaveTextContent( + "2", + ); + }); + + it("tells the user when no books match the search", async () => { + renderRoutes(routes, { + initialEntries: ["/?q=zzzz"], + mocks: [searchBooksMock({ title: "zzzz", limit: 12, offset: 0 }, [])], + }); + + expect( + await screen.findByText("No books found for this search"), + ).toBeInTheDocument(); + expect(screen.getByText("0 results")).toBeInTheDocument(); + }); + + it("shows an error message when the API request fails", async () => { + renderRoutes(routes, { + mocks: [ + { + request: { + query: SEARCH_BOOKS, + variables: { title: "", limit: 12, offset: 0 }, + }, + error: new Error("Network error"), + }, + ], + }); + + expect( + await screen.findByText( + "Sorry, there was an error loading the books. Please try again later.", + ), + ).toBeInTheDocument(); + }); + + it("opens a book's details and goes back to the same search", async () => { + const user = userEvent.setup(); + const variables = { title: "blade", limit: 12, offset: 0 }; + renderRoutes(routes, { + initialEntries: ["/?q=blade"], + // Each request is mocked once: the search results are reused from + // Apollo's cache on the details page and when going back. + mocks: [searchBooksMock(variables), bookMock(1, apiBook)], + }); + + await user.click( + await screen.findByRole("link", { + name: "View details for The Blade Itself", + }), + ); + + expect(await screen.findByText(/Logen Ninefingers/)).toBeInTheDocument(); + expect( + screen.queryByRole("link", { name: /View details for/ }), + ).not.toBeInTheDocument(); + + await user.click( + // Rendered as a link, but exposed with role="button" by the Button component. + screen.getByRole("button", { name: "Go back to search results" }), + ); + + expect(await findBookLinks()).toHaveLength(3); + expect( + screen.getByRole("searchbox", { name: "Search for books" }), + ).toHaveValue("blade"); + }); +}); diff --git a/frontend/app/test/fixtures/books.ts b/frontend/app/test/fixtures/books.ts index 30b38447..0a3e8aa9 100644 --- a/frontend/app/test/fixtures/books.ts +++ b/frontend/app/test/fixtures/books.ts @@ -1,9 +1,13 @@ import type { Book } from "~/hooks/useBook"; +import type { + BookQuery, + SearchBooksQuery, +} from "~/api/types/graphql.generated"; -// Sample book for component tests. +// A book as components receive it, after the hooks have mapped the API response. const bookWithCover: Book = { __typename: "Book", - id: "OL8400950W", + id: "1", isbn: "9781591025948", title: "The Blade Itself", description: null, @@ -16,4 +20,50 @@ const bookWithCover: Book = { "https://covers.openlibrary.org/b/id/14543422-M.jpg?default=false", }; -export { bookWithCover }; +type ApiSearchBook = SearchBooksQuery["searchBooks"]["books"][number]; + +// Books as the GraphQL API returns them from the searchBooks query. +const apiSearchBooks: ApiSearchBook[] = [ + { + __typename: "Book", + id: 1, + title: "The Blade Itself", + author: "Joe Abercrombie", + publishDate: "2006-05-04", + coverImgUrl: null, + }, + { + __typename: "Book", + id: 2, + title: "Before They Are Hanged", + author: "Joe Abercrombie", + publishDate: "2007-03-15", + coverImgUrl: null, + }, + { + __typename: "Book", + id: 3, + title: "Good Omens", + author: "Terry Pratchett, Neil Gaiman", + publishDate: "1990", + coverImgUrl: null, + }, +]; + +// The first search result as the API returns it from the book query. +const apiBook: NonNullable = { + __typename: "Book", + id: 1, + isbn: "9781591025948", + title: "The Blade Itself", + author: "Joe Abercrombie", + language: "English", + publishDate: "2006-05-04", + coverImgUrl: null, + description: + "Logen Ninefingers, infamous barbarian, has finally run out of luck.", + rating: 4.2, + numRatings: 1234, +}; + +export { apiBook, apiSearchBooks, bookWithCover }; diff --git a/frontend/app/test/mocks.ts b/frontend/app/test/mocks.ts new file mode 100644 index 00000000..cce0752e --- /dev/null +++ b/frontend/app/test/mocks.ts @@ -0,0 +1,45 @@ +import type { MockLink } from "@apollo/client/testing"; +import type { + BookQuery, + SearchBooksQueryVariables, +} from "~/api/types/graphql.generated"; +import { BOOK } from "~/hooks/useBook"; +import { SEARCH_BOOKS } from "~/hooks/useSearchBooks"; +import { BOOK_PAGE_LIMIT } from "~/lib/constants"; +import { apiSearchBooks } from "~/test/fixtures/books"; + +// The variables the pages send for "/" (no search, filters, sort or page). +const defaultSearchVariables: SearchBooksQueryVariables = { + title: "", + limit: BOOK_PAGE_LIMIT, + offset: 0, +}; + +// A searchBooks response. Only matches a request with exactly these variables. +function searchBooksMock( + variables: SearchBooksQueryVariables = defaultSearchVariables, + books = apiSearchBooks, + totalCount = books.length, +): MockLink.MockedResponse { + return { + request: { query: SEARCH_BOOKS, variables }, + result: { + data: { + searchBooks: { __typename: "BookSearchResult", totalCount, books }, + }, + }, + }; +} + +// A book response for the book details page. +function bookMock( + id: number, + book: BookQuery["book"], +): MockLink.MockedResponse { + return { + request: { query: BOOK, variables: { id } }, + result: { data: { book } }, + }; +} + +export { bookMock, defaultSearchVariables, searchBooksMock }; diff --git a/frontend/app/test/renderRoutes.tsx b/frontend/app/test/renderRoutes.tsx new file mode 100644 index 00000000..7250745d --- /dev/null +++ b/frontend/app/test/renderRoutes.tsx @@ -0,0 +1,31 @@ +import { render } from "@testing-library/react"; +import { MockedProvider } from "@apollo/client/testing/react"; +import type { MockLink } from "@apollo/client/testing"; +import { createRoutesStub } from "react-router"; + +type Routes = Parameters[0]; + +interface RenderRoutesOptions { + initialEntries?: string[]; + // GraphQL responses for the queries the routes send. A request without a + // matching mock (same query and variables) fails, so tests also check that + // components ask the API for the right data. + mocks?: MockLink.MockedResponse[]; +} + +// Renders routes inside an in-memory router and a mocked Apollo Client, +// so no real requests are sent to the backend. +function renderRoutes( + routes: Routes, + { initialEntries = ["/"], mocks = [] }: RenderRoutesOptions = {}, +) { + const Stub = createRoutesStub(routes); + + return render( + + + , + ); +} + +export { renderRoutes }; diff --git a/frontend/app/test/session.ts b/frontend/app/test/session.ts new file mode 100644 index 00000000..c3444907 --- /dev/null +++ b/frontend/app/test/session.ts @@ -0,0 +1,23 @@ +import type { authClient } from "~/api/auth"; + +type Session = ReturnType; + +// What authClient.useSession() returns in tests. Tests mock "~/api/auth" so +// no requests are sent to the auth server. Only the fields our components +// read are filled in, hence the casts. +const loggedOut = { + data: null, + isPending: false, + error: null, +} as unknown as Session; + +const loggedIn = { + data: { + user: { id: "user-1", name: "Test User", email: "test@example.com" }, + session: { id: "session-1", userId: "user-1" }, + }, + isPending: false, + error: null, +} as unknown as Session; + +export { loggedIn, loggedOut };