diff --git a/README.md b/README.md index a5057921..3fdd408c 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,6 @@ See [backend/README.md](backend/README.md) for more details about the backend se Both the frontend and the backend are tested with [Vitest](https://vitest.dev/). - - **Frontend:** Pages, components and hooks are tested with React Testing Library in a simulated browser (jsdom). Calls to the backend are mocked, so the backend does not need to be running. - **Backend:** The database connection and the GraphQL server are tested against a real MongoDB that runs in memory ([mongodb-memory-server](https://www.npmjs.com/package/mongodb-memory-server)). The tests never use the database on the VM, so they do not need the VPN or the SSH tunnel. MongoDB is downloaded once the first time the backend tests run. @@ -114,11 +113,12 @@ npm run test:frontend -- --coverage The coverage table is printed in the terminal. A detailed report is saved in `frontend/coverage/index.html` and `backend/coverage/index.html`, which you can open in a browser to see which lines are not tested. ### Test coverage + TODO! ### Continuous integration -GitHub Actions ([.github/workflows/ci.yml](.github/workflows/ci.yml)) runs on every pull request and on every push to `main`. It checks the formatting with Prettier, and runs lint, tests and build for both the backend and the frontend. +GitHub Actions ([.github/workflows/ci.yml](.github/workflows/ci.yml)) runs on every pull request and on every push to `main`. It checks the formatting with Prettier, and runs lint, tests for both the backend and the frontend. ## Quality and design diff --git a/backend/src/server.ts b/backend/src/server.ts index 331a810e..177cf9f4 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -91,7 +91,8 @@ interface UserMatchArgs extends UserIdArgs { const NAME_MAX_LENGTH = 40; const DESCRIPTION_MAX_LENGTH = 100; -// Must match the avatar ids in frontend/src/pages/profile/Profile.tsx +// Must match the avatar ids in frontend/src/pages/profile/Profile.tsx and the +// result ids in frontend/src/pages/plantOwnerTest/plantownertest.ts const PROFILE_PICTURES = [ "default", "monstera", @@ -101,6 +102,13 @@ const PROFILE_PICTURES = [ "succulent", "fern", "orchid", + // Results from the plant owner test + "cityMinimalist", + "averageCityGardener", + "cityGardenerDreaming", + "countryMinimalist", + "averageCountryGardener", + "gardenExpert", ]; // Must match the preference ids in frontend/src/pages/profile/Profile.tsx diff --git a/backend/tests/server.test.ts b/backend/tests/server.test.ts index 42286a7a..54a2f61d 100644 --- a/backend/tests/server.test.ts +++ b/backend/tests/server.test.ts @@ -360,6 +360,28 @@ describe("users", () => { expect(result.data?.updateUserProfile?.profilePicture).toBe("default"); }); + it.each([ + "cityMinimalist", + "averageCityGardener", + "cityGardenerDreaming", + "countryMinimalist", + "averageCountryGardener", + "gardenExpert", + ])( + "accepts the plant owner test result %s as profile picture", + async (picture) => { + const { id } = await createUser(); + + const result = await updateProfile({ + userId: id, + profilePicture: picture, + }); + + expect(result.errors).toBeUndefined(); + expect(result.data?.updateUserProfile?.profilePicture).toBe(picture); + }, + ); + it("updateUserPreferences saves preferences without duplicates", async () => { const { id } = await createUser(); diff --git a/docs/tests.md b/docs/tests.md index 2bee8e63..2511dcbe 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -3,10 +3,7 @@ The application is tested using **Vitest** and **React Testing Library**. We test pages, components and hooks, including rendering, user interactions and functionality. **Snapshot tests** are also used to ensure that the rendered UI remains consistent when changes are made. Both the frontend and backend code was tested as specified below. The test coverage was found to be --- (TODO fyll inn). - - - -**end-to-end tests** TODO: skriv her +**end-to-end tests** TODO: skriv her The tests cover the following areas: @@ -17,7 +14,8 @@ The tests cover the following areas: - Accessibility, such as the sidebar navigation landmark and accessible names. ## Test coverage -TODO! Sett inn bilde + +TODO! Sett inn bilde ## Overview of test files @@ -78,18 +76,11 @@ Backend: - `cd backend` - `npm run test -- --run --coverage` - The coverage report is shown in the terminal. A more detailed report is saved in `frontend/coverage/index.html` or `backend/coverage/index.html`, which can be opened in a browser to see which lines are not tested. ### To run tests with test coverage if not all tests are running - `npx vitest run --coverage --coverage.reportOnFailure=true` - - End-to-end testing: TODO! fyll inn - - - - diff --git a/frontend/src/AppRoutes.tsx b/frontend/src/AppRoutes.tsx index 3059f2b5..470cee92 100644 --- a/frontend/src/AppRoutes.tsx +++ b/frontend/src/AppRoutes.tsx @@ -7,6 +7,9 @@ const ExplorePlants = lazy( ); const MyMatchesPage = lazy(() => import("./pages/myMatches/MyMatchesPage.tsx")); const Profile = lazy(() => import("./pages/profile/Profile.tsx")); +const PlantOwnerTest = lazy( + () => import("./pages/plantOwnerTest/PlantOwnerTest.tsx"), +); // eslint-disable-next-line react-refresh/only-export-components export const ROUTES = { @@ -14,6 +17,7 @@ export const ROUTES = { explore: "/explorePlants", myMatches: "/my-matches", profile: "/profile", + plantOwnerTest: "/plantOwnerTest", } as const; function AppRoutes() { @@ -24,6 +28,7 @@ function AppRoutes() { } /> } /> } /> + } /> ); diff --git a/frontend/src/assets/profile.png b/frontend/src/assets/avatars/profile.png similarity index 100% rename from frontend/src/assets/profile.png rename to frontend/src/assets/avatars/profile.png diff --git a/frontend/src/assets/plantQuiz/average_city_gardener.png b/frontend/src/assets/plantQuiz/average_city_gardener.png new file mode 100644 index 00000000..2c414045 Binary files /dev/null and b/frontend/src/assets/plantQuiz/average_city_gardener.png differ diff --git a/frontend/src/assets/plantQuiz/average_country_gardener.png b/frontend/src/assets/plantQuiz/average_country_gardener.png new file mode 100644 index 00000000..67619dbb Binary files /dev/null and b/frontend/src/assets/plantQuiz/average_country_gardener.png differ diff --git a/frontend/src/assets/plantQuiz/city_dreamer.png b/frontend/src/assets/plantQuiz/city_dreamer.png new file mode 100644 index 00000000..37636bbe Binary files /dev/null and b/frontend/src/assets/plantQuiz/city_dreamer.png differ diff --git a/frontend/src/assets/plantQuiz/city_minimalist.png b/frontend/src/assets/plantQuiz/city_minimalist.png new file mode 100644 index 00000000..ee627d7b Binary files /dev/null and b/frontend/src/assets/plantQuiz/city_minimalist.png differ diff --git a/frontend/src/assets/plantQuiz/country_minimalist.png b/frontend/src/assets/plantQuiz/country_minimalist.png new file mode 100644 index 00000000..6389e7e0 Binary files /dev/null and b/frontend/src/assets/plantQuiz/country_minimalist.png differ diff --git a/frontend/src/assets/plantQuiz/garden_expert.png b/frontend/src/assets/plantQuiz/garden_expert.png new file mode 100644 index 00000000..25b6687c Binary files /dev/null and b/frontend/src/assets/plantQuiz/garden_expert.png differ diff --git a/frontend/src/components/sidebar/Sidebar.tsx b/frontend/src/components/sidebar/Sidebar.tsx index f2ff4f70..961a599e 100644 --- a/frontend/src/components/sidebar/Sidebar.tsx +++ b/frontend/src/components/sidebar/Sidebar.tsx @@ -72,6 +72,16 @@ export default function Sidebar({ isOpen, onCloseSidebar }: SidebarProps) { {t("sidebar.profile")} + +
  • + + {t("sidebar.plantOwnerTest")} + +
  • diff --git a/frontend/src/hooks/useProfile.ts b/frontend/src/hooks/useProfile.ts index 5f09fbc2..72e908c0 100644 --- a/frontend/src/hooks/useProfile.ts +++ b/frontend/src/hooks/useProfile.ts @@ -25,23 +25,28 @@ export function useProfile() { }); }, [userId, savedDraft, updateProfile]); - const setProfilePicture = (profilePicture: string) => { - if (!userId) return; - updateProfile({ - variables: { userId, profilePicture }, - // Shows the new picture right away instead of waiting for the server - optimisticResponse: { - updateUserProfile: { - __typename: "User", - id: userId, - name: user?.name ?? null, - description: user?.description ?? null, - profilePicture, + // Resolves to true when the picture was saved in the database + const setProfilePicture = async (profilePicture: string) => { + if (!userId) return false; + try { + await updateProfile({ + variables: { userId, profilePicture }, + // Shows the new picture right away instead of waiting for the server + optimisticResponse: { + updateUserProfile: { + __typename: "User", + id: userId, + name: user?.name ?? null, + description: user?.description ?? null, + profilePicture, + }, }, - }, - }).catch(() => { + }); + return true; + } catch { // Apollo rolls the picture back if the server fails - }); + return false; + } }; return { diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index f5666116..28a0377f 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -13,7 +13,8 @@ "myMatches": "My Matches", "explorePlants": "Explore Plants", "profile": "Profile", - "title": "I <3 Plants" + "title": "I <3 Plants", + "plantOwnerTest": "Plant Owner Test" }, "plantMatchPage": { "skipPlant": "Skip plant", @@ -30,15 +31,12 @@ }, "preferences": { "title": "Plant preferences ✿", - "minimumWater": "low watering", "averageWater": "average watering", "frequentWater": "frequent watering", - "fullSun": "full sun", "partShade": "part shade", "filteredShade": "filtered shade", - "easyCare": "easy care", "mediumCare": "medium care", "hardCare": "high care" @@ -111,5 +109,71 @@ "careLevel": "Care level", "unknown": "Unknown", "noImage": "No image available" + }, + "plantQuiz": { + "title": "What kind of plant owner are you?", + "subtitle": "Answer four questions and find out what kind of plant owner you are!", + "next": "Next", + "back": "Back", + "finish": "See my result", + "restart": "Retake test", + "resultTitle": "You are a:", + "questions": { + "time": { + "title": "How much time do you like to spend on caring for your plants?", + "tenMinutes": "10 minutes a week", + "thirtyMinutes": "30 minutes a week", + "oneHour": "1 hour a week", + "oneDay": "1 day a week" + }, + "light": { + "title": "How much light do your plants get?", + "partShade": "Partial shade", + "partSun": "Partial sun", + "fullSun": "Full sun" + }, + "location": { + "title": "Do you live in the city or in the countryside?", + "city": "City", + "country": "Countryside" + }, + "watering": { + "title": "How often do you like to water your plants?", + "minimum": "As little as possible", + "frequent": "Often", + "average": "Now and then" + } + }, + "results": { + "cityMinimalist": { + "name": "City minimalist", + "description": "You like a green home in the city without much work. Choose hardy plants that are happy with a little water now and then." + }, + "averageCityGardener": { + "name": "Average city gardener", + "description": "You enjoy looking after your plants in the city, as long as it fits into everyday life. Plants with average watering needs suit you well." + }, + "cityGardenerDreaming": { + "name": "City gardener dreaming", + "description": "You love caring for plants and dream of a big garden, even if you live in the city. Fill your home with plants that like a lot of water and attention." + }, + "countryMinimalist": { + "name": "Country minimalist", + "description": "You live in the countryside and like plants that look after themselves. Choose hardy plants that need little water." + }, + "averageCountryGardener": { + "name": "Average country gardener", + "description": "You have room for plants in the countryside and enjoy caring for them now and then. Plants with average watering needs suit you well." + }, + "gardenExpert": { + "name": "Garden expert", + "description": "You live in the countryside and know your garden inside out. You love watering and caring for plants that need a lot of attention." + } + }, + "profilePicture": { + "use": "Use as profile picture", + "saved": "This is now your profile picture!", + "failed": "Could not save the profile picture. Try again later." + } } } diff --git a/frontend/src/i18n/locales/no/translation.json b/frontend/src/i18n/locales/no/translation.json index b1389d44..ea5d77c1 100644 --- a/frontend/src/i18n/locales/no/translation.json +++ b/frontend/src/i18n/locales/no/translation.json @@ -13,7 +13,8 @@ "myMatches": "Mine Matches", "explorePlants": "Utforsk Planter", "profile": "Profil", - "title": "I <3 Plants" + "title": "I <3 Plants", + "plantOwnerTest": "Planteeier Test" }, "plantMatchPage": { "skipPlant": "Hopp over planten", @@ -30,15 +31,12 @@ }, "preferences": { "title": "Plantepreferanser ✿", - "minimumWater": "trenger lite vann", "averageWater": "middels vannbehov", "frequentWater": "trenger mye vann", - "fullSun": "full sol", "partShade": "delvis skygge", "filteredShade": "filtrert skygge", - "easyCare": "lettstelt", "mediumCare": "middels stell", "hardCare": "krever mye stell" @@ -111,5 +109,71 @@ "careLevel": "Stell", "unknown": "Ukjent", "noImage": "Bilde ikke tilgjengelig" + }, + "plantQuiz": { + "title": "Hvilken type planteeier er du?", + "subtitle": "Svar på fire spørsmål og finn ut hvilken type planteeier du er!", + "next": "Neste", + "back": "Tilbake", + "finish": "Se resultatet mitt", + "restart": "Ta testen på nytt", + "resultTitle": "Du er en:", + "questions": { + "time": { + "title": "Hvor mye tid liker du å bruke på å stelle plantene dine?", + "tenMinutes": "10 minutter i uken", + "thirtyMinutes": "30 minutter i uken", + "oneHour": "1 time i uken", + "oneDay": "1 dag i uken" + }, + "light": { + "title": "Hvor mye lys får plantene dine?", + "partShade": "Delvis skygge", + "partSun": "Delvis sol", + "fullSun": "Full sol" + }, + "location": { + "title": "Bor du i byen eller på landet?", + "city": "Byen", + "country": "Landet" + }, + "watering": { + "title": "Hvor ofte liker du å vanne plantene dine?", + "minimum": "Så lite som mulig", + "frequent": "Ofte", + "average": "Innimellom" + } + }, + "results": { + "cityMinimalist": { + "name": "Byminimalist", + "description": "Du liker et grønt hjem i byen uten for mye arbeid. Velg hardføre planter som klarer seg med litt vann innimellom." + }, + "averageCityGardener": { + "name": "Gjennomsnittlig bygartner", + "description": "Du liker å stelle plantene dine i byen, så lenge det passer inn i hverdagen. Planter med middels vannbehov passer deg godt." + }, + "cityGardenerDreaming": { + "name": "Drømmende bygartner", + "description": "Du elsker å stelle planter og drømmer om en stor hage, selv om du bor i byen. Fyll hjemmet med planter som liker mye vann og oppmerksomhet." + }, + "countryMinimalist": { + "name": "Landminimalist", + "description": "Du bor på landet og liker planter som klarer seg selv. Velg hardføre planter som trenger lite vann." + }, + "averageCountryGardener": { + "name": "Gjennomsnittlig landgartner", + "description": "Du har plass til planter på landet og liker å stelle dem innimellom. Planter med middels vannbehov passer deg godt." + }, + "gardenExpert": { + "name": "Hageekspert", + "description": "Du bor på landet og kjenner hagen din ut og inn. Du elsker å vanne og stelle planter som trenger mye oppmerksomhet." + } + }, + "profilePicture": { + "use": "Bruk som profilbilde", + "saved": "Dette er nå profilbildet ditt!", + "failed": "Kunne ikke lagre profilbildet. Prøv igjen senere." + } } } diff --git a/frontend/src/pages/plantOwnerTest/PlantOwnerTest.css b/frontend/src/pages/plantOwnerTest/PlantOwnerTest.css new file mode 100644 index 00000000..58371851 --- /dev/null +++ b/frontend/src/pages/plantOwnerTest/PlantOwnerTest.css @@ -0,0 +1,214 @@ +.plant-owner-test { + margin-left: var(--sidebar-width); + width: calc(100% - var(--sidebar-width)); + padding: 3rem clamp(1.5rem, 4vw, 4rem); + color: var(--text-dark); + font-size: 1.1rem; + box-sizing: border-box; +} + +.plant-owner-test *, +.plant-owner-test *::before, +.plant-owner-test *::after { + box-sizing: border-box; +} + +.plant-owner-test-header { + max-width: 750px; + margin: 0 auto 3rem; + text-align: center; +} + +.plant-owner-test-header h1 { + margin: 0 0 1rem; + font-size: 2.5rem; + line-height: 1.25; +} + +.plant-owner-test-header p { + margin: 0; + font-size: 1.15rem; + line-height: 1.7; +} + +.plant-owner-test-question { + max-width: 700px; + margin: 0 auto 1.75rem; + font-size: 1.75rem; + line-height: 1.4; +} + +.plant-owner-test-options { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 1.25rem; + max-width: 700px; + margin: 0 auto; +} + +.plant-owner-test-option { + display: flex; + align-items: center; + min-height: 145px; + padding: 1.75rem; + border: 2px solid var(--border-soft); + border-radius: 16px; + background: var(--light-green); + color: var(--text-dark); + font: inherit; + font-size: 1.15rem; + font-weight: 500; + line-height: 1.7; + text-align: left; + cursor: pointer; + transition: + border-color 0.2s ease, + background-color 0.2s ease, + transform 0.2s ease; +} + +.plant-owner-test-option:hover { + border-color: var(--dark-green); + background: var(--light-pink); + transform: translateY(-2px); +} + +.plant-owner-test-option.selected { + border: 3px solid var(--dark-pink); + background: var(--light-pink); +} + +.plant-owner-test-navigation { + display: flex; + justify-content: space-between; + gap: 1rem; + max-width: 700px; + margin: 2rem auto 0; +} + +/* Used for all buttons: back, next and retake test */ +.plant-owner-test-button { + min-height: 48px; + padding: 0.9rem 1.5rem; + border: 1px solid var(--dark-green); + border-radius: 999px; + background: var(--dark-green); + color: var(--text-on-green); + font: inherit; + font-size: 1.05rem; + font-weight: 600; + cursor: pointer; + transition: transform 0.2s ease; +} + +.plant-owner-test-button:hover:not(:disabled) { + transform: translateY(-1px); +} + +.plant-owner-test-button:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.plant-owner-test-option:focus-visible, +.plant-owner-test-button:focus-visible { + outline: 3px solid var(--dark-pink); + outline-offset: 3px; +} + +.plant-owner-test-result { + max-width: 600px; + margin: 0 auto; + padding: 2rem 1rem 3rem; + text-align: center; +} + +.plant-owner-test-result-image { + display: block; + width: min(75%, 280px); + aspect-ratio: 1; + margin: 0 auto 2rem; + border-radius: 50%; + object-fit: cover; +} + +/* Space between "use as profile picture" and "retake test" */ +.plant-owner-test-result .plant-owner-test-button { + margin: 0.5rem; +} + +.plant-owner-test-feedback { + margin: 0.5rem 0; + font-weight: 600; +} + +.plant-owner-test-eyebrow { + margin: 0 0 1rem; + color: var(--dark-pink); + font-size: 2rem; + font-weight: 600; +} + +.plant-owner-test-result h2 { + margin: 0 0 1.25rem; + font-size: 2.25rem; + line-height: 1.3; +} + +.plant-owner-test-description { + max-width: 480px; + margin: 0 auto 1.5rem; + font-size: 1.15rem; + line-height: 1.9; +} + +@media (max-width: 767px) { + .plant-owner-test { + margin-left: 0; + width: 100%; + padding: 2rem 1.25rem; + font-size: 1rem; + } + + .plant-owner-test-header { + margin-bottom: 2rem; + } + + .plant-owner-test-header h1 { + font-size: 2rem; + } + + .plant-owner-test-header p, + .plant-owner-test-description { + font-size: 1.05rem; + } + + .plant-owner-test-question { + font-size: 1.4rem; + } + + .plant-owner-test-options { + gap: 0.75rem; + } + + .plant-owner-test-option { + min-height: 100px; + padding: 1rem; + font-size: 1rem; + } + + .plant-owner-test-result { + padding: 1rem 0 2rem; + } + + .plant-owner-test-result h2 { + font-size: 1.9rem; + } +} + +@media (prefers-reduced-motion: reduce) { + .plant-owner-test-option, + .plant-owner-test-button { + transition: none; + } +} diff --git a/frontend/src/pages/plantOwnerTest/PlantOwnerTest.tsx b/frontend/src/pages/plantOwnerTest/PlantOwnerTest.tsx new file mode 100644 index 00000000..69289942 --- /dev/null +++ b/frontend/src/pages/plantOwnerTest/PlantOwnerTest.tsx @@ -0,0 +1,161 @@ +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { useProfile } from "../../hooks/useProfile.ts"; +import { + plantOwnerTest, + resultImages, + getPlantOwnerResult, + type PlantOwnerType, +} from "./plantownertest"; +import "./PlantOwnerTest.css"; + +export default function PlantOwnerTest() { + const { t } = useTranslation(); + const { profilePicture, setProfilePicture } = useProfile(); + + const [currentQuestion, setCurrentQuestion] = useState(0); + // Question id -> chosen option id. Only kept while the test is open, so the + // chosen answers are still shown when going back. Nothing is saved. + const [answers, setAnswers] = useState>({}); + const [result, setResult] = useState(null); + // Whether saving the result as profile picture failed + const [saveFailed, setSaveFailed] = useState(false); + + const question = plantOwnerTest[currentQuestion]; + const selectedAnswer = answers[question.id]; + const isLastQuestion = currentQuestion === plantOwnerTest.length - 1; + + function selectAnswer(option: string) { + setAnswers((previous) => ({ ...previous, [question.id]: option })); + } + + function nextQuestion() { + if (!selectedAnswer) return; + + if (isLastQuestion) { + setResult(getPlantOwnerResult(answers)); + } else { + setCurrentQuestion((previous) => previous + 1); + } + } + + function previousQuestion() { + if (currentQuestion > 0) { + setCurrentQuestion((previous) => previous - 1); + } + } + + function restartTest() { + setCurrentQuestion(0); + setAnswers({}); + setResult(null); + setSaveFailed(false); + } + + async function saveAsProfilePicture(type: PlantOwnerType) { + setSaveFailed(!(await setProfilePicture(type))); + } + + if (result) { + const isProfilePicture = profilePicture === result; + + return ( +
    +
    + {t(`plantQuiz.results.${result}.name`)} + +

    + {t("plantQuiz.resultTitle")} +

    + +

    {t(`plantQuiz.results.${result}.name`)}

    + +

    + {t(`plantQuiz.results.${result}.description`)} +

    + + {isProfilePicture ? ( +

    + {t("plantQuiz.profilePicture.saved")} +

    + ) : ( + + )} + + {saveFailed && ( +

    + {t("plantQuiz.profilePicture.failed")} +

    + )} + + +
    +
    + ); + } + + return ( +
    +
    +

    {t("plantQuiz.title")}

    +

    {t("plantQuiz.subtitle")}

    +
    + +

    + {t(`plantQuiz.questions.${question.id}.title`)} +

    + +
    + {question.options.map((option) => ( + + ))} +
    + +
    + + + +
    +
    + ); +} diff --git a/frontend/src/pages/plantOwnerTest/plantownertest.ts b/frontend/src/pages/plantOwnerTest/plantownertest.ts new file mode 100644 index 00000000..07a3e6eb --- /dev/null +++ b/frontend/src/pages/plantOwnerTest/plantownertest.ts @@ -0,0 +1,60 @@ +// the actual test for the plantowner test + +import cityMinimalist from "../../assets/plantQuiz/city_minimalist.png"; +import averageCityGardener from "../../assets/plantQuiz/average_city_gardener.png"; +import cityGardenerDreaming from "../../assets/plantQuiz/city_dreamer.png"; +import countryMinimalist from "../../assets/plantQuiz/country_minimalist.png"; +import averageCountryGardener from "../../assets/plantQuiz/average_country_gardener.png"; +import gardenExpert from "../../assets/plantQuiz/garden_expert.png"; + +export type PlantOwnerType = + | "cityMinimalist" + | "averageCityGardener" + | "cityGardenerDreaming" + | "countryMinimalist" + | "averageCountryGardener" + | "gardenExpert"; + +export interface QuizQuestion { + id: string; + options: string[]; +} + +export const plantOwnerTest: QuizQuestion[] = [ + { id: "time", options: ["tenMinutes", "thirtyMinutes", "oneHour", "oneDay"] }, + { id: "light", options: ["partShade", "partSun", "fullSun"] }, + { id: "location", options: ["city", "country"] }, + { id: "watering", options: ["minimum", "frequent", "average"] }, +]; + +// The result only depends on where you live and how often you like to water +const results: Record> = { + city: { + minimum: "cityMinimalist", + average: "averageCityGardener", + frequent: "cityGardenerDreaming", + }, + country: { + minimum: "countryMinimalist", + average: "averageCountryGardener", + frequent: "gardenExpert", + }, +}; + +// The picture for each result. The result id is also saved as the user's +// profilePicture when they choose to use it after the test. +export const resultImages: Record = { + cityMinimalist, + averageCityGardener, + cityGardenerDreaming, + countryMinimalist, + averageCountryGardener, + gardenExpert, +}; + +// answers maps a question id to the chosen option id +export function getPlantOwnerResult( + answers: Record, +): PlantOwnerType { + return results[answers.location][answers.watering]; +} diff --git a/frontend/src/pages/profile/Profile.tsx b/frontend/src/pages/profile/Profile.tsx index 72f2f56b..5fc47db1 100644 --- a/frontend/src/pages/profile/Profile.tsx +++ b/frontend/src/pages/profile/Profile.tsx @@ -1,5 +1,5 @@ import "./Profile.css"; -import profileImg from "../../assets/profile.png"; +import profileImg from "../../assets/avatars/profile.png"; import type { Preference } from "../../types/Preference.ts"; import { useTranslation } from "react-i18next"; import { useState } from "react"; @@ -12,6 +12,10 @@ import pothos from "../../assets/avatars/pothos.png"; import snakePlant from "../../assets/avatars/snake-plant.png"; import succulent from "../../assets/avatars/succulent.png"; import { useProfile } from "../../hooks/useProfile.ts"; +import { + resultImages, + type PlantOwnerType, +} from "../plantOwnerTest/plantownertest.ts"; export default function Profile() { const { t } = useTranslation(); @@ -37,8 +41,12 @@ export default function Profile() { { id: "orchid", name: t("profile.orchid"), src: orchid }, ]; + // Pictures from the plant owner test are not in the chooser above, + // so they can only be set by taking the test const currentAvatar = - avatars.find((avatar) => avatar.id === profilePicture)?.src ?? profileImg; + avatars.find((avatar) => avatar.id === profilePicture)?.src ?? + resultImages[profilePicture as PlantOwnerType] ?? + profileImg; const [activeTab, setActiveTab] = useState<"preferences" | "editProfile">( "preferences", diff --git a/frontend/src/tests/PlantOwnerTest.test.tsx b/frontend/src/tests/PlantOwnerTest.test.tsx new file mode 100644 index 00000000..c633919d --- /dev/null +++ b/frontend/src/tests/PlantOwnerTest.test.tsx @@ -0,0 +1,190 @@ +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { beforeEach, describe, it, expect, vi } from "vitest"; +// The extension is needed: without it, plantownertest.ts is found first on +// file systems that ignore upper and lower case (like macOS) +import PlantOwnerTest from "../pages/plantOwnerTest/PlantOwnerTest.tsx"; +import { getPlantOwnerResult } from "../pages/plantOwnerTest/plantownertest.ts"; + +const { updateProfile, useUser } = vi.hoisted(() => ({ + updateProfile: vi.fn(), + useUser: vi.fn(), +})); +vi.mock("@apollo/client/react", () => ({ + useMutation: () => [updateProfile], +})); +vi.mock("../context/UserContext", () => ({ useUser })); +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ t: (key: string) => key }), +})); + +function mockUser(profilePicture = "default") { + useUser.mockReturnValue({ + userId: "user-1", + user: { + id: "user-1", + name: null, + description: null, + profilePicture, + preferences: [], + matchedPlants: [], + }, + loading: false, + }); +} + +// Answers all four questions and opens the result +async function takeTest(location: string, watering: string) { + const user = userEvent.setup(); + const pick = (name: string) => + user.click(screen.getByRole("button", { name })); + + render(); + await pick("plantQuiz.questions.time.oneDay"); + await pick("plantQuiz.next"); + await pick("plantQuiz.questions.light.fullSun"); + await pick("plantQuiz.next"); + await pick(`plantQuiz.questions.location.${location}`); + await pick("plantQuiz.next"); + await pick(`plantQuiz.questions.watering.${watering}`); + await pick("plantQuiz.finish"); + return { user, pick }; +} + +const pressedOptions = () => + screen + .queryAllByRole("button", { pressed: true }) + .map((button) => button.textContent); + +describe("getPlantOwnerResult", () => { + it.each([ + ["city", "minimum", "cityMinimalist"], + ["city", "average", "averageCityGardener"], + ["city", "frequent", "cityGardenerDreaming"], + ["country", "minimum", "countryMinimalist"], + ["country", "average", "averageCountryGardener"], + ["country", "frequent", "gardenExpert"], + ])("gives %s + %s watering the result %s", (location, watering, result) => { + expect(getPlantOwnerResult({ location, watering })).toBe(result); + }); + + it("ignores the answers to the time and light questions", () => { + expect( + getPlantOwnerResult({ + time: "oneDay", + light: "fullSun", + location: "city", + watering: "minimum", + }), + ).toBe("cityMinimalist"); + }); +}); + +describe("PlantOwnerTest", () => { + beforeEach(() => { + updateProfile.mockReset(); + updateProfile.mockResolvedValue({}); + mockUser(); + }); + + it("only allows going on when an answer is chosen", async () => { + const user = userEvent.setup(); + render(); + + expect( + screen.getByRole("heading", { name: "plantQuiz.questions.time.title" }), + ).toBeInTheDocument(); + expect( + screen.getByRole("button", { name: "plantQuiz.back" }), + ).toBeDisabled(); + expect( + screen.getByRole("button", { name: "plantQuiz.next" }), + ).toBeDisabled(); + + await user.click( + screen.getByRole("button", { name: "plantQuiz.questions.time.oneHour" }), + ); + + expect(pressedOptions()).toEqual(["plantQuiz.questions.time.oneHour"]); + expect( + screen.getByRole("button", { name: "plantQuiz.next" }), + ).toBeEnabled(); + }); + + it("shows the earlier answer when going back", async () => { + const user = userEvent.setup(); + render(); + + await user.click( + screen.getByRole("button", { name: "plantQuiz.questions.time.oneDay" }), + ); + await user.click(screen.getByRole("button", { name: "plantQuiz.next" })); + expect(pressedOptions()).toEqual([]); + + await user.click(screen.getByRole("button", { name: "plantQuiz.back" })); + expect(pressedOptions()).toEqual(["plantQuiz.questions.time.oneDay"]); + }); + + it("shows the result with its picture", async () => { + await takeTest("country", "frequent"); + + expect( + screen.getByRole("heading", { + name: "plantQuiz.results.gardenExpert.name", + }), + ).toBeInTheDocument(); + expect( + screen.getByRole("img", { name: "plantQuiz.results.gardenExpert.name" }), + ).toHaveAttribute("src", expect.stringContaining("garden_expert")); + expect( + screen.getByText("plantQuiz.results.gardenExpert.description"), + ).toBeInTheDocument(); + }); + + it("saves the result as the profile picture", async () => { + const { pick } = await takeTest("city", "minimum"); + + await pick("plantQuiz.profilePicture.use"); + + expect(updateProfile).toHaveBeenCalledWith( + expect.objectContaining({ + variables: { userId: "user-1", profilePicture: "cityMinimalist" }, + }), + ); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + }); + + it("shows an error when the profile picture could not be saved", async () => { + updateProfile.mockRejectedValue(new Error("Offline")); + const { pick } = await takeTest("city", "minimum"); + + await pick("plantQuiz.profilePicture.use"); + + expect(await screen.findByRole("alert")).toHaveTextContent( + "plantQuiz.profilePicture.failed", + ); + }); + + it("says so when the result already is the profile picture", async () => { + mockUser("cityMinimalist"); + await takeTest("city", "minimum"); + + expect(screen.getByRole("status")).toHaveTextContent( + "plantQuiz.profilePicture.saved", + ); + expect( + screen.queryByRole("button", { name: "plantQuiz.profilePicture.use" }), + ).not.toBeInTheDocument(); + }); + + it("starts over with no answers when retaking the test", async () => { + const { pick } = await takeTest("city", "average"); + + await pick("plantQuiz.restart"); + + expect( + screen.getByRole("heading", { name: "plantQuiz.questions.time.title" }), + ).toBeInTheDocument(); + expect(pressedOptions()).toEqual([]); + }); +}); diff --git a/frontend/src/tests/Profile.test.tsx b/frontend/src/tests/Profile.test.tsx index 0f0b32d7..1a3bd63d 100644 --- a/frontend/src/tests/Profile.test.tsx +++ b/frontend/src/tests/Profile.test.tsx @@ -178,6 +178,27 @@ describe("Profile page", () => { ); }); + it("shows a picture from the plant owner test, but does not offer it in the chooser", async () => { + const user = userEvent.setup(); + mockUser("gardenExpert"); + + render(); + expect( + screen.getByRole("img", { name: "profile.imageAlt: profile.name" }), + ).toHaveAttribute("src", expect.stringContaining("garden_expert")); + + await user.click( + screen.getByRole("button", { name: "profile.editProfile" }), + ); + + // Only the seven plant avatars can be chosen, and none of them is selected + const choices = screen.getAllByRole("button", { name: /^Choose / }); + expect(choices).toHaveLength(7); + choices.forEach((choice) => + expect(choice).toHaveAttribute("aria-pressed", "false"), + ); + }); + it("matches snapshot", () => { const { container } = render(); diff --git a/frontend/src/tests/__snapshots__/Profile.test.tsx.snap b/frontend/src/tests/__snapshots__/Profile.test.tsx.snap index 60db6acf..82583b5b 100644 --- a/frontend/src/tests/__snapshots__/Profile.test.tsx.snap +++ b/frontend/src/tests/__snapshots__/Profile.test.tsx.snap @@ -11,7 +11,7 @@ exports[`Profile page > matches snapshot 1`] = ` profile.imageAlt: profile.name