From 46975ed44f307a95f573bc3b4d1ca68377c32bf9 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Mon, 26 Oct 2026 12:44:03 +0100 Subject: [PATCH 1/6] Added and corrected frontend tests --- frontend/src/tests/App.test.tsx | 63 ++++ frontend/src/tests/Header.test.tsx | 41 +++ frontend/src/tests/MyMatchesPage.test.tsx | 70 +++- frontend/src/tests/PlantCard.test.tsx | 90 ++++++ frontend/src/tests/PlantMatchPage.test.tsx | 47 ++- frontend/src/tests/PlantPreferences.test.tsx | 106 +++++++ frontend/src/tests/Profile.test.tsx | 86 ++++- frontend/src/tests/ThemeToggle.test.tsx | 32 ++ frontend/src/tests/UserContext.test.tsx | 146 +++++++++ .../__snapshots__/ExplorePage.test.tsx.snap | 300 ++++++++++++++++++ frontend/vite.config.ts | 5 + 11 files changed, 964 insertions(+), 22 deletions(-) create mode 100644 frontend/src/tests/App.test.tsx create mode 100644 frontend/src/tests/Header.test.tsx create mode 100644 frontend/src/tests/PlantCard.test.tsx create mode 100644 frontend/src/tests/PlantPreferences.test.tsx create mode 100644 frontend/src/tests/ThemeToggle.test.tsx create mode 100644 frontend/src/tests/UserContext.test.tsx diff --git a/frontend/src/tests/App.test.tsx b/frontend/src/tests/App.test.tsx new file mode 100644 index 00000000..05003239 --- /dev/null +++ b/frontend/src/tests/App.test.tsx @@ -0,0 +1,63 @@ +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { MemoryRouter } from "react-router-dom"; +import { describe, it, expect, vi } from "vitest"; +import App from "../App"; +import { ROUTES } from "../AppRoutes"; + +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ t: (key: string) => key }), +})); + +// The pages have their own tests, so they are replaced by stand-ins here. +// This keeps the test about which page each route shows. +vi.mock("../pages/plantMatch/PlantMatchPage.tsx", () => ({ + default: () =>

plant match page

, +})); +vi.mock("../pages/explorePlants/ExplorePlants.tsx", () => ({ + default: () =>

explore page

, +})); +vi.mock("../pages/myMatches/MyMatchesPage.tsx", () => ({ + default: () =>

my matches page

, +})); +vi.mock("../pages/profile/Profile.tsx", () => ({ + default: () =>

profile page

, +})); +vi.mock("../components/sidebarButtons/LanguageSwitcher", () => ({ + default: () => null, +})); + +function renderApp(route: string) { + render( + + + , + ); +} + +describe("App", () => { + it.each([ + [ROUTES.plantMatch, "plant match page"], + [ROUTES.explore, "explore page"], + [ROUTES.myMatches, "my matches page"], + [ROUTES.profile, "profile page"], + ])("shows the right page for %s", async (route, page) => { + renderApp(route); + + expect(await screen.findByText(page)).toBeInTheDocument(); + }); + + it("opens the sidebar from the header and closes it again", async () => { + const user = userEvent.setup(); + renderApp(ROUTES.plantMatch); + const header = document.querySelector(".header"); + + expect(header).toHaveAttribute("data-sidebar-open", "false"); + await user.click(screen.getByRole("button", { name: "Open sidebar" })); + expect(header).toHaveAttribute("data-sidebar-open", "true"); + + await user.click(screen.getByRole("link", { name: "sidebar.profile" })); + expect(await screen.findByText("profile page")).toBeInTheDocument(); + expect(header).toHaveAttribute("data-sidebar-open", "false"); + }); +}); diff --git a/frontend/src/tests/Header.test.tsx b/frontend/src/tests/Header.test.tsx new file mode 100644 index 00000000..7293b4c3 --- /dev/null +++ b/frontend/src/tests/Header.test.tsx @@ -0,0 +1,41 @@ +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { MemoryRouter } from "react-router-dom"; +import { describe, it, expect, vi } from "vitest"; +import Header from "../components/header/Header"; +import { ROUTES } from "../AppRoutes"; + +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ t: (key: string) => key }), +})); + +function renderHeader(route: string, onOpenSidebar = vi.fn()) { + render( + +
+ , + ); + return onOpenSidebar; +} + +describe("Header", () => { + it.each([ + [ROUTES.plantMatch, "sidebar.plantMatch"], + [ROUTES.explore, "sidebar.explorePlants"], + [ROUTES.myMatches, "sidebar.myMatches"], + [ROUTES.profile, "sidebar.profile"], + ["/unknown-page", "sidebar.plantMatch"], + ])("shows the title for %s", (route, title) => { + renderHeader(route); + + expect(screen.getByRole("heading", { name: title })).toBeInTheDocument(); + }); + + it("opens the sidebar with the menu button", async () => { + const onOpenSidebar = renderHeader(ROUTES.plantMatch); + + await userEvent.click(screen.getByRole("button", { name: "Open sidebar" })); + + expect(onOpenSidebar).toHaveBeenCalledTimes(1); + }); +}); diff --git a/frontend/src/tests/MyMatchesPage.test.tsx b/frontend/src/tests/MyMatchesPage.test.tsx index 47b2d2c8..553be19d 100644 --- a/frontend/src/tests/MyMatchesPage.test.tsx +++ b/frontend/src/tests/MyMatchesPage.test.tsx @@ -1,24 +1,80 @@ -import { cleanup, render, screen } from "@testing-library/react"; -import { afterEach } from "vitest"; -import { describe, it, expect, vi } from "vitest"; +import { fireEvent, render, screen } from "@testing-library/react"; +import { beforeEach, describe, it, expect, vi } from "vitest"; import MyMatchesPage from "../pages/myMatches/MyMatchesPage"; +import type { Plant } from "../types/Plant"; +const { removeUserMatch, useUser } = vi.hoisted(() => ({ + removeUserMatch: vi.fn(), + useUser: vi.fn(), +})); +vi.mock("@apollo/client/react", () => ({ + useMutation: () => [removeUserMatch], +})); +vi.mock("../context/UserContext", () => ({ useUser })); vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key, }), })); -afterEach(() => { - cleanup(); +const orchid: Plant = { + id: "1", + name: "Orchid", + imageURL: null, + scientificName: null, + description: null, + watering: "Average", + sunlight: ["Full sun"], + careLevel: "Easy", +}; + +function mockUser(matchedPlants: Plant[], loading = false) { + useUser.mockReturnValue({ + userId: "user-1", + user: { + id: "user-1", + name: null, + description: null, + profilePicture: "default", + preferences: [], + matchedPlants, + }, + loading, + }); +} + +beforeEach(() => { + removeUserMatch.mockClear(); }); describe("myMatchesPage", () => { it("shows a message when there are no matches", () => { + mockUser([]); render(); + expect(screen.getByText("myMatchesPage.noMatches")).toBeInTheDocument(); + }); + + it("shows the loading state instead of the no matches message", () => { + mockUser([], true); + render(); + + expect(screen.getByText("myMatchesPage.loading")).toBeInTheDocument(); expect( - screen.getByRole("heading", { name: "myMatchesPage.noMatches" }), - ).toBeInTheDocument(); + screen.queryByText("myMatchesPage.noMatches"), + ).not.toBeInTheDocument(); + }); + + it("shows the saved matches and removes one", () => { + mockUser([orchid]); + render(); + + expect(screen.getAllByText("Orchid").length).toBeGreaterThan(0); + fireEvent.click( + screen.getByRole("button", { name: "myMatchesPage.removeMatch" }), + ); + expect(removeUserMatch).toHaveBeenCalledWith({ + variables: { userId: "user-1", plantId: "1" }, + }); }); }); diff --git a/frontend/src/tests/PlantCard.test.tsx b/frontend/src/tests/PlantCard.test.tsx new file mode 100644 index 00000000..75b957da --- /dev/null +++ b/frontend/src/tests/PlantCard.test.tsx @@ -0,0 +1,90 @@ +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, it, expect, vi } from "vitest"; +import PlantCard from "../components/plantCard/PlantCard"; + +const { useUser } = vi.hoisted(() => ({ useUser: vi.fn() })); +vi.mock("../context/UserContext", () => ({ useUser })); +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ t: (key: string) => key }), +})); + +useUser.mockReturnValue({ userId: null, user: null, loading: false }); + +// The text of every preference chip on the card +const chips = () => + Array.from(document.querySelectorAll(".plant-preference-chip")).map( + (chip) => chip.textContent, + ); + +describe("PlantCard", () => { + it("shows the full plant on the back after clicking information", async () => { + const user = userEvent.setup(); + const onInfo = vi.fn(); + const { container } = render( + , + ); + + expect(screen.getByRole("img", { name: "Orchid" })).toHaveAttribute( + "src", + "orchid.png", + ); + + await user.click( + screen.getByRole("button", { name: "plantCard.information" }), + ); + + expect(onInfo).toHaveBeenCalledTimes(1); + expect(container.firstChild).toHaveClass("is-flipped"); + expect(screen.getByText("Orchidaceae, Phalaenopsis")).toBeInTheDocument(); + expect(screen.getByText("A flowering plant")).toBeInTheDocument(); + expect(screen.getByText("Full sun, Part shade")).toBeInTheDocument(); + + await user.click(screen.getByRole("button", { name: "plantCard.back" })); + + expect(container.firstChild).not.toHaveClass("is-flipped"); + }); + + it("shows unknown for missing facts and no image", () => { + const { container } = render(); + + expect(screen.queryByRole("img")).not.toBeInTheDocument(); + expect(container.querySelector(".plant-card-image-missing")).not.toBeNull(); + expect(screen.getAllByText("plantCard.unknown")).toHaveLength(3); + expect(screen.queryByRole("group")).not.toBeInTheDocument(); + }); + + it.each([ + ["Minimum", [], null, ["preferences.minimumWater"]], + ["Frequent", [], null, ["preferences.frequentWater"]], + [null, ["Filtered shade"], null, ["preferences.filteredShade"]], + [null, ["Part sun/part shade"], null, ["preferences.partShade"]], + [null, [], "Moderate", ["preferences.mediumCare"]], + [null, [], "Medium", ["preferences.mediumCare"]], + [null, [], "High", ["preferences.hardCare"]], + ])( + "turns watering %s, sunlight %j and care %s into preference chips", + (watering, sunlight, careLevel, expected) => { + render( + , + ); + + expect(chips()).toEqual(expected); + }, + ); +}); diff --git a/frontend/src/tests/PlantMatchPage.test.tsx b/frontend/src/tests/PlantMatchPage.test.tsx index 7ea3d390..a5792aaf 100644 --- a/frontend/src/tests/PlantMatchPage.test.tsx +++ b/frontend/src/tests/PlantMatchPage.test.tsx @@ -2,8 +2,16 @@ import { fireEvent, render, screen } from "@testing-library/react"; import { beforeEach, describe, it, expect, vi } from "vitest"; import PlantMatchPage from "../pages/plantMatch/PlantMatchPage"; -const { useQuery } = vi.hoisted(() => ({ useQuery: vi.fn() })); -vi.mock("@apollo/client/react", () => ({ useQuery })); +const { useQuery, addUserMatch, useUser } = vi.hoisted(() => ({ + useQuery: vi.fn(), + addUserMatch: vi.fn(), + useUser: vi.fn(), +})); +vi.mock("@apollo/client/react", () => ({ + useQuery, + useMutation: () => [addUserMatch], +})); +vi.mock("../context/UserContext", () => ({ useUser })); vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }), })); @@ -19,8 +27,25 @@ const plants = ["Hydrangea", "Orchid"].map((name, id) => ({ careLevel: "Easy", })); +// A user with the given saved preferences and no matches yet +function mockUser(preferences: string[] = []) { + useUser.mockReturnValue({ + userId: "user-1", + user: { + id: "user-1", + name: null, + description: null, + profilePicture: "default", + preferences, + matchedPlants: [], + }, + loading: false, + }); +} + beforeEach(() => { - localStorage.clear(); + addUserMatch.mockClear(); + mockUser(); useQuery.mockReturnValue({ data: { getPlants: plants }, loading: false, @@ -53,6 +78,20 @@ describe("PlantMatchPage", () => { }, ); + it("saves a liked plant as a match, but not a skipped one", () => { + render(); + fireEvent.click( + screen.getByRole("button", { name: "plantMatchPage.skipPlant" }), + ); + expect(addUserMatch).not.toHaveBeenCalled(); + fireEvent.click( + screen.getByRole("button", { name: "plantMatchPage.likePlant" }), + ); + expect(addUserMatch).toHaveBeenCalledWith({ + variables: { userId: "user-1", plantId: "1" }, + }); + }); + it("shows the loading state", () => { useQuery.mockReturnValue({ loading: true }); render(); @@ -68,7 +107,7 @@ describe("PlantMatchPage", () => { }); it("highlights card preferences saved on the profile", () => { - localStorage.setItem("plantPreferences", JSON.stringify(["averageWater"])); + mockUser(["averageWater"]); render(); expect(screen.getByText("preferences.averageWater")).toHaveClass( "is-match", diff --git a/frontend/src/tests/PlantPreferences.test.tsx b/frontend/src/tests/PlantPreferences.test.tsx new file mode 100644 index 00000000..7e96ec91 --- /dev/null +++ b/frontend/src/tests/PlantPreferences.test.tsx @@ -0,0 +1,106 @@ +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { beforeEach, describe, it, expect, vi } from "vitest"; +import PlantPreferences from "../components/plantPreferences/PlantPreferences"; +import type { Preference } from "../types/Preference"; + +const { updatePreferences, useUser } = vi.hoisted(() => ({ + updatePreferences: vi.fn(), + useUser: vi.fn(), +})); +vi.mock("@apollo/client/react", () => ({ + useMutation: () => [updatePreferences], +})); +vi.mock("../context/UserContext", () => ({ useUser })); +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ t: (key: string) => key }), +})); + +const preferences: Preference[] = [ + { id: "averageWater", translationKey: "preferences.averageWater" }, + { id: "fullSun", translationKey: "preferences.fullSun" }, +]; + +function mockUser(selected: string[], userId: string | null = "user-1") { + useUser.mockReturnValue({ + userId, + user: userId ? { id: userId, preferences: selected } : null, + loading: false, + }); +} + +// The preferences sent in the last save +const savedPreferences = () => + updatePreferences.mock.lastCall?.[0].variables.preferences; + +describe("PlantPreferences", () => { + beforeEach(() => { + updatePreferences.mockReset(); + updatePreferences.mockResolvedValue({}); + }); + + it("marks the preferences saved on the user", () => { + mockUser(["fullSun"]); + render(); + + expect( + screen.getByRole("button", { name: "preferences.fullSun" }), + ).toHaveClass("selected"); + expect( + screen.getByRole("button", { name: "preferences.averageWater" }), + ).not.toHaveClass("selected"); + }); + + it("adds a preference that is not selected", async () => { + mockUser(["fullSun"]); + render(); + + await userEvent.click( + screen.getByRole("button", { name: "preferences.averageWater" }), + ); + + expect(savedPreferences()).toEqual(["fullSun", "averageWater"]); + // The buttons change right away instead of waiting for the server + expect(updatePreferences.mock.lastCall?.[0].optimisticResponse).toEqual({ + updateUserPreferences: { + __typename: "User", + id: "user-1", + preferences: ["fullSun", "averageWater"], + }, + }); + }); + + it("removes a preference that is already selected", async () => { + mockUser(["fullSun", "averageWater"]); + render(); + + await userEvent.click( + screen.getByRole("button", { name: "preferences.fullSun" }), + ); + + expect(savedPreferences()).toEqual(["averageWater"]); + }); + + it("does not crash when saving fails", async () => { + mockUser([]); + updatePreferences.mockRejectedValue(new Error("Offline")); + render(); + + await userEvent.click( + screen.getByRole("button", { name: "preferences.fullSun" }), + ); + + expect(updatePreferences).toHaveBeenCalledTimes(1); + }); + + it("saves nothing before the user exists", async () => { + mockUser([], null); + render(); + + await userEvent.click( + screen.getByRole("button", { name: "preferences.fullSun" }), + ); + + expect(updatePreferences).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/tests/Profile.test.tsx b/frontend/src/tests/Profile.test.tsx index 23fc8847..0f0b32d7 100644 --- a/frontend/src/tests/Profile.test.tsx +++ b/frontend/src/tests/Profile.test.tsx @@ -1,9 +1,18 @@ -import { render, screen } from "@testing-library/react"; +import { render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { beforeEach, describe, it, expect, vi } from "vitest"; import Profile from "../pages/profile/Profile"; +const { updateProfile, useUser } = vi.hoisted(() => ({ + updateProfile: vi.fn(), + useUser: vi.fn(), +})); +vi.mock("@apollo/client/react", () => ({ + useMutation: () => [updateProfile], +})); +vi.mock("../context/UserContext", () => ({ useUser })); + vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key, @@ -12,9 +21,27 @@ vi.mock("react-i18next", () => ({ describe("Profile page", () => { beforeEach(() => { - localStorage.clear(); + updateProfile.mockReset(); + updateProfile.mockResolvedValue({}); + mockUser(); }); + // A user who has not filled in their profile yet + function mockUser(profilePicture = "default") { + useUser.mockReturnValue({ + userId: "user-1", + user: { + id: "user-1", + name: null, + description: null, + profilePicture, + preferences: [], + matchedPlants: [], + }, + loading: false, + }); + } + it("renders profile name", () => { render(); @@ -90,7 +117,9 @@ describe("Profile page", () => { await user.click( screen.getByRole("button", { name: "profile.editProfile" }), ); - const nameInput = screen.getByRole("textbox", { name: "profile.enterName" }); + const nameInput = screen.getByRole("textbox", { + name: "profile.enterName", + }); const descriptionInput = screen.getByRole("textbox", { name: "profile.aboutYou", }); @@ -99,19 +128,54 @@ describe("Profile page", () => { await user.clear(descriptionInput); await user.type(descriptionInput, "I love plants"); - const avatar = screen.getByRole("button", { name: "Choose profile.monstera" }); - const avatarSrc = screen.getByAltText("profile.monstera").getAttribute("src"); - await user.click(avatar); + await user.click( + screen.getByRole("button", { name: "Choose profile.monstera" }), + ); + // The typed text is shown right away expect(screen.getByRole("heading", { name: "Nina" })).toBeInTheDocument(); expect(screen.getByText("I love plants")).toBeInTheDocument(); - expect(avatar).toHaveAttribute("aria-pressed", "true"); expect( screen.getByRole("img", { name: "profile.imageAlt: Nina" }), - ).toHaveAttribute("src", avatarSrc); - expect(localStorage.getItem("profileName")).toBe("Nina"); - expect(localStorage.getItem("description")).toBe("I love plants"); - expect(localStorage.getItem("profileAvatar")).toBe("monstera"); + ).toBeInTheDocument(); + + // The avatar is saved at once, with an optimistic response + expect(updateProfile).toHaveBeenCalledWith( + expect.objectContaining({ + variables: { userId: "user-1", profilePicture: "monstera" }, + }), + ); + + // Name and description are saved after the user stops typing + await waitFor(() => + expect(updateProfile).toHaveBeenCalledWith({ + variables: { + userId: "user-1", + name: "Nina", + description: "I love plants", + }, + }), + ); + }); + + it("shows the avatar saved on the user", async () => { + const user = userEvent.setup(); + mockUser("monstera"); + + render(); + await user.click( + screen.getByRole("button", { name: "profile.editProfile" }), + ); + + expect( + screen.getByRole("button", { name: "Choose profile.monstera" }), + ).toHaveAttribute("aria-pressed", "true"); + expect( + screen.getByRole("img", { name: "profile.imageAlt: profile.name" }), + ).toHaveAttribute( + "src", + screen.getByAltText("profile.monstera").getAttribute("src"), + ); }); it("matches snapshot", () => { diff --git a/frontend/src/tests/ThemeToggle.test.tsx b/frontend/src/tests/ThemeToggle.test.tsx new file mode 100644 index 00000000..c20cf06e --- /dev/null +++ b/frontend/src/tests/ThemeToggle.test.tsx @@ -0,0 +1,32 @@ +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { afterEach, describe, it, expect, vi } from "vitest"; +import ThemeToggle from "../components/sidebarButtons/ThemeToggle"; + +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ t: (key: string) => key }), +})); + +describe("ThemeToggle", () => { + afterEach(() => { + document.documentElement.removeAttribute("data-theme"); + }); + + it("switches between dark and light mode", async () => { + const user = userEvent.setup(); + render(); + + await user.click( + screen.getByRole("button", { name: "sidebar.switchToDarkMode" }), + ); + expect(document.documentElement).toHaveAttribute("data-theme", "dark"); + + await user.click( + screen.getByRole("button", { name: "sidebar.switchToLightMode" }), + ); + expect(document.documentElement).toHaveAttribute("data-theme", "light"); + expect( + screen.getByRole("button", { name: "sidebar.switchToDarkMode" }), + ).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/tests/UserContext.test.tsx b/frontend/src/tests/UserContext.test.tsx new file mode 100644 index 00000000..969ad942 --- /dev/null +++ b/frontend/src/tests/UserContext.test.tsx @@ -0,0 +1,146 @@ +import type { ComponentProps } from "react"; +import { render, screen, waitFor } from "@testing-library/react"; +import { MockedProvider } from "@apollo/client/testing/react"; +import { beforeEach, describe, it, expect, vi } from "vitest"; +import { UserProvider, useUser } from "../context/UserContext"; +import { CREATE_USER, GET_USER } from "../context/userQueries"; + +type Mocks = ComponentProps["mocks"]; + +// A user as the backend returns it +function makeUser(id: string, name: string | null = null) { + return { + __typename: "User", + id, + name, + description: null, + profilePicture: "default", + preferences: [], + matchedPlants: [], + }; +} + +function getUserMock(userId: string, user: ReturnType | null) { + return { + request: { query: GET_USER, variables: { userId } }, + result: { data: { getUser: user } }, + }; +} + +// `result` is a spy, so tests can check whether a user was created +function createUserMock(user: ReturnType) { + return { + request: { query: CREATE_USER }, + result: vi.fn(() => ({ data: { createUser: user } })), + }; +} + +// Shows what the context gives its children +function UserInfo() { + const { userId, user, loading } = useUser(); + return ( +
+

{userId ?? "none"}

+

{user?.name ?? "none"}

+

{String(loading)}

+
+ ); +} + +function setup(mocks: Mocks) { + return render( + + + + + , + ); +} + +describe("UserContext", () => { + beforeEach(() => { + localStorage.clear(); + }); + + it("gives no user without a UserProvider", () => { + render(); + + expect(screen.getByTestId("user-id")).toHaveTextContent("none"); + expect(screen.getByTestId("user-name")).toHaveTextContent("none"); + expect(screen.getByTestId("loading")).toHaveTextContent("false"); + }); + + it("loads the user saved in the browser", async () => { + localStorage.setItem("userId", "user-1"); + const create = createUserMock(makeUser("new-user")); + setup([getUserMock("user-1", makeUser("user-1", "Nina")), create]); + + expect(screen.getByTestId("loading")).toHaveTextContent("true"); + expect(await screen.findByText("Nina")).toBeInTheDocument(); + expect(screen.getByTestId("user-id")).toHaveTextContent("user-1"); + expect(create.result).not.toHaveBeenCalled(); + }); + + it("creates and saves a new user on the first visit", async () => { + const create = createUserMock(makeUser("new-user", "New")); + setup([create, getUserMock("new-user", makeUser("new-user", "New"))]); + + expect(await screen.findByText("New")).toBeInTheDocument(); + expect(screen.getByTestId("user-id")).toHaveTextContent("new-user"); + expect(localStorage.getItem("userId")).toBe("new-user"); + expect(create.result).toHaveBeenCalledTimes(1); + }); + + it("creates a new user when the saved one no longer exists", async () => { + localStorage.setItem("userId", "deleted-user"); + const create = createUserMock(makeUser("new-user", "New")); + setup([ + getUserMock("deleted-user", null), + create, + getUserMock("new-user", makeUser("new-user", "New")), + ]); + + expect(await screen.findByText("New")).toBeInTheDocument(); + expect(localStorage.getItem("userId")).toBe("new-user"); + }); + + it("keeps the saved user when the backend is down", async () => { + localStorage.setItem("userId", "user-1"); + const create = createUserMock(makeUser("new-user")); + setup([ + { + request: { query: GET_USER, variables: { userId: "user-1" } }, + error: new Error("Offline"), + }, + create, + ]); + + await waitFor(() => + expect(screen.getByTestId("loading")).toHaveTextContent("false"), + ); + expect(screen.getByTestId("user-id")).toHaveTextContent("user-1"); + expect(create.result).not.toHaveBeenCalled(); + expect(localStorage.getItem("userId")).toBe("user-1"); + }); + + it("keeps working when creating a user fails", async () => { + setup([{ request: { query: CREATE_USER }, error: new Error("Offline") }]); + + await waitFor(() => + expect(screen.getByTestId("loading")).toHaveTextContent("false"), + ); + expect(screen.getByTestId("user-id")).toHaveTextContent("none"); + expect(localStorage.getItem("userId")).toBeNull(); + }); + + it("removes user data left in the browser from before the database", () => { + localStorage.setItem("userId", "user-1"); + localStorage.setItem("matchedPlants", "[]"); + localStorage.setItem("profileName", "Nina"); + setup([getUserMock("user-1", makeUser("user-1"))]); + + expect(localStorage.getItem("matchedPlants")).toBeNull(); + expect(localStorage.getItem("profileName")).toBeNull(); + expect(localStorage.getItem("userId")).toBe("user-1"); + }); +}); diff --git a/frontend/src/tests/__snapshots__/ExplorePage.test.tsx.snap b/frontend/src/tests/__snapshots__/ExplorePage.test.tsx.snap index 63f475c9..35f7af01 100644 --- a/frontend/src/tests/__snapshots__/ExplorePage.test.tsx.snap +++ b/frontend/src/tests/__snapshots__/ExplorePage.test.tsx.snap @@ -22,6 +22,21 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with no re > ExplorePlants.search + snapshots > matches the snapshot of the page with resul > ExplorePlants.search + snapshots > matches the snapshot of the page with resul > Testplante 1 + + + +
  • snapshots > matches the snapshot of the page with resul > Testplante 2 + + + +
  • snapshots > matches the snapshot of the page with resul > Testplante 3 + + + +
  • snapshots > matches the snapshot of the page with resul > Testplante 4 + + + +
  • snapshots > matches the snapshot of the page with resul > Testplante 5 + + + +
  • snapshots > matches the snapshot of the page with resul > Testplante 6 + + + +
  • snapshots > matches the snapshot of the page with resul > Testplante 7 + + + +
  • snapshots > matches the snapshot of the page with resul > Testplante 8 + + + +
  • snapshots > matches the snapshot of the page with resul > Testplante 9 + + + +
  • snapshots > matches the snapshot of the page with resul > Testplante 10 + + + +
  • snapshots > matches the snapshot of the page with resul > Testplante 11 + + + +
  • snapshots > matches the snapshot of the page with resul > Testplante 12 + + + +