From aab209f065086abae182a163fdc930606758db4e Mon Sep 17 00:00:00 2001 From: Helene Lotsberg Date: Sun, 22 Nov 2026 15:32:43 +0100 Subject: [PATCH 1/6] find elements by role and name instead of CSS classes in E2E tests --- docs/architecture.md | 2 +- docs/tests.md | 2 + e2e/helpers/names.ts | 46 +++++ e2e/helpers/navigation.ts | 19 +- e2e/uiExplorePlants.spec.ts | 48 ++--- e2e/uiImages.spec.ts | 24 ++- e2e/uiMatchAndRemovePlant.spec.ts | 169 +++++++++--------- e2e/uiUserProfile.spec.ts | 35 ++-- .../src/components/plantCard/PlantCard.tsx | 5 +- .../pages/explorePlants/ExplorePlantsPage.tsx | 6 +- .../src/pages/myMatches/MyMatchesPage.tsx | 6 +- frontend/src/pages/profile/ProfilePage.tsx | 1 + .../ExplorePlantsPage.test.tsx.snap | 15 ++ 13 files changed, 242 insertions(+), 136 deletions(-) create mode 100644 e2e/helpers/names.ts diff --git a/docs/architecture.md b/docs/architecture.md index e556b12c..9cb5f9a1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -288,7 +288,7 @@ T03-Project-2/ ├── docs/ # Project documentation (architecture, tests, quality, AI usage), media/ has the coverage images ├── e2e/ # Playwright e2e and API tests │ ├── fixtures/ # The 20 test plants -│ ├── helpers/ # Shared helpers for GraphQL requests and navigation +│ ├── helpers/ # Shared helpers for GraphQL requests, navigation and the accessible names used by the UI tests │ ├── api*.spec.ts # API tests, GraphQL requests straight to the backend │ ├── ui*.spec.ts # UI tests in the browser, including accessibility (uiAccessibility.spec.ts) │ ├── globalSetup.ts # Empties the test database and adds the test plants before the tests diff --git a/docs/tests.md b/docs/tests.md index d60e7c72..ec7faf6e 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -223,6 +223,8 @@ Other choices in the config: Each file covers one scenario, and API and UI tests for the same feature come in pairs. The **API tests** check the backend logic over HTTP, including atypical input that is hard to reach through the UI. The **UI tests** check that the frontend is correctly connected to the backend and that the user journeys work from start to finish. +The UI tests find elements the way a user or a screen reader would: by role, label and accessible name (`getByRole`, `getByLabel`), not by CSS classes or ids. A test then only breaks when something changes that the user notices, not when the styling is refactored, and an element without an accessible name cannot be found, so the tests also check that the controls are labelled. The app can run in Norwegian and English, so the names are written once in both languages in `e2e/helpers/names.ts`. Elements without a natural role, such as the plant cards in a list, the avatar pictures (decorative, `alt=""`) and the placeholder picture (a CSS background), have a `data-testid`. + | Feature | API test | UI test | | ----------------------------------------- | ------------------------ | ----------------------- | | Search, filter, sort, pagination, details | `apiExplorePlants` | `uiExplorePlants` | diff --git a/e2e/helpers/names.ts b/e2e/helpers/names.ts new file mode 100644 index 00000000..7d5732c2 --- /dev/null +++ b/e2e/helpers/names.ts @@ -0,0 +1,46 @@ +// The accessible names the UI tests use to find elements, in both languages. +// The app can run in Norwegian or English, so every name matches both, and the +// tests do not depend on CSS classes that may change when the styling changes. +// The texts come from frontend/src/i18n/locales/{en,no}/translation.json. +export const names = { + // Sidebar + openSidebar: /^(open sidebar|åpne sidemeny)$/i, + sidebarNavigation: /^(sidebar navigation|navigasjon i sidemenyen)$/i, + plantMatch: /^(plant match|plante-matching)$/i, + myMatches: /^(my matches|mine matches)$/i, + explorePlants: /^(explore plants|utforsk planter)$/i, + + // Plant Match + likePlant: /^(like plant|lik planten)$/i, + skipPlant: /^(skip plant|hopp over planten)$/i, + done: /^(done!|ferdig!)$/i, + + // Plant cards + tapForDetails: + /^(tap the corner of the card for details|trykk på hjørnet for detaljer om planten)$/i, + tapToFlipBack: /^(tap to flip back|trykk for å snu tilbake)$/i, + // The match button says what a click does, so its name changes with the state + matchButton: /my matches|mine matches/i, + addMatch: /^(add to my matches|legg til i mine matches)$/i, + removeMatch: /^(remove from my matches|fjern fra mine matches)$/i, + + // Explore Plants and My Matches + // A select's name also has the chosen option, e.g. "Care level All (20)" + careLevel: /^(care level|stell)\b/i, + // The sort button's name also has the chosen order, e.g. "Sort: Name (A-Z)" + sortButton: /^(sort|sorter):/i, + nameAZ: /^(name|navn) \(a-z\)$/i, + nameZA: /^(name|navn) \(z-a\)$/i, + reset: /^(reset|nullstill)$/i, + pageNavigation: /^(page navigation|sidenavigasjon)$/i, + next: /^(next|neste)$/i, + previous: /^(previous|forrige)$/i, + noMatches: /no matches|ingen matcher/i, + + // Profile + editProfile: /^(edit profile|endre profil)$/i, + nameField: /write your name|skriv ditt navn/i, + descriptionField: /write something about you|skriv noe om deg selv/i, + // "Profile picture: " + profilePicture: /^(profile picture|profilbilde):/i, +}; diff --git a/e2e/helpers/navigation.ts b/e2e/helpers/navigation.ts index f609e4bf..3a4ce1dd 100644 --- a/e2e/helpers/navigation.ts +++ b/e2e/helpers/navigation.ts @@ -1,15 +1,26 @@ import { expect, type Page } from "@playwright/test"; +import { names } from "./names"; // Shared navigation helpers for the UI tests (ui*.spec.ts) // Opens the sidebar menu on small screens. On desktop the sidebar is always // visible and has no open button, so there is nothing to do. export async function openSidebar(page: Page) { - const openButton = page.getByRole("button", { - name: /open sidebar|åpne sidemeny/i, - }); + const openButton = page.getByRole("button", { name: names.openSidebar }); if (!(await openButton.isVisible())) return; await openButton.click(); - await expect(page.locator("#sidebar")).toHaveAttribute("data-open", "true"); + // The closed sidebar is hidden, so the navigation is only visible once it is open + await expect( + page.getByRole("navigation", { name: names.sidebarNavigation }), + ).toBeVisible(); +} + +// Goes to another page with the link in the sidebar, like a user would +export async function goToPage(page: Page, linkName: RegExp) { + await openSidebar(page); + await page + .getByRole("navigation", { name: names.sidebarNavigation }) + .getByRole("link", { name: linkName }) + .click(); } diff --git a/e2e/uiExplorePlants.spec.ts b/e2e/uiExplorePlants.spec.ts index 1016a177..8a635f57 100644 --- a/e2e/uiExplorePlants.spec.ts +++ b/e2e/uiExplorePlants.spec.ts @@ -1,21 +1,27 @@ import { test, expect } from "@playwright/test"; +import { names } from "./helpers/names"; // A continuous user journey on ExplorePlants, based on the 20 plants in -// e2e/fixtures/plants.json. The locators are language independent (roles, option values -// and CSS classes), so the test works in both Norwegian and English. +// e2e/fixtures/plants.json. Elements are found by role and accessible name, with +// the names in both languages (see helpers/names.ts), so the test works in +// Norwegian and English and does not depend on CSS classes. The plant cards have +// no role of their own, so they are found by data-testid. test("user pages, filters, searches, opens a plant, sorts and resets", async ({ page, }) => { - const cards = page.locator(".plant-grid > li"); + const cards = page.getByTestId("plant-item"); const searchField = page.getByRole("searchbox"); - // Care level is the only select with "high" as an option - const careLevelSelect = page.locator("select").filter({ - has: page.locator('option[value="high"]'), + const careLevelSelect = page.getByRole("combobox", { + name: names.careLevel, }); - const pagination = page.locator(".pagination"); - const previousButton = pagination.getByRole("button").first(); - const nextButton = pagination.getByRole("button").last(); + const pagination = page.getByRole("navigation", { + name: names.pageNavigation, + }); + const previousButton = pagination.getByRole("button", { + name: names.previous, + }); + const nextButton = pagination.getByRole("button", { name: names.next }); await test.step("the first page shows 12 plants sorted a–z", async () => { await page.goto("#/explorePlants"); @@ -50,29 +56,31 @@ test("user pages, filters, searches, opens a plant, sorts and resets", async ({ await test.step("opening a plant shows its details", async () => { const jadeCard = cards.nth(0); - const details = jadeCard.locator(".plant-card-face-back"); + // Only the side of the card that is shown is in the accessibility tree, + // the other side is aria-hidden. So this is always the side the user sees. + const shownSide = jadeCard.getByRole("article"); - await jadeCard.locator(".plant-card-front .plant-card-hint").click(); - await expect(details).toHaveAttribute("aria-hidden", "false"); - await expect(details).toContainText("Crassula ovata"); - await expect(details).toContainText("Low"); - await expect(details).toContainText( + await expect(shownSide).not.toContainText("Crassula ovata"); + await jadeCard.getByRole("button", { name: names.tapForDetails }).click(); + await expect(shownSide).toContainText("Crassula ovata"); + await expect(shownSide).toContainText("Low"); + await expect(shownSide).toContainText( "A succulent with round, glossy leaves.", ); // Flip the card back so the next steps see the front again - await details.locator(".plant-card-hint").click(); - await expect(details).toHaveAttribute("aria-hidden", "true"); + await jadeCard.getByRole("button", { name: names.tapToFlipBack }).click(); + await expect(shownSide).not.toContainText("Crassula ovata"); }); await test.step("sorting z–a reverses the order", async () => { - await page.locator(".sort-button").click(); - await page.locator(".sort-option").nth(1).click(); // name_desc, see SORT_OPTIONS + await page.getByRole("button", { name: names.sortButton }).click(); + await page.getByRole("button", { name: names.nameZA }).click(); await expect(cards.first()).toContainText("Snake Plant"); }); await test.step("reset shows all plants again", async () => { - await page.locator(".reset-button").click(); + await page.getByRole("button", { name: names.reset }).click(); await expect(searchField).toHaveValue(""); await expect(cards).toHaveCount(12); await expect(cards.first()).toContainText("Aloe Vera"); diff --git a/e2e/uiImages.spec.ts b/e2e/uiImages.spec.ts index cbaade4f..6af52f8b 100644 --- a/e2e/uiImages.spec.ts +++ b/e2e/uiImages.spec.ts @@ -1,10 +1,14 @@ 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. // 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 +// pictures are decorative (alt="") and the placeholder is a CSS background, +// so those are found by data-testid. const BACKEND_GRAPHQL_URL = "http://localhost:3002/graphql"; @@ -49,13 +53,13 @@ test("the default profile picture and all avatars load", async ({ page }) => { await page.goto("#/profile"); // New users have the default profile picture - await expectImageLoaded(page.locator("img.profile-img")); + await expectImageLoaded( + page.getByRole("img", { name: names.profilePicture }), + ); - await page - .getByRole("button", { name: /edit profile|endre profil/i }) - .click(); + await page.getByRole("button", { name: names.editProfile }).click(); - const avatars = page.locator("button.avatar-option img"); + const avatars = page.getByTestId("avatar-option").locator("img"); await expect(avatars).toHaveCount(7); for (const avatar of await avatars.all()) { await expectImageLoaded(avatar); @@ -64,7 +68,9 @@ test("the default profile picture and all avatars load", async ({ page }) => { test("all pictures from the plant owner test load", async ({ page }) => { await page.goto("#/profile"); - await expect(page.locator("img.profile-img")).toBeVisible(); + await expect( + page.getByRole("img", { name: names.profilePicture }), + ).toBeVisible(); // The app stores the id of the user it created in localStorage const userId = await page.evaluate(() => localStorage.getItem("userId")); @@ -84,7 +90,9 @@ test("all pictures from the plant owner test load", async ({ page }) => { expect((await response.json()).errors).toBeUndefined(); await page.reload(); - const profileImage = page.locator("img.profile-img"); + const profileImage = page.getByRole("img", { + name: names.profilePicture, + }); // The default picture is shown until the user is loaded, so wait for the new one await expect(profileImage).not.toHaveAttribute("src", /profile/); await expectImageLoaded(profileImage); @@ -97,7 +105,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 - const missingImage = page.locator(".plant-card-image-missing").first(); + const missingImage = page.getByTestId("plant-image-missing").first(); await expect(missingImage).toBeVisible(); // The placeholder is a CSS background, so read the URL the browser actually uses diff --git a/e2e/uiMatchAndRemovePlant.spec.ts b/e2e/uiMatchAndRemovePlant.spec.ts index 09313dd6..83fd2b4d 100644 --- a/e2e/uiMatchAndRemovePlant.spec.ts +++ b/e2e/uiMatchAndRemovePlant.spec.ts @@ -1,39 +1,60 @@ -import { test, expect } from "@playwright/test"; -import { openSidebar } from "./helpers/navigation"; +import { test, expect, type Locator, type Page } from "@playwright/test"; +import { goToPage } from "./helpers/navigation"; +import { names } from "./helpers/names"; // User journeys for matching plants: from PlantMatch and from ExplorePlants, // that matches show up in MyMatches and can be removed from both MyMatches // and ExplorePlants, and that MyMatches can be sorted and paged. // Each test gets a new browser and therefore a new user with no matches. +// Elements are found by role and accessible name in both languages (see +// helpers/names.ts). The plant cards in the lists on ExplorePlants and +// MyMatches have no role of their own, so they are found by data-testid. + +// The cards in the list on ExplorePlants or MyMatches +const plantItems = (page: Page) => page.getByTestId("plant-item"); + +// The name on the plant card in PlantMatch. Only the side of the card that is +// shown is in the accessibility tree, so this is the name the user sees. +// Scoped to the page with the like button, since the previous page can still be +// on screen for a moment after navigating, and its cards also have names. +const plantMatchCardName = (page: Page) => + page + .getByRole("main") + .filter({ has: page.getByRole("button", { name: names.likePlant }) }) + .getByRole("article") + .getByRole("heading", { level: 2 }); + +// The button on a plant card that adds it to MyMatches, or removes it +const matchButtonIn = (item: Locator) => + item.getByRole("button", { name: names.matchButton }); test("user can like a plant in PlantMatch, find it in MyMatches and remove the match", async ({ page, }) => { await page.goto(""); - const likeButton = page.locator("button.like-button"); + const likeButton = page.getByRole("button", { name: names.likePlant }); + const cardName = plantMatchCardName(page); await expect(likeButton).toBeEnabled(); - await expect(page.locator(".plant-card-front")).toBeVisible(); + await expect(cardName).toBeVisible(); // Remember which plant was liked, since PlantMatch shows random plants - const likedName = ( - await page.locator(".plant-card-front .plant-card-name").textContent() - )?.trim(); + const likedName = (await cardName.textContent())?.trim(); expect(likedName).toBeTruthy(); await likeButton.click(); - await openSidebar(page); - await page.locator('a[href$="/myMatches"]').click(); + await goToPage(page, names.myMatches); - const matchCards = page.locator(".plant-card-match"); + const matchCards = plantItems(page); await expect(matchCards).toHaveCount(1); await expect(matchCards.first()).toContainText(likedName ?? ""); - await matchCards.first().locator(".remove-match-button").click(); + await matchCards + .first() + .getByRole("button", { name: names.removeMatch }) + .click(); await expect(matchCards).toHaveCount(0); - await expect(page.locator(".matches-grid")).toContainText( - /no matches|ingen matcher/i, - ); + await expect(page.getByRole("main")).toContainText(names.noMatches); }); test("user can add a plant from ExplorePlants, find it in MyMatches and remove it again from ExplorePlants", async ({ @@ -42,112 +63,102 @@ test("user can add a plant from ExplorePlants, find it in MyMatches and remove i await page.goto("#/explorePlants"); // The first plant sorted a–z is always Aloe Vera in the fixtures - const firstCard = page.locator(".plant-grid > li").first(); + const firstCard = plantItems(page).first(); await expect(firstCard).toContainText("Aloe Vera"); - const matchButton = firstCard.locator(".add-match-button"); - const matchCards = page.locator(".plant-card-match"); - await expect(matchButton).not.toHaveClass(/add-match-button--matched/); + // The name of the button says what a click does, so it shows the state + const matchButton = matchButtonIn(firstCard); + const matchCards = plantItems(page); + await expect(matchButton).toHaveAccessibleName(names.addMatch); await matchButton.click(); // The button shows that the plant is in MyMatches, and can still be clicked - await expect(matchButton).toHaveClass(/add-match-button--matched/); + await expect(matchButton).toHaveAccessibleName(names.removeMatch); await expect(matchButton).toBeEnabled(); - await openSidebar(page); - await page.locator('a[href$="/myMatches"]').click(); + await goToPage(page, names.myMatches); await expect(matchCards).toHaveCount(1); await expect(matchCards.first()).toContainText("Aloe Vera"); // Clicking the button again on ExplorePlants removes the match - await openSidebar(page); - await page.locator('a[href$="/explorePlants"]').click(); + await goToPage(page, names.explorePlants); await expect(firstCard).toContainText("Aloe Vera"); - await expect(matchButton).toHaveClass(/add-match-button--matched/); + await expect(matchButton).toHaveAccessibleName(names.removeMatch); await matchButton.click(); - await expect(matchButton).not.toHaveClass(/add-match-button--matched/); + await expect(matchButton).toHaveAccessibleName(names.addMatch); - await openSidebar(page); - await page.locator('a[href$="/myMatches"]').click(); + await goToPage(page, names.myMatches); await expect(matchCards).toHaveCount(0); }); test("user can sort the matches in MyMatches and move between pages", async ({ page, }) => { + const cards = plantItems(page); + const nextButton = page + .getByRole("navigation", { name: names.pageNavigation }) + .getByRole("button", { name: names.next }); + // Matches the 12 plants on the first Explore page (Aloe Vera first) and then // the first plant on the second page (Monstera), so MyMatches gets 2 pages await page.goto("#/explorePlants"); - const exploreCards = page.locator(".plant-grid > li"); - await expect(exploreCards).toHaveCount(12); + await expect(cards).toHaveCount(12); for (let i = 0; i < 12; i++) { - const button = exploreCards.nth(i).locator(".add-match-button"); + const button = matchButtonIn(cards.nth(i)); await button.click(); - await expect(button).toHaveClass(/add-match-button--matched/); + await expect(button).toHaveAccessibleName(names.removeMatch); } - await page.locator(".pagination").getByRole("button").last().click(); - await expect(exploreCards.first()).toContainText("Monstera"); - const lastButton = exploreCards.first().locator(".add-match-button"); + await nextButton.click(); + await expect(cards.first()).toContainText("Monstera"); + const lastButton = matchButtonIn(cards.first()); await lastButton.click(); - await expect(lastButton).toHaveClass(/add-match-button--matched/); + await expect(lastButton).toHaveAccessibleName(names.removeMatch); - await openSidebar(page); - await page.locator('a[href$="/myMatches"]').click(); - const matchCards = page.locator(".plant-card-match"); + await goToPage(page, names.myMatches); // 13 matches: the count, and 12 on the first page with the newest first - await expect(page.locator(".my-matches-count")).toContainText("13"); - await expect(matchCards).toHaveCount(12); - await expect(matchCards.first()).toContainText("Monstera"); + await expect(page.getByText(/(you have|du har) 13 matches/i)).toBeVisible(); + await expect(cards).toHaveCount(12); + await expect(cards.first()).toContainText("Monstera"); // The second page has the oldest match - await page.locator(".pagination").getByRole("button").last().click(); - await expect(matchCards).toHaveCount(1); - await expect(matchCards.first()).toContainText("Aloe Vera"); + await nextButton.click(); + await expect(cards).toHaveCount(1); + await expect(cards.first()).toContainText("Aloe Vera"); - // Sorting A–Z goes back to page 1 (option 3: newest, oldest, A–Z, Z–A) - await page.locator(".sort-button").click(); - await page.locator(".sort-option").nth(2).click(); - await expect(matchCards).toHaveCount(12); - await expect(matchCards.first()).toContainText("Aloe Vera"); + // Sorting A–Z goes back to page 1 + await page.getByRole("button", { name: names.sortButton }).click(); + await page.getByRole("button", { name: names.nameAZ }).click(); + await expect(cards).toHaveCount(12); + await expect(cards.first()).toContainText("Aloe Vera"); // The sort order is remembered when going to another page and back - await openSidebar(page); - await page.locator('a[href$="/explorePlants"]').click(); - await openSidebar(page); - await page.locator('a[href$="/myMatches"]').click(); - await expect(matchCards.first()).toContainText("Aloe Vera"); + await goToPage(page, names.explorePlants); + await goToPage(page, names.myMatches); + await expect(cards.first()).toContainText("Aloe Vera"); // ... and after a reload await page.reload(); - await expect(matchCards.first()).toContainText("Aloe Vera"); + await expect(cards.first()).toContainText("Aloe Vera"); }); test("PlantMatch continues from the same card after visiting another page and after a reload", async ({ page, }) => { await page.goto(""); - // Scoped to PlantMatch, so the cards on Explore Plants are not matched - const cardName = page.locator( - ".plant-match .plant-card-front .plant-card-name", - ); + const cardName = plantMatchCardName(page); await expect(cardName).toBeVisible(); // Skip the first plant, so the deck is on the second card const firstName = (await cardName.textContent())?.trim(); - await page.locator("button.dislike-button").click(); + await page.getByRole("button", { name: names.skipPlant }).click(); await expect(cardName).not.toHaveText(firstName ?? ""); const currentName = (await cardName.textContent())?.trim(); // Visit another page and come back - await openSidebar(page); - await page.locator('a[href$="/explorePlants"]').click(); - await expect(page.locator(".plant-grid > li").first()).toBeVisible(); - await openSidebar(page); - await page - .locator("#sidebar") - .getByRole("link", { name: /plant match|plante-matching/i }) - .click(); + await goToPage(page, names.explorePlants); + await expect(plantItems(page).first()).toBeVisible(); + await goToPage(page, names.plantMatch); await expect(cardName).toHaveText(currentName ?? ""); // sessionStorage is kept when the page is reloaded in the same tab @@ -159,32 +170,26 @@ test("a plant matched on ExplorePlants never shows up in PlantMatch", async ({ page, }) => { await page.goto("#/explorePlants"); - const firstItem = page.locator(".plant-grid > li").first(); + const firstItem = plantItems(page).first(); const matchedName = ( - await firstItem.locator(".plant-card-front .plant-card-name").textContent() + await firstItem.getByRole("heading", { level: 2 }).textContent() )?.trim(); - const addButton = firstItem.locator(".add-match-button"); + const addButton = matchButtonIn(firstItem); await addButton.click(); - await expect(addButton).toHaveClass(/add-match-button--matched/); + await expect(addButton).toHaveAccessibleName(names.removeMatch); - await openSidebar(page); - await page - .locator("#sidebar") - .getByRole("link", { name: /plant match|plante-matching/i }) - .click(); + await goToPage(page, names.plantMatch); // Skip through the whole deck and check every card on the way - const cardName = page.locator( - ".plant-match .plant-card-front .plant-card-name", - ); - const doneCard = page.locator(".empty-plant-card"); + const cardName = plantMatchCardName(page); + const doneCard = page.getByRole("heading", { level: 2, name: names.done }); const shown: string[] = []; while (!(await doneCard.isVisible())) { await expect(cardName.or(doneCard)).toBeVisible(); if (await doneCard.isVisible()) break; const name = (await cardName.textContent())?.trim() ?? ""; shown.push(name); - await page.locator("button.dislike-button").click(); + await page.getByRole("button", { name: names.skipPlant }).click(); await expect(cardName.or(doneCard)).not.toHaveText(name); } expect(shown.length).toBeGreaterThan(0); diff --git a/e2e/uiUserProfile.spec.ts b/e2e/uiUserProfile.spec.ts index e29b1a6f..e3ed127e 100644 --- a/e2e/uiUserProfile.spec.ts +++ b/e2e/uiUserProfile.spec.ts @@ -1,9 +1,12 @@ import { test, expect, type Response } from "@playwright/test"; -import { openSidebar } from "./helpers/navigation"; +import { goToPage } from "./helpers/navigation"; +import { names } from "./helpers/names"; // User journey: update name, description and avatar on the profile page, // check that the changes are stored, and navigate on to another page. // Each test gets a new browser and therefore a new user. +// Elements are found by role, label and accessible name in both languages +// (see helpers/names.ts), not by CSS classes or ids. // Matches a GraphQL response whose request contains the given text, // used to wait until a profile change has been saved @@ -15,13 +18,16 @@ test("user can update profile and avatar, and navigate between pages", async ({ page, }) => { const editProfileTab = page.getByRole("button", { - name: /edit profile|endre profil/i, + name: names.editProfile, }); - const nameField = page.locator("#profile-name"); - const descriptionField = page.locator("#profile-description"); + const nameField = page.getByLabel(names.nameField); + const descriptionField = page.getByLabel(names.descriptionField); + // Monstera is the first avatar, and has the same name in both languages. // New users have the profile picture "default", which is not in the list, - // so no avatar is selected from the start - const chosenAvatar = page.locator("button.avatar-option").first(); + // so no avatar is selected from the start. + const chosenAvatar = page.getByRole("button", { name: /^monstera$/i }); + // The name the user has chosen, shown as a heading at the top of the profile + const shownName = page.getByRole("heading", { level: 2, name: "John" }); await test.step("user edits name, description and avatar", async () => { await page.goto("#/profile"); @@ -42,9 +48,7 @@ test("user can update profile and avatar, and navigate between pages", async ({ await descriptionField.fill("Loves green plants"); await chosenAvatar.click(); - await expect(page.locator("main.profile .profile-text h2")).toContainText( - "John", - ); + await expect(shownName).toBeVisible(); await expect(chosenAvatar).toHaveAttribute("aria-pressed", "true"); // Saving is debounced: wait until the changes have reached the backend @@ -53,12 +57,8 @@ test("user can update profile and avatar, and navigate between pages", async ({ await test.step("the changes are stored after a reload", async () => { await page.reload(); - await expect(page.locator("main.profile .profile-text h2")).toContainText( - "John", - ); - await expect(page.locator("main.profile")).toContainText( - "Loves green plants", - ); + await expect(shownName).toBeVisible(); + await expect(page.getByRole("main")).toContainText("Loves green plants"); // The page opens on the "Preferences" tab after a reload, so open the edit tab again await editProfileTab.click(); @@ -66,8 +66,7 @@ test("user can update profile and avatar, and navigate between pages", async ({ }); await test.step("user navigates to ExplorePlants", async () => { - await openSidebar(page); - await page.locator('a[href$="/explorePlants"]').click(); - await expect(page.locator(".explore-page")).toBeVisible(); + await goToPage(page, names.explorePlants); + await expect(page.getByRole("searchbox")).toBeVisible(); }); }); diff --git a/frontend/src/components/plantCard/PlantCard.tsx b/frontend/src/components/plantCard/PlantCard.tsx index ca6312d8..b39feaba 100644 --- a/frontend/src/components/plantCard/PlantCard.tsx +++ b/frontend/src/components/plantCard/PlantCard.tsx @@ -86,7 +86,10 @@ export default function PlantCard({ alt={plantName} /> ) : ( -
+
)}
diff --git a/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx b/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx index 67d1852d..d6296e7a 100644 --- a/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx +++ b/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx @@ -153,7 +153,11 @@ export default function ExplorePlantsPage() { : t("explorePlantsPage.addMatch"); return ( -
  • +
  • {plants.map((plant) => ( -
    +
    {/* Every plant here is matched, so the button only removes */} setProfilePicture(avatar.id)} aria-pressed={profilePicture === avatar.id} + data-testid="avatar-option" > {avatar.name} diff --git a/frontend/src/tests/__snapshots__/ExplorePlantsPage.test.tsx.snap b/frontend/src/tests/__snapshots__/ExplorePlantsPage.test.tsx.snap index 67e4adc6..aefc25da 100644 --- a/frontend/src/tests/__snapshots__/ExplorePlantsPage.test.tsx.snap +++ b/frontend/src/tests/__snapshots__/ExplorePlantsPage.test.tsx.snap @@ -448,6 +448,7 @@ exports[`ExplorePlantsPage > snapshots > matches the snapshot of the page with r >
  • snapshots > matches the snapshot of the page with r
  • snapshots > matches the snapshot of the page with r
  • snapshots > matches the snapshot of the page with r
  • snapshots > matches the snapshot of the page with r
  • snapshots > matches the snapshot of the page with r
  • snapshots > matches the snapshot of the page with r
  • snapshots > matches the snapshot of the page with r
  • snapshots > matches the snapshot of the page with r
  • snapshots > matches the snapshot of the page with r
  • snapshots > matches the snapshot of the page with r
  • snapshots > matches the snapshot of the page with r
  • snapshots > matches the snapshot of the page with t >
  • snapshots > matches the snapshot of the page with t
  • snapshots > matches the snapshot of the page with t
  • Date: Sun, 22 Nov 2026 15:43:17 +0100 Subject: [PATCH 2/6] Replace page snapshots with targeted assertions and snapshot FilterSelect --- docs/tests.md | 9 +- frontend/src/tests/ExplorePlantsPage.test.tsx | 44 +- frontend/src/tests/FilterSelect.test.tsx | 45 + frontend/src/tests/ProfilePage.test.tsx | 12 +- .../ExplorePlantsPage.test.tsx.snap | 1245 ----------------- .../__snapshots__/FilterSelect.test.tsx.snap | 28 + .../__snapshots__/ProfilePage.test.tsx.snap | 151 -- 7 files changed, 92 insertions(+), 1442 deletions(-) delete mode 100644 frontend/src/tests/__snapshots__/ExplorePlantsPage.test.tsx.snap create mode 100644 frontend/src/tests/__snapshots__/FilterSelect.test.tsx.snap delete mode 100644 frontend/src/tests/__snapshots__/ProfilePage.test.tsx.snap diff --git a/docs/tests.md b/docs/tests.md index ec7faf6e..5f1eacd5 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -106,7 +106,7 @@ The coverage only counts the Vitest tests. Code that is only run by the end-to-e ### Component tests (frontend) -The tests are in `frontend/src/tests`. Snapshot tests are used for the explore page, the language switcher and the profile page. +The tests are in `frontend/src/tests`. Snapshot tests are only used for small components that seldom change: the language switcher and the filter dropdown (`FilterSelect`). A snapshot of a whole page failed on every small change to the page, even when nothing was wrong, so it was easy to update it without reading the diff, and it did not say what had broken. The pages are therefore checked with targeted assertions, where each test says what it checks. - `App.test.tsx` - Shows the right page for each route, and opens and closes the sidebar from the header. @@ -120,10 +120,9 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p - Pagination: moving between pages, disabled buttons at the ends, and going back to page 1 when a filter or the search text changes. - Matches: the button adds a plant that is not matched (✿), and removes a plant that is already matched (✖). - URL state: search, filters, sorting and page are restored from the URL, changes are written to the URL, and reset clears the Explore parameters. - - Accessibility: a search landmark, a heading and labelled controls. - - Snapshots of the page with results, with no results and with the sort menu open. + - Accessibility: a search landmark, a heading, labelled controls, a search field with an example in the placeholder, and the filters grouped under a name. - `FilterSelect.test.tsx` - - A labelled dropdown with "All" as the first option, showing the selected value and reporting a new choice, including going back to "All". + - A labelled dropdown with "All" as the first option, showing the selected value and reporting a new choice, including going back to "All". The number of plants for every value and for "All", values with no plants disabled except the chosen one, and a snapshot. - `SortMenu.test.tsx` - 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` @@ -152,7 +151,7 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p - `PlantPreferences.test.tsx` - Saved preferences are marked, also with `aria-pressed` for screen readers, preferences can be added and removed, the page does not crash when saving fails, and nothing is saved before the user exists. - `ProfilePage.test.tsx` - - The name, the image alt text and a screen reader prefix for the description, the preferences tab by default, the labelled fields and avatar chooser in the edit tab, saving name, description and avatar, the saved avatar, that a picture from the plant owner test is shown but not offered in the chooser, and a snapshot. + - 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. diff --git a/frontend/src/tests/ExplorePlantsPage.test.tsx b/frontend/src/tests/ExplorePlantsPage.test.tsx index d216738b..32d39146 100644 --- a/frontend/src/tests/ExplorePlantsPage.test.tsx +++ b/frontend/src/tests/ExplorePlantsPage.test.tsx @@ -563,8 +563,17 @@ describe("ExplorePlantsPage", () => { expect( screen.queryByRole("heading", { level: 1 }), ).not.toBeInTheDocument(); + // The label is short, and the placeholder gives an example of what to search for + const searchField = screen.getByRole("searchbox", { + name: "explorePlantsPage.search", + }); + expect(searchField).toHaveAttribute( + "placeholder", + "explorePlantsPage.searchPlaceholder", + ); + // The filters are grouped under a name, so screen readers hear what they are expect( - screen.getByRole("searchbox", { name: "explorePlantsPage.search" }), + screen.getByRole("group", { name: "explorePlantsPage.filters" }), ).toBeInTheDocument(); expect( screen.getByRole("navigation", { name: "pagination.label" }), @@ -580,37 +589,4 @@ describe("ExplorePlantsPage", () => { ).toBeInTheDocument(); }); }); - - // Snapshot tests: compare the rendered page with a saved snapshot, so - // unintended changes to the markup (labels, roles, structure) are caught. - // The snapshots are saved in src/tests/__snapshots__ and must be committed. - // If the markup is changed on purpose, update them with `npx vitest run -u`. - describe("snapshots", () => { - it("matches the snapshot of the page with results and page navigation", async () => { - const { container } = setup([mockResponse({}, makePlants(12), 30)]); - await screen.findAllByTestId("plant-card"); - - expect(container).toMatchSnapshot(); - }); - - it("matches the snapshot of the page with no results", async () => { - const { container } = setup([mockResponse({}, [])]); - await screen.findByText("explorePlantsPage.noResults"); - - expect(container).toMatchSnapshot(); - }); - - it("matches the snapshot of the page with the sort menu open", async () => { - const { container, user } = setup([mockResponse({})]); - await screen.findAllByTestId("plant-card"); - - await user.click( - screen.getByRole("button", { - name: "explorePlantsPage.sort: explorePlantsPage.name_asc", - }), - ); - - expect(container).toMatchSnapshot(); - }); - }); }); diff --git a/frontend/src/tests/FilterSelect.test.tsx b/frontend/src/tests/FilterSelect.test.tsx index def928a1..2b493f65 100644 --- a/frontend/src/tests/FilterSelect.test.tsx +++ b/frontend/src/tests/FilterSelect.test.tsx @@ -48,4 +48,49 @@ describe("FilterSelect", () => { await userEvent.selectOptions(select, ""); expect(onChange).toHaveBeenCalledWith(""); }); + + it("shows the number of plants and disables values with none, except the chosen one", () => { + render( + , + ); + + expect(screen.getByRole("option", { name: "All (3)" })).toBeEnabled(); + expect(screen.getByRole("option", { name: "Low (0)" })).toBeDisabled(); + expect(screen.getByRole("option", { name: "Medium (3)" })).toBeEnabled(); + // Chosen, so the user can still choose it away + expect(screen.getByRole("option", { name: "High (0)" })).toBeEnabled(); + }); + + // Snapshot test. Snapshots are only used for small components like this one, + // which change seldom, so a failing snapshot points to a real change in the + // markup. Whole pages are checked with targeted assertions instead, since a + // snapshot of a page fails on every small change and says little about what broke. + it("matches the snapshot with counts and a disabled value", () => { + const { container } = render( + , + ); + + expect(container).toMatchSnapshot(); + }); }); diff --git a/frontend/src/tests/ProfilePage.test.tsx b/frontend/src/tests/ProfilePage.test.tsx index f2442457..11c58e3f 100644 --- a/frontend/src/tests/ProfilePage.test.tsx +++ b/frontend/src/tests/ProfilePage.test.tsx @@ -71,9 +71,13 @@ describe("Profile page", () => { it("shows the preferences tab by default", () => { render(); + // The tabs say which one is open expect( screen.getByRole("button", { name: "profile.preferences" }), - ).toBeInTheDocument(); + ).toHaveAttribute("aria-pressed", "true"); + expect( + screen.getByRole("button", { name: "profile.editProfile" }), + ).toHaveAttribute("aria-pressed", "false"); expect( screen.getByRole("heading", { name: "preferences.title" }), @@ -296,10 +300,4 @@ describe("Profile page", () => { expect(choice).toHaveAttribute("aria-pressed", "false"), ); }); - - it("matches snapshot", () => { - const { container } = render(); - - expect(container).toMatchSnapshot(); - }); }); diff --git a/frontend/src/tests/__snapshots__/ExplorePlantsPage.test.tsx.snap b/frontend/src/tests/__snapshots__/ExplorePlantsPage.test.tsx.snap deleted file mode 100644 index aefc25da..00000000 --- a/frontend/src/tests/__snapshots__/ExplorePlantsPage.test.tsx.snap +++ /dev/null @@ -1,1245 +0,0 @@ -// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html - -exports[`ExplorePlantsPage > snapshots > matches the snapshot of the page with no results 1`] = ` -
    -
    - - -
    -

    - explorePlantsPage.noResults -

    -

    -

      -
    -
    -
    -`; - -exports[`ExplorePlantsPage > snapshots > matches the snapshot of the page with results and page navigation 1`] = ` -
    -
    - - -
    -

    - explorePlantsPage.resultsCount 30 -

    -
      -
    • -
      - Plant 1 -
      - - - - -
    • -
    • -
      - Plant 2 -
      - - - - -
    • -
    • -
      - Plant 3 -
      - - - - -
    • -
    • -
      - Plant 4 -
      - - - - -
    • -
    • -
      - Plant 5 -
      - - - - -
    • -
    • -
      - Plant 6 -
      - - - - -
    • -
    • -
      - Plant 7 -
      - - - - -
    • -
    • -
      - Plant 8 -
      - - - - -
    • -
    • -
      - Plant 9 -
      - - - - -
    • -
    • -
      - Plant 10 -
      - - - - -
    • -
    • -
      - Plant 11 -
      - - - - -
    • -
    • -
      - Plant 12 -
      - - - - -
    • -
    - -
    -
    -
    -`; - -exports[`ExplorePlantsPage > snapshots > matches the snapshot of the page with the sort menu open 1`] = ` -
    -
    - - -
    -

    - explorePlantsPage.resultsCount 3 -

    -
      -
    • -
      - Plant 1 -
      - - - - -
    • -
    • -
      - Plant 2 -
      - - - - -
    • -
    • -
      - Plant 3 -
      - - - - -
    • -
    - -
    -
    -
    -`; diff --git a/frontend/src/tests/__snapshots__/FilterSelect.test.tsx.snap b/frontend/src/tests/__snapshots__/FilterSelect.test.tsx.snap new file mode 100644 index 00000000..a4aaf9b2 --- /dev/null +++ b/frontend/src/tests/__snapshots__/FilterSelect.test.tsx.snap @@ -0,0 +1,28 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`FilterSelect > matches the snapshot with counts and a disabled value 1`] = ` +
    + +
    +`; diff --git a/frontend/src/tests/__snapshots__/ProfilePage.test.tsx.snap b/frontend/src/tests/__snapshots__/ProfilePage.test.tsx.snap deleted file mode 100644 index ba75b73e..00000000 --- a/frontend/src/tests/__snapshots__/ProfilePage.test.tsx.snap +++ /dev/null @@ -1,151 +0,0 @@ -// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html - -exports[`Profile page > matches snapshot 1`] = ` -
    -
    -
    - profile.imageAlt: profile.name -
    -

    - profile.name -

    -

    - - profile.descriptionLabel - : - - - profile.description -

    -
    -
    -
    - - -
    -
    -
    -

    - preferences.title -

    -
    - - -
    -
    -
    - - - - - - - - - -
    -
    -
    -
    -`; From a6ee722b465734f129ccbb0704abcfd0f512a915 Mon Sep 17 00:00:00 2001 From: Helene Lotsberg Date: Sun, 22 Nov 2026 15:57:37 +0100 Subject: [PATCH 3/6] match the My Matches link with new matches and update FilterSelect snapshot --- e2e/helpers/names.ts | 4 +++- .../src/tests/__snapshots__/FilterSelect.test.tsx.snap | 7 ++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/e2e/helpers/names.ts b/e2e/helpers/names.ts index 7d5732c2..db0fd042 100644 --- a/e2e/helpers/names.ts +++ b/e2e/helpers/names.ts @@ -7,7 +7,9 @@ export const names = { openSidebar: /^(open sidebar|åpne sidemeny)$/i, sidebarNavigation: /^(sidebar navigation|navigasjon i sidemenyen)$/i, plantMatch: /^(plant match|plante-matching)$/i, - myMatches: /^(my matches|mine matches)$/i, + // The link can also say how many new matches there are, + // e.g. "My Matches , 1 new match" (the hidden text is in its own element) + myMatches: /^(my matches|mine matches)\b/i, explorePlants: /^(explore plants|utforsk planter)$/i, // Plant Match diff --git a/frontend/src/tests/__snapshots__/FilterSelect.test.tsx.snap b/frontend/src/tests/__snapshots__/FilterSelect.test.tsx.snap index a4aaf9b2..2a6ed72e 100644 --- a/frontend/src/tests/__snapshots__/FilterSelect.test.tsx.snap +++ b/frontend/src/tests/__snapshots__/FilterSelect.test.tsx.snap @@ -10,17 +10,18 @@ exports[`FilterSelect > matches the snapshot with counts and a disabled value 1` From b8b5316d70ca7f6b041fbcc5073495ee8d57ba52 Mon Sep 17 00:00:00 2001 From: Helene Lotsberg Date: Sun, 22 Nov 2026 16:29:12 +0100 Subject: [PATCH 4/6] add E2E test for preferences deciding the order in Plant Match --- docs/tests.md | 21 +++--- e2e/helpers/locators.ts | 22 ++++++ e2e/helpers/names.ts | 11 +++ e2e/uiMatchAndRemovePlant.spec.ts | 17 +---- e2e/uiPreferences.spec.ts | 113 ++++++++++++++++++++++++++++++ 5 files changed, 160 insertions(+), 24 deletions(-) create mode 100644 e2e/helpers/locators.ts create mode 100644 e2e/uiPreferences.spec.ts diff --git a/docs/tests.md b/docs/tests.md index 1eca5dbc..0b4ca493 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -144,7 +144,7 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - `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, nothing is fetched before the user has loaded, and the end card with disabled buttons is shown when there are no plants at all. + - 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. - `PlantOwnerTestPage.test.tsx` - The result for all six combinations of answers, and that the time and light answers do not change it. - Going on is only possible with an answer, an earlier answer is shown when going back, the result is shown with its picture, the result can be saved as profile picture, an error is shown when saving fails, the page says so when the result already is the profile picture, and the test can be taken again with no answers. @@ -220,17 +220,18 @@ Other choices in the config: #### Scenarios -Each file covers one scenario, and API and UI tests for the same feature come in pairs. The **API tests** check the backend logic over HTTP, including atypical input that is hard to reach through the UI. The **UI tests** check that the frontend is correctly connected to the backend and that the user journeys work from start to finish. +Each file covers one scenario. Most features have both an API test and a UI test. The **API tests** check the backend logic over HTTP, including atypical input that is hard to reach through the UI. The **UI tests** check that the frontend is correctly connected to the backend and that the user journeys work from start to finish. Some UI tests have no API test of their own: accessibility and pictures are only about the frontend, and saving preferences is already covered by `apiUserProfile`, while the order of the plants is tested in the backend tests. The UI tests find elements the way a user or a screen reader would: by role, label and accessible name (`getByRole`, `getByLabel`), not by CSS classes or ids. A test then only breaks when something changes that the user notices, not when the styling is refactored, and an element without an accessible name cannot be found, so the tests also check that the controls are labelled. The app can run in Norwegian and English, so the names are written once in both languages in `e2e/helpers/names.ts`. Elements without a natural role, such as the plant cards in a list, the avatar pictures (decorative, `alt=""`) and the placeholder picture (a CSS background), have a `data-testid`. -| Feature | API test | UI test | -| ----------------------------------------- | ------------------------ | ----------------------- | -| Search, filter, sort, pagination, details | `apiExplorePlants` | `uiExplorePlants` | -| Profile and avatar | `apiUserProfile` | `uiUserProfile` | -| Matching, removing, sorting and paging | `apiMatchAndRemovePlant` | `uiMatchAndRemovePlant` | -| Accessibility on all pages | – | `uiAccessibility` | -| Pictures load | – | `uiImages` | +| Feature | API test | UI test | +| ------------------------------------------ | ------------------------ | ----------------------- | +| Search, filter, sort, pagination, details | `apiExplorePlants` | `uiExplorePlants` | +| Profile and avatar | `apiUserProfile` | `uiUserProfile` | +| Matching, removing, sorting and paging | `apiMatchAndRemovePlant` | `uiMatchAndRemovePlant` | +| Accessibility on all pages | – | `uiAccessibility` | +| Pictures load | – | `uiImages` | +| Preferences decide the order in PlantMatch | – | `uiPreferences` | **ExplorePlants (`uiExplorePlants`):** one continuous user journey that tests pagination, filtering, search, the detail view, sorting and reset, and that changing a filter on page 2 takes the user back to page 1. @@ -242,6 +243,8 @@ The UI tests find elements the way a user or a screen reader would: by role, lab The test user has no preferences, so PlantMatch shows the plants in random order. The test therefore remembers the name of the liked plant and checks that it is the same plant that ends up in MyMatches. +**Preferences (`uiPreferences`):** the core feature of the app, from start to finish. A new user lands on PlantMatch, the start page, where the order is random. The user then chooses three preferences on the profile page, and back on PlantMatch the deck starts over with a plant that matches all three, which the card also says to screen readers on each matching chip. The order and the marked chips are the same after a reload, so the preferences are stored in the database and the deck in `sessionStorage`. When the user changes the preferences, PlantMatch starts over with the plant that matches the new ones. The test data has only one or two plants that match each set of preferences, so the expected plants are known. The other UI tests use a new user without preferences, where PlantMatch is random. + **Profile (`uiUserProfile`):** changing name, description and avatar is shown at once and is still there after a reload, so the changes are stored in the database. 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. diff --git a/e2e/helpers/locators.ts b/e2e/helpers/locators.ts new file mode 100644 index 00000000..d355e364 --- /dev/null +++ b/e2e/helpers/locators.ts @@ -0,0 +1,22 @@ +import type { Page } from "@playwright/test"; +import { names } from "./names"; + +// Shared locators for elements that several UI tests need + +// The plant cards in the list on ExplorePlants or MyMatches. They have no role +// of their own, so they are found by data-testid. +export const plantItems = (page: Page) => page.getByTestId("plant-item"); + +// The plant card shown in PlantMatch. Only the side of the card that is shown +// is in the accessibility tree, so this is the side the user sees. Scoped to the +// page with the like button, since the previous page can still be on screen for +// a moment after navigating, and its cards are also articles. +export const plantMatchCard = (page: Page) => + page + .getByRole("main") + .filter({ has: page.getByRole("button", { name: names.likePlant }) }) + .getByRole("article"); + +// The name on the plant card in PlantMatch +export const plantMatchCardName = (page: Page) => + plantMatchCard(page).getByRole("heading", { level: 2 }); diff --git a/e2e/helpers/names.ts b/e2e/helpers/names.ts index db0fd042..8b4cb122 100644 --- a/e2e/helpers/names.ts +++ b/e2e/helpers/names.ts @@ -40,6 +40,17 @@ export const names = { noMatches: /no matches|ingen matcher/i, // Profile + profile: /^(profile|profil)$/i, + // Preferences, as they are named on the buttons on the profile page + averageWater: /^(average watering|middels vannbehov)$/i, + frequentWater: /^(frequent watering|trenger mye vann)$/i, + fullSun: /^(full sun|full sol)$/i, + filteredShade: /^(filtered shade|filtrert skygge)$/i, + mediumCare: /^(medium care|middels stell)$/i, + hardCare: /^(high care|krever mye stell)$/i, + // Hidden text on a chip on a plant card that matches a saved preference + matchesPreferences: + /matches your saved preferences|matcher dine lagrede preferanser/i, editProfile: /^(edit profile|endre profil)$/i, nameField: /write your name|skriv ditt navn/i, descriptionField: /write something about you|skriv noe om deg selv/i, diff --git a/e2e/uiMatchAndRemovePlant.spec.ts b/e2e/uiMatchAndRemovePlant.spec.ts index 83fd2b4d..85c1a994 100644 --- a/e2e/uiMatchAndRemovePlant.spec.ts +++ b/e2e/uiMatchAndRemovePlant.spec.ts @@ -1,6 +1,7 @@ -import { test, expect, type Locator, type Page } from "@playwright/test"; +import { test, expect, type Locator } from "@playwright/test"; import { goToPage } from "./helpers/navigation"; import { names } from "./helpers/names"; +import { plantItems, 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 @@ -10,20 +11,6 @@ import { names } from "./helpers/names"; // helpers/names.ts). The plant cards in the lists on ExplorePlants and // MyMatches have no role of their own, so they are found by data-testid. -// The cards in the list on ExplorePlants or MyMatches -const plantItems = (page: Page) => page.getByTestId("plant-item"); - -// The name on the plant card in PlantMatch. Only the side of the card that is -// shown is in the accessibility tree, so this is the name the user sees. -// Scoped to the page with the like button, since the previous page can still be -// on screen for a moment after navigating, and its cards also have names. -const plantMatchCardName = (page: Page) => - page - .getByRole("main") - .filter({ has: page.getByRole("button", { name: names.likePlant }) }) - .getByRole("article") - .getByRole("heading", { level: 2 }); - // The button on a plant card that adds it to MyMatches, or removes it const matchButtonIn = (item: Locator) => item.getByRole("button", { name: names.matchButton }); diff --git a/e2e/uiPreferences.spec.ts b/e2e/uiPreferences.spec.ts new file mode 100644 index 00000000..86b3ebd9 --- /dev/null +++ b/e2e/uiPreferences.spec.ts @@ -0,0 +1,113 @@ +import { test, expect, type Page, type Response } from "@playwright/test"; +import { goToPage } from "./helpers/navigation"; +import { names } from "./helpers/names"; +import { plantMatchCard, plantMatchCardName } from "./helpers/locators"; + +// User journey for the core feature of the app: the preferences the user +// chooses on the profile page decide which plants PlantMatch shows first. +// The other UI tests use a new user without preferences, so PlantMatch is random +// there. This test chooses preferences and checks the order against the 20 +// plants in e2e/fixtures/plants.json, where only a few plants match all three. + +// Average watering, full sun and medium care: only English Ivy and Rubber Tree +// match all three (in random order, since they match equally well) +const FIRST_PREFERENCES = [names.averageWater, names.fullSun, names.mediumCare]; +const FIRST_BEST_MATCHES = /^(English Ivy|Rubber Tree)$/; + +// Frequent watering, filtered shade and high care: only Maidenhair Fern +const SECOND_PREFERENCES = [ + names.frequentWater, + names.filteredShade, + names.hardCare, +]; +const SECOND_BEST_MATCH = "Maidenhair Fern"; + +// Matches the response to the request that saves exactly these preference ids, +// used to wait until the last click has been saved in the database +const preferencesSaved = (ids: string[]) => (response: Response) => { + const body = response.request().postData() ?? ""; + return ( + response.url().includes("/graphql") && + body.includes("updateUserPreferences") && + ids.every((id) => body.includes(`"${id}"`)) + ); +}; + +// Clicks the preference buttons on the profile page and waits until the +// result has been saved. Clicking a chosen preference removes it. +async function togglePreferences( + page: Page, + buttons: RegExp[], + savedIds: string[], +) { + const saved = page.waitForResponse(preferencesSaved(savedIds)); + for (const name of buttons) { + await page.getByRole("button", { name }).click(); + } + await saved; +} + +// Each chip on the card that matches a saved preference also says so in text +// for screen readers, so the number of such chips is how well the plant matches +const matchingChips = (page: Page) => + plantMatchCard(page).getByText(names.matchesPreferences); + +test("the preferences chosen on the profile decide which plants come first in PlantMatch, also after a reload", async ({ + page, +}) => { + const cardName = plantMatchCardName(page); + + await test.step("a new user lands on PlantMatch, where the order is random", async () => { + // PlantMatch is the start page, so every user has seen it before + // choosing preferences + await page.goto(""); + await expect(cardName).toBeVisible(); + await expect(matchingChips(page)).toHaveCount(0); + }); + + await test.step("the user chooses preferences on the profile", async () => { + await goToPage(page, names.profile); + await togglePreferences(page, FIRST_PREFERENCES, [ + "averageWater", + "fullSun", + "mediumCare", + ]); + for (const name of FIRST_PREFERENCES) { + await expect(page.getByRole("button", { name })).toHaveAttribute( + "aria-pressed", + "true", + ); + } + }); + + await test.step("back on PlantMatch, the deck starts over with a plant that matches all of them", async () => { + await goToPage(page, names.plantMatch); + await expect(cardName).toHaveText(FIRST_BEST_MATCHES); + await expect(matchingChips(page)).toHaveCount(3); + }); + + await test.step("the order and the preferences are kept after a reload", async () => { + const firstName = (await cardName.textContent())?.trim() ?? ""; + await page.reload(); + await expect(cardName).toHaveText(firstName); + // The chips are marked from the preferences saved in the database + await expect(matchingChips(page)).toHaveCount(3); + }); + + await test.step("new preferences give a new order", async () => { + await goToPage(page, names.profile); + // Remove the first preferences and choose new ones + await togglePreferences( + page, + [...FIRST_PREFERENCES, ...SECOND_PREFERENCES], + ["frequentWater", "filteredShade", "hardCare"], + ); + + await goToPage(page, names.plantMatch); + await expect(cardName).toHaveText(SECOND_BEST_MATCH); + await expect(matchingChips(page)).toHaveCount(3); + + await page.reload(); + await expect(cardName).toHaveText(SECOND_BEST_MATCH); + }); +}); From d2f1a513e0925b0ebd4121b6b90d05ac1a818563 Mon Sep 17 00:00:00 2001 From: Helene Lotsberg Date: Sun, 22 Nov 2026 16:29:55 +0100 Subject: [PATCH 5/6] restart the Plant Match deck when preferences changed on another page --- frontend/src/hooks/usePlantDeck.ts | 33 ++++++++++++++++------ frontend/src/tests/PlantMatchPage.test.tsx | 30 ++++++++++++++++++++ 2 files changed, 55 insertions(+), 8 deletions(-) diff --git a/frontend/src/hooks/usePlantDeck.ts b/frontend/src/hooks/usePlantDeck.ts index 53ee9a94..4b2dffa5 100644 --- a/frontend/src/hooks/usePlantDeck.ts +++ b/frontend/src/hooks/usePlantDeck.ts @@ -15,7 +15,16 @@ export const PREFETCH_THRESHOLD = 3; // the images are large base64 strings. export const DECK_STORAGE_KEY = "plantMatch.deck"; -type SavedDeck = { plants: Plant[]; seenIds: string[]; hasMore: boolean }; +// The preferences the deck was sorted by are saved too, so a deck that is out +// of date can be found when the user comes back (see the user effect below). +// Decks saved before this was added have none, and count as sorted without +// preferences. +type SavedDeck = { + plants: Plant[]; + seenIds: string[]; + hasMore: boolean; + preferences?: string[]; +}; function preferencesChanged(previous: string[], next: string[]) { return ( @@ -73,18 +82,20 @@ export function usePlantDeck() { const [reloadVersion, setReloadVersion] = useState(0); const [resetting, setResetting] = useState(false); + // Read when a batch is fetched. A change starts a new deck so its order + // reflects the user's current preferences. Starts as the preferences the + // saved deck was sorted by, so they are saved with it until the user is loaded. + const preferences = useRef(saved?.preferences ?? []); + // Save the cards that are left after every swipe and every new batch useEffect(() => { saveDeck({ plants: plants.slice(index), seenIds: [...seenIds.current], hasMore, + preferences: preferences.current, }); }, [plants, index, hasMore]); - - // Read when a batch is fetched. A change starts a new deck so its order - // reflects the user's current preferences. - const preferences = useRef([]); // The user's matches are never shown, so they are excluded from every batch const matchedIds = useRef([]); @@ -105,9 +116,15 @@ export function usePlantDeck() { if (userLoading) return; const nextPreferences = user?.preferences ?? []; - const shouldRestart = - preferencesInitialized.current && - preferencesChanged(preferences.current, nextPreferences); + // While the page is open: start over when the preferences change. + // When the page opens with a saved deck: start over if the preferences were + // changed on another page (the profile) after the deck was sorted. + // PlantMatch is the start page, so this happens the first time a new user + // chooses preferences, and without it the deck would keep the old order. + const shouldRestart = preferencesInitialized.current + ? preferencesChanged(preferences.current, nextPreferences) + : saved !== null && + preferencesChanged(saved.preferences ?? [], nextPreferences); preferences.current = nextPreferences; matchedIds.current = user?.matchedPlantIds ?? []; diff --git a/frontend/src/tests/PlantMatchPage.test.tsx b/frontend/src/tests/PlantMatchPage.test.tsx index 9a65292a..472132ac 100644 --- a/frontend/src/tests/PlantMatchPage.test.tsx +++ b/frontend/src/tests/PlantMatchPage.test.tsx @@ -364,6 +364,36 @@ describe("PlantMatchPage", () => { expect(await screen.findAllByText("Hydrangea")).not.toHaveLength(0); }); + it("starts over when the preferences were changed on another page since the deck was saved", async () => { + // A new user lands on PlantMatch without preferences, so the deck is saved unsorted + const { unmount } = render(); + await screen.findAllByText("Hydrangea"); + skip(); + unmount(); + + // The user chooses preferences on the profile page and comes back + mockUser(["averageWater"]); + query.mockClear(); + render(); + + // A new deck sorted by the new preferences, from the first plant + await waitFor(() => expect(query).toHaveBeenCalledTimes(1)); + expect(query.mock.calls[0][0].variables).toEqual({ + limit: PLANT_BATCH_SIZE, + excludeIds: [], + preferences: ["averageWater"], + }); + expect(await screen.findAllByText("Hydrangea")).not.toHaveLength(0); + }); + + it("saves the preferences the deck was sorted by", async () => { + mockUser(["fullSun"]); + render(); + await screen.findAllByText("Hydrangea"); + const saved = JSON.parse(sessionStorage.getItem(DECK_STORAGE_KEY) ?? ""); + expect(saved.preferences).toEqual(["fullSun"]); + }); + it("waits for the user before fetching the first batch", () => { useUser.mockReturnValue({ userId: "user-1", user: null, loading: true }); render(); From 67bad816e735d99dda5c830b936b174a18ca9ad8 Mon Sep 17 00:00:00 2001 From: Helene Lotsberg Date: Sun, 22 Nov 2026 16:34:38 +0100 Subject: [PATCH 6/6] fix missing hook dependency in usePlantDeck --- frontend/src/hooks/usePlantDeck.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frontend/src/hooks/usePlantDeck.ts b/frontend/src/hooks/usePlantDeck.ts index 4b2dffa5..a40ad79c 100644 --- a/frontend/src/hooks/usePlantDeck.ts +++ b/frontend/src/hooks/usePlantDeck.ts @@ -131,7 +131,8 @@ export function usePlantDeck() { preferencesInitialized.current = true; if (shouldRestart) restart(); - }, [restart, user, userLoading]); + // saved is only read once and never changes, so it does not rerun the effect + }, [restart, saved, user, userLoading]); const loadMore = useCallback(async () => { if (inFlight.current) return;