Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,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
Expand Down
32 changes: 18 additions & 14 deletions docs/tests.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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`
Expand All @@ -145,14 +144,14 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p
- `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.
- `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.
Expand Down Expand Up @@ -221,15 +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.

| 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` |
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` |
| 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.

Expand All @@ -241,6 +243,8 @@ Each file covers one scenario, and API and UI tests for the same feature come in

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.
Expand Down
22 changes: 22 additions & 0 deletions e2e/helpers/locators.ts
Original file line number Diff line number Diff line change
@@ -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 });
59 changes: 59 additions & 0 deletions e2e/helpers/names.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// 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,
// 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
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
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,
// "Profile picture: <name>"
profilePicture: /^(profile picture|profilbilde):/i,
};
19 changes: 15 additions & 4 deletions e2e/helpers/navigation.ts
Original file line number Diff line number Diff line change
@@ -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();
}
Loading
Loading