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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
13 changes: 7 additions & 6 deletions backend/src/listen.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
// 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<Server> {
return new Promise((resolve, reject) => {
const server = createServer(app);
server.once("error", reject);
server.listen(port, () => resolve());
server.listen(port, () => resolve(server));
});
}
36 changes: 36 additions & 0 deletions backend/tests/listen.test.ts
Original file line number Diff line number Diff line change
@@ -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",
});
});
});
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Binary file modified docs/media/coverageBackend.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/media/coverageFrontend.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
23 changes: 19 additions & 4 deletions docs/tests.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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`
Expand All @@ -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.
Expand All @@ -168,21 +173,25 @@ 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`
- Switching between dark and light mode, restoring the saved mode on load, falling back to light mode for an invalid saved theme, and switching when browser storage is blocked.
- `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`
Expand All @@ -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

Expand Down Expand Up @@ -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.
Expand All @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion e2e/fixtures/plants.json
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading