diff --git a/README.md b/README.md index fa951b5c..0a6432c7 100644 --- a/README.md +++ b/README.md @@ -137,7 +137,7 @@ The first time you run the e2e tests, install the browser with `npx playwright i | Part | Statements | Branches | Functions | Lines | | -------- | ---------- | -------- | --------- | ------- | -| Frontend | 96.95 % | 92.75 % | 95.31 % | 97.67 % | +| Frontend | 97.38 % | 93.86 % | 96.76 % | 98.39 % | | Backend | 100 % | 100 % | 100 % | 100 % | See [tests.md](docs/tests.md) for the test strategy, more ways to run the tests, how to run the tests with coverage and screenshots of the coverage reports, what the test files cover and what the tests found. diff --git a/backend/src/listen.ts b/backend/src/listen.ts index ed11f815..bd24444f 100644 --- a/backend/src/listen.ts +++ b/backend/src/listen.ts @@ -1,13 +1,14 @@ -import { createServer } from "node:http"; +import { createServer, type Server } from "node:http"; import type { Express } from "express"; -// Starts listening on the port. Rejects if it fails, e.g. when the port is -// already in use, so the server stops with the error instead of hanging. -// In its own file, so the tests can replace it and not open a port. -export function listen(app: Express, port: number): Promise { +// Starts listening on the port and returns the server. Rejects if it fails, +// e.g. when the port is already in use, so the server stops with the error +// instead of hanging. In its own file, so the tests can replace it and not +// open a port. +export function listen(app: Express, port: number): Promise { return new Promise((resolve, reject) => { const server = createServer(app); server.once("error", reject); - server.listen(port, () => resolve()); + server.listen(port, () => resolve(server)); }); } diff --git a/backend/tests/listen.test.ts b/backend/tests/listen.test.ts new file mode 100644 index 00000000..bca61bc0 --- /dev/null +++ b/backend/tests/listen.test.ts @@ -0,0 +1,36 @@ +import type { Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import express from "express"; +import { afterEach, describe, expect, it } from "vitest"; +import { listen } from "../src/listen.js"; + +describe("listen", () => { + const servers: Server[] = []; + + // Close every server the test opened, so no port is left open + afterEach(async () => { + await Promise.all( + servers.map((server) => new Promise((done) => server.close(done))), + ); + servers.length = 0; + }); + + it("listens on the port and returns the server", async () => { + // Port 0 lets the system pick a free port + const server = await listen(express(), 0); + servers.push(server); + + expect(server.listening).toBe(true); + expect((server.address() as AddressInfo).port).toBeGreaterThan(0); + }); + + it("rejects when the port is already in use", async () => { + const first = await listen(express(), 0); + servers.push(first); + const { port } = first.address() as AddressInfo; + + await expect(listen(express(), port)).rejects.toMatchObject({ + code: "EADDRINUSE", + }); + }); +}); diff --git a/docs/architecture.md b/docs/architecture.md index 483e6c56..492ebbc7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -295,7 +295,7 @@ T03-Project-2/ │ │ ├── schema.ts # GraphQL schema │ │ ├── server.ts # Starts the backend (app.ts: Express with /graphql and /images) │ │ └── types.ts # TypeScript types for documents, GraphQL types and arguments -│ ├── tests/ # Backend tests against an in-memory MongoDB (db, server, indexes), with their own tsconfig.json +│ ├── tests/ # Backend tests against an in-memory MongoDB (db, server, indexes, migrations, listen), with their own tsconfig.json │ ├── seedDataFetch.js # Script that fetches plant data from the Perenual API and stores it in MongoDB │ └── .env.example # Template for required environment variables ├── docs/ # Project documentation (architecture, tests, quality, AI usage), media/ has the coverage images diff --git a/docs/media/coverageBackend.png b/docs/media/coverageBackend.png index be1fcb4b..a7834344 100644 Binary files a/docs/media/coverageBackend.png and b/docs/media/coverageBackend.png differ diff --git a/docs/media/coverageFrontend.png b/docs/media/coverageFrontend.png index c62a5d16..a9e1c5ee 100644 Binary files a/docs/media/coverageFrontend.png and b/docs/media/coverageFrontend.png differ diff --git a/docs/tests.md b/docs/tests.md index 6b68d517..a8786c72 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -93,7 +93,7 @@ To watch an e2e test, open UI mode, run a test, and expand it to choose the desk | Part | Statements | Branches | Functions | Lines | | -------- | ---------- | -------- | --------- | ------- | -| Frontend | 96.95 % | 92.75 % | 95.31 % | 97.67 % | +| Frontend | 97.38 % | 93.86 % | 96.76 % | 98.39 % | | Backend | 100 % | 100 % | 100 % | 100 % | - Frontend test coverage: @@ -134,6 +134,8 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - The selected option in the button's accessible name, opening the menu with focus on the selected option, moving between the options with the arrow keys, Home and End, that the button is linked to the list with `aria-controls` and the menu closes when Tab moves focus out of it, choosing an option, and closing with Escape or a click outside, with focus going back to the button. - `getPageItems.test.ts` - Which page numbers are shown: every page when there are few, the first pages near the start, the last pages near the end, the current page and its neighbours in the middle, "…" never hiding just one page, and never more than seven items however many pages there are. +- `Pagination.test.tsx` + - Clicking a page number goes straight to that page, the current page is marked with `aria-current` and clicking it does nothing, and the previous and next buttons are disabled at the ends. - `Header.test.tsx` - Shows the right title for each page, including the "Page not found" title for unknown paths, opens the sidebar with the menu button, and that the menu button tells screen readers whether the sidebar is open (`aria-expanded`, `aria-controls`). - `i18n.test.tsx` @@ -146,17 +148,20 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - Sorting and pages: the number of matches next to the sort menu in an `aria-live` region that stays on the page, so "no matches" is also announced, moving between pages, a new sort order saved in `sessionStorage` and going back to page 1, and going to the last page when the current page no longer exists. - Search and filters: a chosen filter is sent, saved in `sessionStorage` and goes back to page 1, the search is sent after the debounce delay, search and filters saved earlier in the session are restored, the number of matches for each filter value with empty values disabled, a message in an `aria-live` region under the filters when no matches fit, like on Explore Plants (with the search and filters still on screen), a separate count when the list is filtered, and reset clearing the search, the filters and the sort order. The search and filters are hidden when the user has no matches at all. - Best match first: only offered when the user has preferences, saved for the session, and newest first when it was saved but the user has no preferences any more. + - The most compatible plant: shown in a button with its picture from the backend's address, which sorts by best match, scrolls to the plant and turns its card to the details, also when the list is already sorted that way, and which works with the keyboard. - `NotFoundPage.test.tsx` - An unknown path shows the 404 page, with a link back to Plant Match. - `apiUrl.test.ts` - An image path from the backend is resolved against the API's address, and a full URL is kept as it is. - `PlantCard.test.tsx` - The plant image is loaded from the backend's address and lazily (`loading="lazy"`). + - A page can turn the card to the details through its ref (`showDetails`), and asking again does not turn it back. - The back of the card shows the whole plant after clicking information, missing facts and images are shown as unknown, watering, sunlight and care level are turned into the right preference chips, and the values on the back are translated in any casing (with "Moderate" as medium), while unknown values are shown as they are. - `PlantMatchPage.test.tsx` - The instructions and the first plant, going to the next plant with like and dislike and the empty card at the end, that a liked plant is saved as a match and a skipped one is not, the loading and error states, that preferences saved on the profile are highlighted on the card and also said in text for screen readers, and that the info button is described by the instructions, which Escape hides. - Loading in batches: the first batch is fetched with the batch size and no excluded plants, the next batch is only fetched when few cards are left and leaves out the plants already shown, every plant is shown exactly once, no more requests are made after a short batch, and a second request is not started while one is in progress. - Preferences and edge cases: the user's saved preferences are sent with the request so the best matches come first, changing preferences starts a new deck with the updated ordering, also when they were changed on the profile page while PlantMatch was closed (the saved deck remembers which preferences it was sorted by), nothing is fetched before the user has loaded, and the end card with disabled buttons is shown when there are no plants at all. + - Swiping: dragging the card far enough right saves a match and left skips the plant, a short drag moves the card back without flipping it, a tap that hardly moves flips the card, a mostly vertical movement lets the page scroll, other mouse buttons are ignored, and with animations on, the card flies off before the next plant is shown and swipes are ignored meanwhile. A liked card stays on screen while it flies off, even though it is already saved as a match, and the end card is only shown after the last card has flown off. - `PlantOwnerTestPage.test.tsx` - The result for all six combinations of answers, and that the time and light answers do not change it. - The suggested preferences for every result: watering and, for the minimalists and the plant lovers, care level from the result, care level from the time answer for the average gardeners, and partial sun suggesting part shade. @@ -168,7 +173,7 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - The name, the image alt text and a screen reader prefix for the description, the preferences tab open by default (`aria-pressed`), the labelled fields and avatar chooser in the edit tab, saving name, description and avatar, the saved avatar, and that a picture from the plant owner test is shown but not offered in the chooser. - Saving the profile text at once when a field loses focus, when the user leaves the page and when the tab is reloaded or closed, without saving the same text twice. - `Sidebar.test.tsx` - - The title, links to all pages, the language switcher and theme toggle, that the sidebar closes when a link or the close button is clicked, that the open state is shown in the `data-open` attribute, an accessible navigation landmark, that only the current page is marked as active, that focus moves to the close button when it opens, and that Escape closes it. + - The title, links to all pages, the language switcher and theme toggle, that the sidebar closes when a link or the close button is clicked, that the open state is shown in the `data-open` attribute, an accessible navigation landmark, that only the current page is marked as active, that focus moves to the close button when it opens, that Escape closes it while other keys do not, and that the heart in the title is in its own element so it can be green. - `SidebarNewMatches.test.tsx` - The badge on My Matches counts only matches made while the app is open, not a match that is removed again, and counts a match the user already had as new if it is removed and added again. It is cleared when My Matches is opened. - `ThemeToggle.test.tsx` @@ -176,13 +181,17 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - `translationKeys.test.tsx` - The Norwegian and English translation files have exactly the same keys, so no text is missing in either language. - `UserContext.test.tsx` - - No user without a provider, loading the user saved in the browser, creating and saving a new user on the first visit, creating a new user when the saved one no longer exists, keeping the saved user when the backend is down, working on when creating a user fails, and removing old user data left in the browser. + - No user without a provider, loading the user saved in the browser, creating and saving a new user on the first visit, creating a new user when the saved one no longer exists, keeping the saved user when the backend is down and trying again every five seconds until it is back, starting without a saved user when browser storage is blocked, working on when creating a user fails, and removing old user data left in the browser. - `useDebounce.test.ts` - The initial value is returned at once, updates only come after the delay, the delay restarts on quick changes, and the default delay is 300 ms. +- `useDismissibleTooltip.test.ts` + - Escape hides the help text while other keys do not, and it is shown again when the mouse or focus leaves. - `useExploreParams.test.tsx` - Default values when the URL has no parameters, reading search, filters, sorting and page from the URL, page 1 for an invalid page number, going back to page 1 when the search, a filter or the sort order changes, keeping the other parameters when the page changes, removing a parameter that is set to an empty value, and clearing all Explore parameters on reset. - `useMatchedPlants.test.tsx` - The ids of the matched plants, that My Matches is removed from the cache when a match is added or removed, adding and removing a match with no message when it works, an error message when the request fails or the user is not found, and nothing sent when there is no user or the plant is already matched. +- `usePreferences.test.ts` + - The saved preferences, saving that works, that saving counts as failed when the request fails or the user is not found, and that nothing is saved before the user exists. - `useSessionState.test.ts` - Default and initial values, reading and saving in `sessionStorage`, keeping the value when the hook is mounted again, and working on when reading or saving fails. - `Walkthrough.test.tsx` @@ -206,6 +215,10 @@ The tests are in `backend/tests`. They use a real MongoDB in memory, started in - Error messages: invalid input gives the right message and the code `BAD_USER_INPUT` and saves nothing (too long name or description, unknown profile picture, unknown preferences, unknown or malformed plant ids), invalid GraphQL requests give the right error, and the server passes on a database error and keeps running. - `indexes.test.ts` - The index for sorting by name is created, and creating it again on the next start does not fail. +- `migrations.test.ts` + - Old data is updated when the server starts: the old avatar id `snake-plant` is renamed to `snakePlant`, other pictures are left alone, and running it again on the next start does not fail. +- `listen.test.ts` + - The server listens on a free port, and stops with an error when the port is already in use. ### End-to-end and API tests @@ -260,6 +273,7 @@ The UI tests find elements the way a user or a screen reader would: by role, lab **Matching plants (`uiMatchAndRemovePlant`):** - Liking a plant on PlantMatch adds it to MyMatches, where it can be removed. +- Swiping a plant left on PlantMatch skips it and swiping right matches it, with the mouse on desktop and a finger on mobile. Playwright can only tap with a finger, so the drag is sent through the Chrome DevTools Protocol, and the browser handles it like a real finger, including `touch-action` on the card. The component tests send pointer events in jsdom, so only this test checks that the gesture works in a real browser. - Adding a plant from ExplorePlants adds it to MyMatches and turns its ✿ button into ✖. Clicking the button again on ExplorePlants removes the plant from MyMatches. - Searching and filtering MyMatches: the search only looks among the user's matches, a filter disables the values that would give no matches, the choices are remembered when going to another page and back, a search that finds nothing says so under the filters, and reset shows all the matches again. - Matching 13 plants from ExplorePlants gives two pages in MyMatches: the count, the newest first on page 1 and the oldest on page 2, sorting A–Z going back to page 1, and the sort order remembered when going to another page and back, and after a reload. @@ -283,10 +297,11 @@ The frontend and backend have their own lists of preference and profile picture Saving the profile is debounced by 500 ms, and the text is also saved at once when a field loses focus. The test waits until the save request has reached the backend before reloading, instead of waiting a fixed time, so it does not depend on the length of the debounce. -**Pictures (`uiImages`):** checks that every picture in the app is actually downloaded and decoded by the browser: the default profile picture, the seven avatars, the six pictures from the plant owner test and the placeholder on plant cards without an image. The component tests run in jsdom, which never loads images, so they only check the `src` attribute and would still pass if a file was missing or broken. An image counts as loaded when it has a natural width larger than 0. +**Pictures (`uiImages`):** checks that every picture in the app is actually downloaded and decoded by the browser: the default profile picture, the seven avatars, the six pictures from the plant owner test, a plant image sent by the backend and the placeholder on plant cards without an image. The component tests run in jsdom, which never loads images, so they only check the `src` attribute and would still pass if a file was missing or broken. An image counts as loaded when it has a natural width larger than 0. - The pictures from the plant owner test are only shown after the test is finished, so the test sets each result as profile picture through the API, reloads the profile page and checks the picture shown there. - The placeholder is a CSS background, so the test reads the URL the browser uses from the card's `::before` element and loads it as an image. +- Calathea is the only test plant with a stored image. The test checks that the image is asked for from the backend's address and not the frontend's, that the backend answers with a PNG file and a `Cache-Control` header, and that it loads. The frontend and the backend run on different ports, like on the VM, so an image link that is not turned into the backend's address fails here, while the component tests, which mock the backend, would still pass. **Walkthrough (`uiWalkthrough`):** these tests start as new users with empty storage. The other UI tests start as users who have already seen the walkthrough (`storageState` in `playwright.config.ts`), since it would otherwise cover the page they test. diff --git a/e2e/fixtures/plants.json b/e2e/fixtures/plants.json index 67869c3b..3e271c66 100644 --- a/e2e/fixtures/plants.json +++ b/e2e/fixtures/plants.json @@ -87,7 +87,7 @@ "sunlight": ["filtered shade"], "careLevel": "High", "description": "A plant with large, striped leaves.", - "imageData": null + "imageData": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEElEQVR4nGPQqzWCIwbiOABnIw3R2yR41wAAAABJRU5ErkJggg==" }, { "perenualId": 10, diff --git a/e2e/uiImages.spec.ts b/e2e/uiImages.spec.ts index 8b22f05e..6f5dccc4 100644 --- a/e2e/uiImages.spec.ts +++ b/e2e/uiImages.spec.ts @@ -2,8 +2,8 @@ import { test, expect, type Locator, type Page } from "@playwright/test"; import { names } from "./helpers/names"; // Checks that the pictures in the app actually load in the browser: the avatars -// on the profile page, the pictures from the plant owner test, and the -// placeholder shown on plant cards without an image. +// on the profile page, the pictures from the plant owner test, the plant images +// sent by the backend, and the placeholder shown on plant cards without an image. // The unit tests run in jsdom, which never downloads images, so they only // check the src attribute. A missing or broken file is only found here. // Images are found by role and alt text where they have one. The avatar @@ -104,7 +104,7 @@ test("the placeholder picture loads on plant cards without an image", async ({ }) => { await page.goto("#/explorePlants"); - // None of the test plants has an image, so every card shows the placeholder + // Aloe Vera, the first plant a–z, has no image, so its card shows the placeholder const missingImage = page.getByTestId("plant-image-missing").first(); await expect(missingImage).toBeVisible(); @@ -118,3 +118,31 @@ test("the placeholder picture loads on plant cards without an image", async ({ expect(await loadImageWidth(page, url!)).toBeGreaterThan(0); }); + +test("a stored plant image is sent by the backend as a file and loads", async ({ + page, +}) => { + // Calathea is the only test plant with a stored image. The backend sends it + // from /images/, and the frontend must ask the backend for it, not the + // frontend's own address, since they run on different ports (as on the VM). + const imageResponse = page.waitForResponse((response) => + /\/images\/[0-9a-f]{24}$/.test(response.url()), + ); + await page.goto("#/explorePlants"); + + const image = page.getByRole("img", { name: "Calathea" }); + await expect(image).toHaveAttribute( + "src", + /^http:\/\/localhost:3002\/images\/[0-9a-f]{24}$/, + ); + // The images are lazy-loaded, so on a small screen it is only loaded when + // the user scrolls to it + await image.scrollIntoViewIfNeeded(); + await expectImageLoaded(image); + + // Sent as an image file that the browser can keep, not as base64 text + const response = await imageResponse; + expect(response.status()).toBe(200); + expect(response.headers()["content-type"]).toBe("image/png"); + expect(response.headers()["cache-control"]).toContain("max-age="); +}); diff --git a/e2e/uiMatchAndRemovePlant.spec.ts b/e2e/uiMatchAndRemovePlant.spec.ts index fe7f5aaf..0d468150 100644 --- a/e2e/uiMatchAndRemovePlant.spec.ts +++ b/e2e/uiMatchAndRemovePlant.spec.ts @@ -1,7 +1,11 @@ -import { test, expect, type Locator } from "@playwright/test"; +import { test, expect, type Locator, type Page } from "@playwright/test"; import { goToPage } from "./helpers/navigation"; import { names } from "./helpers/names"; -import { plantItems, plantMatchCardName } from "./helpers/locators"; +import { + plantItems, + plantMatchCard, + plantMatchCardName, +} from "./helpers/locators"; // User journeys for matching plants: from PlantMatch and from ExplorePlants, // that matches show up in MyMatches and can be removed from both MyMatches @@ -15,6 +19,46 @@ import { plantItems, plantMatchCardName } from "./helpers/locators"; const matchButtonIn = (item: Locator) => item.getByRole("button", { name: names.matchButton }); +// Drags the card in PlantMatch dx pixels sideways, like a user would: with the +// mouse on desktop and with a finger on mobile. Playwright can only tap with a +// finger, so the touch drag is sent through the Chrome DevTools Protocol. The +// browser then handles it like a real finger, including touch-action on the +// card, so the test fails if the page scrolls instead of the card moving. +async function swipeCard(page: Page, dx: number, isMobile: boolean) { + const card = plantMatchCard(page); + await card.scrollIntoViewIfNeeded(); + const box = await card.boundingBox(); + if (!box) throw new Error("The plant card is not visible"); + const x = box.x + box.width / 2; + const y = box.y + box.height / 2; + const steps = 10; + + if (!isMobile) { + await page.mouse.move(x, y); + await page.mouse.down(); + await page.mouse.move(x + dx, y, { steps }); + await page.mouse.up(); + return; + } + + const cdp = await page.context().newCDPSession(page); + await cdp.send("Input.dispatchTouchEvent", { + type: "touchStart", + touchPoints: [{ x, y }], + }); + for (let step = 1; step <= steps; step++) { + await cdp.send("Input.dispatchTouchEvent", { + type: "touchMove", + touchPoints: [{ x: x + (dx * step) / steps, y }], + }); + } + await cdp.send("Input.dispatchTouchEvent", { + type: "touchEnd", + touchPoints: [], + }); + await cdp.detach(); +} + test("user can like a plant in PlantMatch, find it in MyMatches and remove the match", async ({ page, }) => { @@ -44,6 +88,32 @@ test("user can like a plant in PlantMatch, find it in MyMatches and remove the m await expect(page.getByRole("main")).toContainText(names.noMatches); }); +test("user can swipe left to skip a plant and right to match one in PlantMatch", async ({ + page, + isMobile, +}) => { + await page.goto(""); + const cardName = plantMatchCardName(page); + await expect(cardName).toBeVisible(); + + // Swipe the first plant to the left to skip it + const skippedName = (await cardName.textContent())?.trim(); + await swipeCard(page, -150, isMobile); + await expect(cardName).not.toHaveText(skippedName ?? ""); + + // Swipe the next plant to the right to match it + const likedName = (await cardName.textContent())?.trim(); + expect(likedName).toBeTruthy(); + await swipeCard(page, 150, isMobile); + await expect(cardName).not.toHaveText(likedName ?? ""); + + // Only the plant swiped right is in MyMatches + await goToPage(page, names.myMatches); + const matchCards = plantItems(page); + await expect(matchCards).toHaveCount(1); + await expect(matchCards.first()).toContainText(likedName ?? ""); +}); + test("user can add a plant from ExplorePlants, find it in MyMatches and remove it again from ExplorePlants", async ({ page, }) => { @@ -156,6 +226,10 @@ test("PlantMatch continues from the same card after visiting another page and af test("a plant matched on ExplorePlants never shows up in PlantMatch", async ({ page, }) => { + // The test skips through the whole deck. With reduced motion the cards do + // not fly off, so it does not wait for the animation on every card. The + // animation itself is tested by the swipe test. + await page.emulateMedia({ reducedMotion: "reduce" }); await page.goto("#/explorePlants"); const firstItem = plantItems(page).first(); const matchedName = ( diff --git a/frontend/src/components/plantCard/PlantCard.tsx b/frontend/src/components/plantCard/PlantCard.tsx index 80a25347..bbc7c45e 100644 --- a/frontend/src/components/plantCard/PlantCard.tsx +++ b/frontend/src/components/plantCard/PlantCard.tsx @@ -1,5 +1,5 @@ -import { useEffect, useRef, useState } from "react"; -import type { KeyboardEvent } from "react"; +import { useEffect, useImperativeHandle, useRef, useState } from "react"; +import type { KeyboardEvent, Ref } from "react"; import { useTranslation } from "react-i18next"; import PlantPreferenceChips from "../plantPreferenceChips/PlantPreferenceChips"; import type { Plant } from "../../types/Plant"; @@ -9,16 +9,24 @@ import "./PlantCard.css"; type PlantCardData = Omit; +// What a page can do with a plant card through its ref +export type PlantCardHandle = { + // Turns the card to the details on the back, if it is not already turned + showDetails: () => void; +}; + type PlantCardProps = { plant: PlantCardData; size?: "large" | "compact"; onInfo?: () => void; + ref?: Ref; }; export default function PlantCard({ plant, size = "large", onInfo, + ref, }: PlantCardProps) { const { name, @@ -38,6 +46,8 @@ export default function PlantCard({ const [isFlipped, setIsFlipped] = useState(false); + useImperativeHandle(ref, () => ({ showDetails: () => setIsFlipped(true) })); + useEffect(() => { if (!moveFocusRef.current) return; moveFocusRef.current = false; diff --git a/frontend/src/pages/myMatches/MyMatchesPage.css b/frontend/src/pages/myMatches/MyMatchesPage.css index 3deaadcd..f9476ba5 100644 --- a/frontend/src/pages/myMatches/MyMatchesPage.css +++ b/frontend/src/pages/myMatches/MyMatchesPage.css @@ -106,7 +106,10 @@ padding: 24px 36px; box-sizing: border-box; border-radius: 20px; + border: none; background: var(--light-green); + font: inherit; + text-align: left; cursor: pointer; transition: transform 0.2s ease, @@ -114,11 +117,18 @@ overflow: hidden; } -.compatible-plant-field:hover { +/* Lifted on hover, and also when reached with the keyboard */ +.compatible-plant-field:hover, +.compatible-plant-field:focus-visible { transform: translateY(-3px); box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1); } +.compatible-plant-field:focus-visible { + outline: 2px solid var(--dark-green); + outline-offset: 2px; +} + .compatible-plant-field img { width: 150px; height: 180px; @@ -127,12 +137,13 @@ border-radius: 14px; } -.compatible-plant-field p { - margin: 0; +.compatible-plant-label, +.compatible-plant-name { + display: block; color: var(--text-dark); } -.compatible-plant-field p:first-child { +.compatible-plant-label { font-size: 0.95rem; font-weight: 600; color: var(--pink-text); @@ -140,7 +151,7 @@ letter-spacing: 1px; } -.compatible-plant-field p:last-child { +.compatible-plant-name { margin-top: 8px; font-size: 1.6rem; font-weight: 700; @@ -187,7 +198,7 @@ height: 100px; } - .compatible-plant-field p:last-child { + .compatible-plant-name { font-size: 1.2rem; } } diff --git a/frontend/src/pages/myMatches/MyMatchesPage.tsx b/frontend/src/pages/myMatches/MyMatchesPage.tsx index d8e95bb0..a5974b4a 100644 --- a/frontend/src/pages/myMatches/MyMatchesPage.tsx +++ b/frontend/src/pages/myMatches/MyMatchesPage.tsx @@ -2,7 +2,9 @@ import { useEffect, useMemo, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { useQuery } from "@apollo/client/react"; import MatchButton from "../../components/matchButton/MatchButton"; -import PlantCard from "../../components/plantCard/PlantCard"; +import PlantCard, { + type PlantCardHandle, +} from "../../components/plantCard/PlantCard"; import Pagination from "../../components/pagination/Pagination"; import PlantSearchForm from "../../components/plantSearchForm/PlantSearchForm"; import { @@ -16,6 +18,7 @@ import { useDebounce } from "../../hooks/useDebounce"; import { useUser } from "../../context/UserContext"; import { MY_MATCHES, type MyMatchesData } from "../../graphql/user/queries"; import { PAGE_SIZE } from "../../graphql/plants/queries"; +import { toImageUrl } from "../../graphql/apiUrl"; import "./MyMatchesPage.css"; const SORT_OPTIONS = ["newest", "oldest", "name_asc", "name_desc"]; @@ -83,12 +86,20 @@ export default function MyMatchesPage() { }); const bestMatch = bestMatchData?.myMatches.plants[0]; + // Clicking the best match shows all matches sorted by best match, and + // scrolls to the plant and turns its card to the details once that list is + // shown. scrollRequest changes on + // every click, so it also scrolls when the list is already sorted that way + // and nothing else changes. const scrollToBestMatch = useRef(false); + const bestMatchCardRef = useRef(null); + const [scrollRequest, setScrollRequest] = useState(0); const showBestMatch = () => { reset(); setSort(PREFERENCES_SORT); setPage(1); scrollToBestMatch.current = true; + setScrollRequest((request) => request + 1); }; // While new results load, the previous ones stay on screen, like on @@ -99,7 +110,16 @@ export default function MyMatchesPage() { const plants = useMemo(() => data?.myMatches.plants ?? [], [data]); useEffect(() => { - if (!scrollToBestMatch.current || !bestMatch) return; + // Wait for the list sorted by best match, not the previous list that is + // still shown while it loads + if ( + !scrollToBestMatch.current || + !bestMatch || + activeSort !== PREFERENCES_SORT || + !currentData + ) { + return; + } const element = document.getElementById(`plant-${bestMatch.id}`); @@ -109,9 +129,12 @@ export default function MyMatchesPage() { block: "center", }); + // Show the details on the back of the card too + bestMatchCardRef.current?.showDetails(); + scrollToBestMatch.current = false; } - }, [plants, bestMatch]); + }, [plants, bestMatch, activeSort, currentData, scrollRequest]); const totalCount = data?.myMatches.totalCount ?? 0; const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE)); // Only show the loading text when there is nothing to show yet @@ -175,24 +198,24 @@ export default function MyMatchesPage() { )} {bestMatch && ( -
-
-

{t("myMatchesPage.compatible-plant")}

-

{bestMatch.name}

-
+ + + {t("myMatchesPage.compatible-plant")} + + {bestMatch.name} + + {/* The name is already in the text, so the picture is decorative */} {bestMatch.imageURL && ( - {bestMatch.name + )} -
+ )} {/* Hidden when user has no preferences set in their profile.*/} @@ -250,7 +273,11 @@ export default function MyMatchesPage() { key={plant.id} data-testid="plant-item" > - + {/* Every plant here is matched, so the button only removes */} (null); + // The card that flies off. A liked plant is saved as a match at once, and + // matched plants are left out of the deck, so the deck already shows the + // next plant. The liked card is kept on screen until it has flown off. + const [leavingPlant, setLeavingPlant] = useState(null); + const shownPlant = leaving ? leavingPlant : plant; const dragStartRef = useRef<{ x: number; y: number } | null>(null); const draggedRef = useRef(false); const timeoutRef = useRef(undefined); @@ -55,6 +61,7 @@ export default function PlantMatchPage() { const showNextPlant = () => { goToNextPlant(); setLeaving(null); + setLeavingPlant(null); setDragX(0); }; @@ -67,6 +74,7 @@ export default function PlantMatchPage() { showNextPlant(); return; } + setLeavingPlant(plant); setLeaving(direction); timeoutRef.current = window.setTimeout(showNextPlant, SWIPE_OUT_MS); }; @@ -183,9 +191,9 @@ export default function PlantMatchPage() { )} - {!loading && !error && plant && ( + {!loading && !error && shownPlant && (
- +
)} - {!loading && !error && noMorePlants && ( + {!loading && !error && noMorePlants && !leaving && (
diff --git a/frontend/src/tests/ExplorePlantsPage.test.tsx b/frontend/src/tests/ExplorePlantsPage.test.tsx index 1c2c0792..da0fbc7a 100644 --- a/frontend/src/tests/ExplorePlantsPage.test.tsx +++ b/frontend/src/tests/ExplorePlantsPage.test.tsx @@ -3,7 +3,7 @@ import { act, render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { MockedProvider } from "@apollo/client/testing/react"; import { MemoryRouter, useLocation } from "react-router-dom"; -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { describe, it, expect, vi, beforeEach } from "vitest"; import ExplorePlantsPage from "../pages/explorePlants/ExplorePlantsPage"; import { EXPLORE_PLANTS, PAGE_SIZE } from "../graphql/plants/queries"; @@ -165,28 +165,21 @@ function setup( const cards = () => screen.queryAllByTestId("plant-card"); const cardNames = () => cards().map((card) => card.textContent); -// Move past the 300 ms search debounce +// Wait out the 300 ms search debounce. Real timers are used, since fake +// timers that move on by themselves (shouldAdvanceTime) let the mocked +// responses arrive outside act(), which gave act() warnings. async function advanceDebounce() { - await act(async () => { - vi.advanceTimersByTime(300); - }); + await act(() => new Promise((resolve) => setTimeout(resolve, 300))); } describe("ExplorePlantsPage", () => { beforeEach(() => { - // shouldAdvanceTime keeps userEvent and findBy* from hanging with fake timers - vi.useFakeTimers({ shouldAdvanceTime: true }); matchedPlants.matchedPlantIds = []; matchedPlants.addMatch.mockReset(); matchedPlants.removeMatch.mockReset(); currentUser.preferences = []; }); - // Restore real timers after each test - afterEach(() => { - vi.useRealTimers(); - }); - // What the user sees while the query is loading, when it fails, and when // it returns no plants (the page navigation is hidden when there are no results). describe("loading, errors and empty results", () => { diff --git a/frontend/src/tests/MyMatchesPage.test.tsx b/frontend/src/tests/MyMatchesPage.test.tsx index 72f97327..4d808747 100644 --- a/frontend/src/tests/MyMatchesPage.test.tsx +++ b/frontend/src/tests/MyMatchesPage.test.tsx @@ -421,6 +421,10 @@ describe("myMatchesPage", () => { // Sorting by the user's preferences, read from the user in the backend describe("best match first", () => { + // The box with the user's most compatible plant + const bestMatchButton = () => + screen.getByRole("button", { name: /myMatchesPage.compatible-plant/ }); + // A user with saved preferences function mockUserWithPreferences() { useUser.mockReturnValue({ @@ -479,6 +483,23 @@ describe("myMatchesPage", () => { expect(lastVariables()).toMatchObject({ sort: "newest" }); }); + it("shows the picture of the best match from the backend's address", () => { + mockUserWithPreferences(); + mockMatches([{ ...orchid, imageURL: "/images/1" }]); + + render(); + + // The name is in the text of the button, so the picture is decorative + const picture = bestMatchButton().querySelector("img"); + expect(picture).toHaveAttribute("alt", ""); + // The path from the backend is turned into the backend's address, so + // the picture also works on the VM, where the backend is on another port + expect(picture).toHaveAttribute( + "src", + new URL("/images/1", window.location.href).href, + ); + }); + it("shows the best match when clicked", async () => { const user = userEvent.setup(); mockUserWithPreferences(); @@ -503,28 +524,23 @@ describe("myMatchesPage", () => { value: scrollIntoView, }); - useQuery.mockImplementation((_query, options) => { - const plants = [orchid]; - - return { - data: { - myMatches: { - totalCount: 1, - plants: options.variables.limit === 1 ? [orchid] : plants, - filterCounts: makeFilterCounts(), - }, + // The same objects on every render, like Apollo's cache, so the list + // only changes when the data really changes + const result = { + data: { + myMatches: { + totalCount: 1, + plants: [orchid], + filterCounts: makeFilterCounts(), }, - loading: false, - }; - }); + }, + loading: false, + }; + useQuery.mockReturnValue(result); render(); - fireEvent.click( - screen - .getByText("myMatchesPage.compatible-plant") - .closest('[role="button"]')!, - ); + fireEvent.click(bestMatchButton()); await waitFor(() => { expect(scrollIntoView).toHaveBeenCalledWith({ @@ -533,7 +549,34 @@ describe("myMatchesPage", () => { }); }); + // The card is turned to the details of the plant + expect(document.querySelector(".plant-card-flipper")).toHaveClass( + "is-flipped", + ); + + // The list is already sorted by best match now, so nothing else + // changes, but a new click still scrolls to the plant, and the card + // stays on the details instead of turning back + fireEvent.click(bestMatchButton()); + await waitFor(() => expect(scrollIntoView).toHaveBeenCalledTimes(2)); + expect(document.querySelector(".plant-card-flipper")).toHaveClass( + "is-flipped", + ); + delete (HTMLElement.prototype as Partial).scrollIntoView; }); + + it("can be chosen with the keyboard", async () => { + const user = userEvent.setup(); + mockUserWithPreferences(); + mockMatches([orchid]); + + render(); + + bestMatchButton().focus(); + await user.keyboard("{Enter}"); + + expect(lastVariables()).toMatchObject({ sort: "preferences" }); + }); }); }); diff --git a/frontend/src/tests/Pagination.test.tsx b/frontend/src/tests/Pagination.test.tsx new file mode 100644 index 00000000..3ac08d2f --- /dev/null +++ b/frontend/src/tests/Pagination.test.tsx @@ -0,0 +1,60 @@ +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, it, expect, vi } from "vitest"; +import Pagination from "../components/pagination/Pagination"; + +// The key, with the page number when there is one, so each page button has +// its own name +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ + t: (key: string, options?: { page?: number }) => + options?.page ? `${key} ${options.page}` : key, + }), +})); + +function renderPagination(page: number, totalPages = 5) { + const onPageChange = vi.fn(); + render( + , + ); + return { onPageChange }; +} + +const pageButton = (page: number) => + screen.getByRole("button", { name: `pagination.goToPage ${page}` }); + +describe("Pagination", () => { + it("goes straight to a page when its number is clicked", async () => { + const { onPageChange } = renderPagination(1); + + await userEvent.click(pageButton(3)); + + expect(onPageChange).toHaveBeenCalledWith(3); + }); + + it("marks the current page, and does nothing when it is clicked", async () => { + const { onPageChange } = renderPagination(2); + + expect(pageButton(2)).toHaveAttribute("aria-current", "page"); + expect(pageButton(3)).not.toHaveAttribute("aria-current"); + + await userEvent.click(pageButton(2)); + + expect(onPageChange).not.toHaveBeenCalled(); + }); + + it("can't go before the first or after the last page", () => { + renderPagination(1, 1); + + expect( + screen.getByRole("button", { name: /pagination.previous/ }), + ).toBeDisabled(); + expect( + screen.getByRole("button", { name: /pagination.next/ }), + ).toBeDisabled(); + }); +}); diff --git a/frontend/src/tests/PlantCard.test.tsx b/frontend/src/tests/PlantCard.test.tsx index f650c6c3..cc1dcb01 100644 --- a/frontend/src/tests/PlantCard.test.tsx +++ b/frontend/src/tests/PlantCard.test.tsx @@ -1,7 +1,10 @@ -import { render, screen } from "@testing-library/react"; +import { createRef } from "react"; +import { act, 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"; +import PlantCard, { + type PlantCardHandle, +} from "../components/plantCard/PlantCard"; import type { Plant } from "../types/Plant"; const { useUser } = vi.hoisted(() => ({ useUser: vi.fn() })); @@ -33,6 +36,21 @@ const makePlant = (fields: Partial = {}): Omit => ({ }); describe("PlantCard", () => { + it("can be turned to the details by the page, and stays there", () => { + const ref = createRef(); + const { container } = render( + , + ); + expect(container.firstChild).not.toHaveClass("is-flipped"); + + act(() => ref.current?.showDetails()); + expect(container.firstChild).toHaveClass("is-flipped"); + + // Asking again does not turn it back + act(() => ref.current?.showDetails()); + expect(container.firstChild).toHaveClass("is-flipped"); + }); + it("flips to the details when the card is clicked, and back again", async () => { const user = userEvent.setup(); const onInfo = vi.fn(); diff --git a/frontend/src/tests/PlantMatchPage.test.tsx b/frontend/src/tests/PlantMatchPage.test.tsx index 662b2bd2..a41933cc 100644 --- a/frontend/src/tests/PlantMatchPage.test.tsx +++ b/frontend/src/tests/PlantMatchPage.test.tsx @@ -1,11 +1,12 @@ import { + act, fireEvent, render, screen, waitFor, within, } from "@testing-library/react"; -import { beforeEach, describe, it, expect, vi } from "vitest"; +import { afterEach, beforeEach, describe, it, expect, vi } from "vitest"; import PlantMatchPage from "../pages/plantMatch/PlantMatchPage"; import { DECK_STORAGE_KEY, @@ -90,6 +91,8 @@ beforeEach(() => { describe("PlantMatchPage", () => { it("links the info button to the instructions and hides them with Escape", async () => { render(); + // Wait for the first plant, so the deck is not updated after the test + await screen.findAllByText("Hydrangea"); const infoButton = screen.getByRole("button", { name: "plantMatchPage.howToMatch", }); @@ -437,4 +440,194 @@ describe("PlantMatchPage", () => { expect(query).not.toHaveBeenCalled(); expect(screen.getByText("plantMatchPage.loading")).toBeInTheDocument(); }); + + describe("swiping the card", () => { + // The card that is dragged, around the plant card + const card = () => document.querySelector(".swipe-card")!; + const flipper = () => document.querySelector(".plant-card-flipper")!; + + // Presses the left mouse button on the card and moves it dx and dy pixels + function dragBy(dx: number, dy = 0) { + fireEvent.pointerDown(card(), { button: 0, clientX: 0, clientY: 0 }); + fireEvent.pointerMove(card(), { clientX: dx, clientY: dy }); + } + + async function renderFirstPlant() { + render(); + await screen.findAllByText("Hydrangea"); + } + + it("matches the plant when the card is dragged far enough right", async () => { + await renderFirstPlant(); + + dragBy(150); + expect(card()).toHaveClass("is-dragging", "is-liking"); + fireEvent.pointerUp(card()); + + // Hydrangea, the first plant + expect(addUserMatch).toHaveBeenCalledWith({ + variables: { userId: "user-1", plantId: "0" }, + }); + expect(screen.getAllByText("Orchid").length).toBeGreaterThan(0); + }); + + it("skips the plant when the card is dragged far enough left", async () => { + await renderFirstPlant(); + + dragBy(-150); + expect(card()).toHaveClass("is-skipping"); + fireEvent.pointerUp(card()); + + expect(addUserMatch).not.toHaveBeenCalled(); + expect(screen.getAllByText("Orchid").length).toBeGreaterThan(0); + }); + + it("moves the card back when it is let go before the threshold, without flipping it", async () => { + await renderFirstPlant(); + + dragBy(60); + expect(card()).toHaveStyle({ + transform: "translateX(60px) rotate(3deg)", + }); + fireEvent.pointerUp(card()); + // The click that ends the drag does not flip the card + fireEvent.click(card().querySelector(".plant-card-flip-target")!); + + expect(card()).toHaveStyle({ transform: "translateX(0px) rotate(0deg)" }); + expect(card()).not.toHaveClass("is-dragging"); + expect(flipper()).not.toHaveClass("is-flipped"); + expect(addUserMatch).not.toHaveBeenCalled(); + expect(screen.getAllByText("Hydrangea").length).toBeGreaterThan(0); + }); + + it("flips the card on a tap that hardly moves", async () => { + await renderFirstPlant(); + + dragBy(4); + fireEvent.pointerUp(card()); + fireEvent.click(card().querySelector(".plant-card-flip-target")!); + + expect(card()).not.toHaveClass("is-dragging"); + expect(flipper()).toHaveClass("is-flipped"); + }); + + it("lets the page scroll when the movement is mostly up or down", async () => { + await renderFirstPlant(); + + dragBy(20, 80); + // Moving sideways afterwards does not start a drag + fireEvent.pointerMove(card(), { clientX: 200, clientY: 80 }); + fireEvent.pointerUp(card()); + + expect(card()).toHaveStyle({ transform: "translateX(0px) rotate(0deg)" }); + expect(screen.getAllByText("Hydrangea").length).toBeGreaterThan(0); + }); + + it("ignores other mouse buttons and moves without a press", async () => { + await renderFirstPlant(); + + fireEvent.pointerMove(card(), { clientX: 200 }); + fireEvent.pointerUp(card()); + fireEvent.pointerDown(card(), { button: 2, clientX: 0, clientY: 0 }); + fireEvent.pointerMove(card(), { clientX: 200, clientY: 0 }); + fireEvent.pointerUp(card()); + + expect(card()).toHaveStyle({ transform: "translateX(0px) rotate(0deg)" }); + expect(screen.getAllByText("Hydrangea").length).toBeGreaterThan(0); + }); + + describe("with animations", () => { + beforeEach(() => { + // The user does not prefer reduced motion + vi.stubGlobal("matchMedia", () => ({ matches: false })); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + it("lets the card fly off before the next plant, and ignores swipes meanwhile", async () => { + await renderFirstPlant(); + vi.useFakeTimers(); + + fireEvent.click( + screen.getByRole("button", { name: "plantMatchPage.likePlant" }), + ); + // The match is saved at once, while the card flies off + expect(card()).toHaveClass("is-leaving-right"); + expect(addUserMatch).toHaveBeenCalledTimes(1); + + // A second like or a drag while it flies off does nothing + fireEvent.click( + screen.getByRole("button", { name: "plantMatchPage.likePlant" }), + ); + dragBy(150); + fireEvent.pointerUp(card()); + expect(addUserMatch).toHaveBeenCalledTimes(1); + expect(card()).not.toHaveClass("is-dragging"); + + act(() => vi.advanceTimersByTime(300)); + + expect(screen.getAllByText("Orchid").length).toBeGreaterThan(0); + expect(card()).not.toHaveClass("is-leaving-right"); + }); + + it("keeps the liked card on screen while it flies off, though it is already matched", async () => { + const { rerender } = render(); + await screen.findAllByText("Hydrangea"); + vi.useFakeTimers(); + + fireEvent.click( + screen.getByRole("button", { name: "plantMatchPage.likePlant" }), + ); + // The match is saved at once, so the user now has Hydrangea as a match, + // and the deck would show the next plant + mockUser([], ["0"]); + rerender(); + + expect(card()).toHaveClass("is-leaving-right"); + expect(screen.getAllByText("Hydrangea").length).toBeGreaterThan(0); + expect(screen.queryByText("Orchid")).not.toBeInTheDocument(); + + act(() => vi.advanceTimersByTime(300)); + + // The next plant comes in without flying, and no plant is skipped + expect(screen.getAllByText("Orchid").length).toBeGreaterThan(0); + expect(card()).not.toHaveClass("is-leaving-right"); + }); + + it("shows the end card only after the last card has flown off", async () => { + mockBackend([plants[0]]); + const { rerender } = render(); + await screen.findAllByText("Hydrangea"); + vi.useFakeTimers(); + + fireEvent.click( + screen.getByRole("button", { name: "plantMatchPage.likePlant" }), + ); + mockUser([], ["0"]); + rerender(); + + expect( + screen.queryByRole("heading", { + name: /plantMatchPage\.(noMorePlants|allMatched)Title/, + }), + ).not.toBeInTheDocument(); + + act(() => vi.advanceTimersByTime(300)); + + // The last card is gone, and no other plant took its place + expect(document.querySelector(".swipe-card")).not.toBeInTheDocument(); + // Then the end card is shown, once the page has checked whether + // every plant is matched + vi.useRealTimers(); + expect( + await screen.findByRole("heading", { + name: /plantMatchPage\.(noMorePlants|allMatched)Title/, + }), + ).toBeInTheDocument(); + }); + }); + }); }); diff --git a/frontend/src/tests/ProfilePage.test.tsx b/frontend/src/tests/ProfilePage.test.tsx index ac9f06e6..87f1392e 100644 --- a/frontend/src/tests/ProfilePage.test.tsx +++ b/frontend/src/tests/ProfilePage.test.tsx @@ -1,4 +1,4 @@ -import { render, screen, waitFor } from "@testing-library/react"; +import { act, render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { beforeEach, describe, it, expect, vi } from "vitest"; @@ -212,7 +212,7 @@ describe("Profile page", () => { }); // When the debounce runs later, the same text is not sent again - await new Promise((resolve) => setTimeout(resolve, 600)); + await act(() => new Promise((resolve) => setTimeout(resolve, 600))); expect(savesOfName("Nina")).toHaveLength(1); }); diff --git a/frontend/src/tests/Sidebar.test.tsx b/frontend/src/tests/Sidebar.test.tsx index 02566067..8394d10e 100644 --- a/frontend/src/tests/Sidebar.test.tsx +++ b/frontend/src/tests/Sidebar.test.tsx @@ -1,17 +1,25 @@ 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 { afterEach, describe, it, expect, vi } from "vitest"; import Sidebar from "../components/sidebar/Sidebar"; import { ROUTES } from "../AppRoutes"; -// mock i18next to return the key as the translation +// mock i18next to return the key as the translation, unless a test sets +// a real text in translations +const { translations } = vi.hoisted(() => ({ + translations: {} as Record, +})); vi.mock("react-i18next", () => ({ useTranslation: () => ({ - t: (key: string) => key, + t: (key: string) => translations[key] ?? key, }), })); +afterEach(() => { + for (const key of Object.keys(translations)) delete translations[key]; +}); + // replace the child components with simple stand-ins. They have their own // tests (or are not part of what we test here), and this keeps the Sidebar // test focused on the Sidebar itself @@ -56,6 +64,13 @@ describe("Sidebar", () => { expect(open.onCloseSidebar).toHaveBeenCalledTimes(1); }); + it("does not close on other keys", async () => { + const { user, onCloseSidebar } = renderSidebar({ isOpen: true }); + // Not Enter or Space, since focus is on the close button + await user.keyboard("a"); + expect(onCloseSidebar).not.toHaveBeenCalled(); + }); + it("does not react to Escape while it is closed", async () => { const { user, onCloseSidebar } = renderSidebar({ isOpen: false }); await user.keyboard("{Escape}"); @@ -74,6 +89,15 @@ describe("Sidebar", () => { ).toBeInTheDocument(); }); + it("puts the heart in the title in its own element, so it can be green", () => { + translations["sidebar.title"] = "I <3 Plants"; + renderSidebar(); + + const heading = screen.getByRole("heading", { level: 2 }); + expect(heading).toHaveTextContent("I <3 Plants"); + expect(heading.querySelector(".sidebar-heart")).toHaveTextContent("<3"); + }); + it("displays navigation links to all pages", () => { renderSidebar(); diff --git a/frontend/src/tests/UserContext.test.tsx b/frontend/src/tests/UserContext.test.tsx index b8471333..c372b528 100644 --- a/frontend/src/tests/UserContext.test.tsx +++ b/frontend/src/tests/UserContext.test.tsx @@ -1,7 +1,7 @@ import type { ComponentProps } from "react"; -import { render, screen, waitFor } from "@testing-library/react"; +import { act, render, screen, waitFor } from "@testing-library/react"; import { MockedProvider } from "@apollo/client/testing/react"; -import { beforeEach, describe, it, expect, vi } from "vitest"; +import { afterEach, beforeEach, describe, it, expect, vi } from "vitest"; import { UserProvider, useUser } from "../context/UserContext"; import { GET_USER } from "../graphql/user/queries"; import { CREATE_USER } from "../graphql/user/mutations"; @@ -124,6 +124,51 @@ describe("UserContext", () => { expect(localStorage.getItem("userId")).toBe("user-1"); }); + describe("when the backend is down", () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it("keeps trying every five seconds and shows the user once it is back", async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + localStorage.setItem("userId", "user-1"); + const offline = { + request: { query: GET_USER, variables: { userId: "user-1" } }, + error: new Error("Offline"), + }; + // Down at first and on the first retry, back on the second + setup([ + offline, + offline, + getUserMock("user-1", makeUser("user-1", "Nina")), + ]); + + await waitFor(() => + expect(screen.getByTestId("loading")).toHaveTextContent("false"), + ); + expect(screen.getByTestId("user-name")).toHaveTextContent("none"); + + await act(() => vi.advanceTimersByTimeAsync(5000)); + expect(screen.getByTestId("user-name")).toHaveTextContent("none"); + + await act(() => vi.advanceTimersByTimeAsync(5000)); + expect(await screen.findByText("Nina")).toBeInTheDocument(); + }); + }); + + it("starts without a saved user when browser storage is blocked", async () => { + vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => { + throw new Error("Blocked"); + }); + const create = createUserMock(makeUser("new-user")); + setup([create, getUserMock("new-user", makeUser("new-user", "Nina"))]); + + // No saved user could be read, so a new one is created and loaded + expect(await screen.findByText("Nina")).toBeInTheDocument(); + expect(create.result).toHaveBeenCalled(); + vi.restoreAllMocks(); + }); + it("keeps working when creating a user fails", async () => { setup([{ request: { query: CREATE_USER }, error: new Error("Offline") }]); diff --git a/frontend/src/tests/setup.ts b/frontend/src/tests/setup.ts index 505180fa..83959af9 100644 --- a/frontend/src/tests/setup.ts +++ b/frontend/src/tests/setup.ts @@ -17,3 +17,9 @@ if (!HTMLDialogElement.prototype.close) { this.open = false; }; } + +// jsdom does not lay out the page, so it has no scrollIntoView. A test that +// checks the scrolling replaces it with a spy. +if (!Element.prototype.scrollIntoView) { + Element.prototype.scrollIntoView = function () {}; +} diff --git a/frontend/src/tests/useDismissibleTooltip.test.ts b/frontend/src/tests/useDismissibleTooltip.test.ts new file mode 100644 index 00000000..5ea4b249 --- /dev/null +++ b/frontend/src/tests/useDismissibleTooltip.test.ts @@ -0,0 +1,38 @@ +import type { KeyboardEvent } from "react"; +import { act, renderHook } from "@testing-library/react"; +import { describe, it, expect } from "vitest"; +import { useDismissibleTooltip } from "../hooks/useDismissibleTooltip"; + +// The parts of a keyboard event the hook reads +const press = (key: string) => ({ key }) as KeyboardEvent; + +describe("useDismissibleTooltip", () => { + it("hides the text with Escape, but not with other keys", () => { + const { result } = renderHook(() => useDismissibleTooltip()); + expect(result.current.isDismissed).toBe(false); + + act(() => result.current.wrapperProps.onKeyDown(press("Enter"))); + expect(result.current.isDismissed).toBe(false); + + act(() => result.current.wrapperProps.onKeyDown(press("Escape"))); + expect(result.current.isDismissed).toBe(true); + }); + + it("shows the text again when the mouse leaves", () => { + const { result } = renderHook(() => useDismissibleTooltip()); + + act(() => result.current.wrapperProps.onKeyDown(press("Escape"))); + act(() => result.current.wrapperProps.onMouseLeave()); + + expect(result.current.isDismissed).toBe(false); + }); + + it("shows the text again when focus leaves", () => { + const { result } = renderHook(() => useDismissibleTooltip()); + + act(() => result.current.wrapperProps.onKeyDown(press("Escape"))); + act(() => result.current.wrapperProps.onBlur()); + + expect(result.current.isDismissed).toBe(false); + }); +}); diff --git a/frontend/src/tests/usePreferences.test.ts b/frontend/src/tests/usePreferences.test.ts new file mode 100644 index 00000000..b701c405 --- /dev/null +++ b/frontend/src/tests/usePreferences.test.ts @@ -0,0 +1,76 @@ +import { act, renderHook } from "@testing-library/react"; +import { beforeEach, describe, it, expect, vi } from "vitest"; +import { usePreferences } from "../hooks/usePreferences"; + +const { updatePreferences, useUser } = vi.hoisted(() => ({ + updatePreferences: vi.fn(), + useUser: vi.fn(), +})); +vi.mock("@apollo/client/react", () => ({ + useMutation: () => [updatePreferences], +})); +vi.mock("../context/UserContext", () => ({ useUser })); + +// Saves the preferences and returns whether it worked +async function save(preferences: string[]) { + const { result } = renderHook(() => usePreferences()); + let saved = false; + await act(async () => { + saved = await result.current.savePreferences(preferences); + }); + return saved; +} + +describe("usePreferences", () => { + beforeEach(() => { + updatePreferences.mockReset(); + useUser.mockReturnValue({ + userId: "user-1", + user: { id: "user-1", preferences: ["fullSun"] }, + }); + }); + + it("returns the saved preferences, and that they can be saved", () => { + const { result } = renderHook(() => usePreferences()); + + expect(result.current.preferences).toEqual(["fullSun"]); + expect(result.current.canSave).toBe(true); + }); + + it("says the preferences were saved when the server returns the user", async () => { + updatePreferences.mockResolvedValue({ + data: { updateUserPreferences: { id: "user-1" } }, + }); + + expect(await save(["partShade"])).toBe(true); + expect(updatePreferences.mock.lastCall?.[0].variables).toEqual({ + userId: "user-1", + preferences: ["partShade"], + }); + }); + + it("says they were not saved when the user is not found", async () => { + updatePreferences.mockResolvedValue({ + data: { updateUserPreferences: null }, + }); + + expect(await save(["partShade"])).toBe(false); + }); + + it("says they were not saved when the request fails", async () => { + updatePreferences.mockRejectedValue(new Error("Offline")); + + expect(await save(["partShade"])).toBe(false); + }); + + it("saves nothing before the user exists", async () => { + useUser.mockReturnValue({ userId: null, user: null }); + + const { result } = renderHook(() => usePreferences()); + expect(result.current.preferences).toEqual([]); + expect(result.current.canSave).toBe(false); + + expect(await save(["partShade"])).toBe(false); + expect(updatePreferences).not.toHaveBeenCalled(); + }); +});