From 212431ea3d0bdbfc03fc08e5a2e7b27ca936799d Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 16:45:13 +0100 Subject: [PATCH 001/102] test(frontend): configure testing infrastructure and coverage reporting --- frontend/.gitignore | 4 + frontend/package-lock.json | 1338 +++++++++++++++++++++++++++++++++++- frontend/package.json | 8 + frontend/vite.config.ts | 22 +- 4 files changed, 1359 insertions(+), 13 deletions(-) diff --git a/frontend/.gitignore b/frontend/.gitignore index f59fa7d..308ac0c 100644 --- a/frontend/.gitignore +++ b/frontend/.gitignore @@ -23,4 +23,8 @@ dist-ssr *.sln *.sw? +# Test and coverage reports +coverage/ +junit.xml + .env.production \ No newline at end of file diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 9d33006..505b247 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -26,6 +26,10 @@ "@babel/core": "^8.1.3", "@rolldown/plugin-babel": "^0.3.1", "@tailwindcss/vite": "^4.3.5", + "@testing-library/dom": "^10.4.2", + "@testing-library/jest-dom": "^8.0.0", + "@testing-library/react": "^16.3.3", + "@testing-library/user-event": "^14.6.13", "@types/babel__core": "^7.20.5", "@types/d3-chord": "^3.0.6", "@types/d3-shape": "^3.2.0", @@ -35,7 +39,10 @@ "@vitejs/devtools": "^0.8.3", "@vitejs/devtools-rolldown": "^0.8.0", "@vitejs/plugin-react": "^6.3.0", + "@vitest/coverage-v8": "^5.1.2", "babel-plugin-react-compiler": "^1.0.0", + "jsdom": "^31.0.1", + "msw": "^3.0.8", "oxlint": "^1.95.0", "oxlint-tsgolint": "^7.0.2009", "tailwindcss": "^4.3.3", @@ -48,6 +55,13 @@ "node": "^22.12.0 || ^24.0.0 || >=26.0.0" } }, + "node_modules/@adobe/css-tools": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.5.0.tgz", + "integrity": "sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==", + "dev": true, + "license": "MIT" + }, "node_modules/@babel/code-frame": { "version": "8.0.6", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-8.0.6.tgz", @@ -579,6 +593,16 @@ } } }, + "node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@devframes/agentic": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/@devframes/agentic/-/agentic-1.3.5.tgz", @@ -796,6 +820,24 @@ } } }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, "node_modules/@floating-ui/core": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", @@ -843,6 +885,94 @@ "url": "https://github.com/sponsors/ayuhito" } }, + "node_modules/@inquirer/ansi": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.1.1.tgz", + "integrity": "sha512-WwCc5T9554vU/M3W6mztOJvZK/5RgMwQsGlSZSZpKA/H2IfsTWIPdn1WiS8+HHjhe3H0IsmQCXUlDbvGM6vvuA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + } + }, + "node_modules/@inquirer/confirm": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-6.4.1.tgz", + "integrity": "sha512-ZLvGnS/+OtditM3RxULWDI3FVl3lR8mvh1ljZ8GCK8XKyfjI6Fq+ni6/2gbbH6n3gj6tinfNbE3QPplZ/xNVtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^12.1.1", + "@inquirer/type": "4.3.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/core": { + "version": "12.1.1", + "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-12.1.1.tgz", + "integrity": "sha512-JrVSjoB/+B4le+A/0GyZGv/oIK30KgGNUA0eVtEMNQLUmdpizfyXM0zglUZnwTtHLjpKGRlU/q6Iv5z2GYQw9w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.1.1", + "@inquirer/figures": "^2.1.1", + "@inquirer/type": "4.3.1", + "cli-width": "^4.1.0", + "fast-string-width": "^3.0.2", + "fast-wrap-ansi": "^0.2.0", + "mute-stream": "^3.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/figures": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-2.1.1.tgz", + "integrity": "sha512-63AOoKi9Wlsd1G+X5dKRg15GzN/WIEf0VghxHkcVn9JswideMlwq40qJMAO3II6JyhpDZPmi3CmVKjwOSYBAmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + } + }, + "node_modules/@inquirer/type": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.3.1.tgz", + "integrity": "sha512-WzfM7UPG5F8fhKPey5pTkAZQrGcGjOHbm6YLotuDdiuAkXEHiHSZh59yNeZs4RyrMHcZEZrl+GOcuLzzfLKJqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", @@ -952,6 +1082,41 @@ "node": ">=20" } }, + "node_modules/@msw/url": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@msw/url/-/url-0.1.3.tgz", + "integrity": "sha512-IvN0kCVRFtr12gBS3Nk8PRqjWjE/80ydze2DNQ0Z74ZjnMDWibVoaYFqGv9vR2LoiUfcVgEVaBWLFyp15M5YJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@mswjs/interceptors": { + "version": "0.45.14", + "resolved": "https://registry.npmjs.org/@mswjs/interceptors/-/interceptors-0.45.14.tgz", + "integrity": "sha512-2y8lEnhEKzgxSoALB7ibIPpUJ68YqWmvGjYO2D6Z4dAmMAr7kG9Poh6HiW1poT+okHGSr6LgsbqO8rDDH7MsSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@open-draft/until": "^3.0.1", + "@types/debug": "^4.1.13", + "debug": "^4.4.3", + "is-node-process": "^1.2.0", + "outvariant": "^1.4.3", + "rettime": "^0.11.12" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@open-draft/until": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@open-draft/until/-/until-3.0.1.tgz", + "integrity": "sha512-s7/9ELP4aP9YZtW7RJaa0Xf3RISaRH9+EFN18FtykJYRHGNrl8f9ymvoNXzjhrjmftFvkQudtuDU9RYhk0xs3A==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/kettanaito" + } + }, "node_modules/@oxc-project/types": { "version": "0.160.0", "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.160.0.tgz", @@ -2181,6 +2346,153 @@ "url": "https://github.com/sponsors/tannerlinsley" } }, + "node_modules/@testing-library/dom": { + "version": "10.4.2", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz", + "integrity": "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "5.3.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.5.0", + "picocolors": "1.1.1", + "pretty-format": "^27.0.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@testing-library/dom/node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@testing-library/dom/node_modules/@babel/runtime": { + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.16.tgz", + "integrity": "sha512-LKBjGopxrQE0aFucNL69OyyyF143MOWUULEOftU3oCgyD35Sy84UUpVnt/sNvTb7ZmCyALSt7om+fojlW35zYQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@testing-library/dom/node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@testing-library/jest-dom": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-8.0.0.tgz", + "integrity": "sha512-Nu45KEeFgP/ydCMipnisMblq6YHViqEFi3fKN0a40s+zdKDDD7vEPCEavS0i7i4RxmclcEIL8q2o42pu+WgNgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@adobe/css-tools": "^4.4.0", + "aria-query": "^5.0.0", + "css.escape": "^1.5.1", + "dom-accessibility-api": "^0.6.3", + "picocolors": "^1.1.1", + "redent": "^3.0.0" + }, + "engines": { + "node": ">=22", + "npm": ">=6", + "yarn": ">=1" + }, + "peerDependencies": { + "@testing-library/dom": ">=10 <11", + "vitest": ">=5 <6" + }, + "peerDependenciesMeta": { + "vitest": { + "optional": true + } + } + }, + "node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.6.3.tgz", + "integrity": "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@testing-library/react": { + "version": "16.3.3", + "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.3.tgz", + "integrity": "sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@testing-library/dom": "^10.0.0", + "@types/react": "^18.0.0 || ^19.0.0", + "@types/react-dom": "^18.0.0 || ^19.0.0", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@testing-library/react/node_modules/@babel/runtime": { + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.16.tgz", + "integrity": "sha512-LKBjGopxrQE0aFucNL69OyyyF143MOWUULEOftU3oCgyD35Sy84UUpVnt/sNvTb7ZmCyALSt7om+fojlW35zYQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@testing-library/user-event": { + "version": "14.6.13", + "resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.13.tgz", + "integrity": "sha512-2LVZGptuB5un1Cu/u31o9adkCwbsUTMp4B4p04xupI7uobvTIpgKidSdShqZiReo/mQmvR9xjgdgTgge4oAbYA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12", + "npm": ">=6" + }, + "peerDependencies": { + "@testing-library/dom": ">=7.21.4" + } + }, + "node_modules/@types/aria-query": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", + "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -2268,6 +2580,16 @@ "@types/d3-path": "*" } }, + "node_modules/@types/debug": { + "version": "4.1.13", + "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz", + "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/ms": "*" + } + }, "node_modules/@types/deep-eql": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", @@ -2296,6 +2618,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", + "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/node": { "version": "26.6.11", "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.11.tgz", @@ -2326,6 +2655,16 @@ "@types/react": "^19.3.0" } }, + "node_modules/@types/set-cookie-parser": { + "version": "2.4.10", + "resolved": "https://registry.npmjs.org/@types/set-cookie-parser/-/set-cookie-parser-2.4.10.tgz", + "integrity": "sha512-GGmQVGpQWUe5qglJozEjZV/5dyxbOOZ0LHe/lqyWssB88Y4svNfst0uqBVscdDeIKl5Jy5+aPSvy7mI9tYRguw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@typescript/typescript-aix-ppc64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", @@ -2786,6 +3125,58 @@ } } }, + "node_modules/@vitest/coverage-v8": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-5.1.2.tgz", + "integrity": "sha512-VG0JLv0T4kr1fR6QAfe8PTou+Frc4t0u4j+oKgDH3djJpFawzBfGyX14/z56NXoCTNem3OEphzCJhc4DkE62xQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "@vitest/istanbul-lib-coverage": "^2.1.1", + "@vitest/istanbul-lib-report": "^2.1.1", + "ast-v8-to-istanbul": "^1.0.8", + "magicast": "^0.5.5", + "obug": "^3.0.0", + "std-env": "^4.3.0", + "tinyrainbow": "^3.2.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "5.1.2", + "vitest": "5.1.2" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, + "node_modules/@vitest/istanbul-lib-coverage": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-coverage/-/istanbul-lib-coverage-2.1.1.tgz", + "integrity": "sha512-pF9nMHHuyQzyEXdkWX3d4wElEKjymfL5TEoofegJn/jK2WjmTLOcJKfJ7/YwYGYdbZf8Ebrt4VDUoBPiTuO9zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22" + } + }, + "node_modules/@vitest/istanbul-lib-report": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-report/-/istanbul-lib-report-2.1.1.tgz", + "integrity": "sha512-Qba+8OpQQAbWrmq3u1olh6jqE/vyW4OYJe6TLrrTBpXhjJhbY7Os69wyVvMQmNA64KJhGd5nQ/c7l4io8tPCHQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/istanbul-lib-coverage": "2.1.1" + }, + "engines": { + "node": ">=22" + } + }, "node_modules/@vitest/mocker": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.2.tgz", @@ -2837,6 +3228,39 @@ "node": ">=0.4.0" } }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/aria-query": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", + "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "dequal": "^2.0.3" + } + }, "node_modules/artichokie": { "version": "0.4.5", "resolved": "https://registry.npmjs.org/artichokie/-/artichokie-0.4.5.tgz", @@ -2861,6 +3285,18 @@ "node": ">=12" } }, + "node_modules/ast-v8-to-istanbul": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.8.tgz", + "integrity": "sha512-lPdpagk13ANXV+HClJEpCZM7kUsl5XcvgqKzZhaj6Ve1ZFICcY2sGhAN1n1vT0tML6EclT7bfVgTxqL57Gkpow==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^10.0.0" + } + }, "node_modules/babel-plugin-react-compiler": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/babel-plugin-react-compiler/-/babel-plugin-react-compiler-1.0.0.tgz", @@ -2884,18 +3320,45 @@ "node": ">=6.0.0" } }, - "node_modules/browserslist": { - "version": "4.29.5", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz", - "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==", + "node_modules/bcp-47": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/bcp-47/-/bcp-47-2.1.2.tgz", + "integrity": "sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg==", "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-alphanumerical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/bcp-47-match": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-2.0.3.tgz", + "integrity": "sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/browserslist": { + "version": "4.29.5", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz", + "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", "url": "https://tidelift.com/funding/github/npm/browserslist" }, { @@ -2971,6 +3434,49 @@ "url": "https://polar.sh/cva" } }, + "node_modules/cli-width": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz", + "integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 12" + } + }, + "node_modules/cliui": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz", + "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^7.2.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cliui/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/clsx": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", @@ -3006,6 +3512,20 @@ "dev": true, "license": "MIT" }, + "node_modules/cookie": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-2.0.2.tgz", + "integrity": "sha512-SL0cVuEdETEp7pN0FuZb01toc3vnODEfVUCooxG1SJN0yIirh7JMb9X9bvfCFf0vzzbT68RdbKDHYTiWy7a7iw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/cookie-es": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/cookie-es/-/cookie-es-3.1.1.tgz", @@ -3042,6 +3562,13 @@ } } }, + "node_modules/css.escape": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz", + "integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==", + "dev": true, + "license": "MIT" + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", @@ -3082,6 +3609,55 @@ "node": ">=12" } }, + "node_modules/data-urls": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz", + "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.1.2" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/destr": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz", @@ -3127,6 +3703,13 @@ } } }, + "node_modules/dom-accessibility-api": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", + "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", + "dev": true, + "license": "MIT" + }, "node_modules/echarts": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/echarts/-/echarts-6.1.0.tgz", @@ -3150,6 +3733,13 @@ "dev": true, "license": "ISC" }, + "node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "dev": true, + "license": "MIT" + }, "node_modules/empathic": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/empathic/-/empathic-2.1.0.tgz", @@ -3174,6 +3764,19 @@ "node": ">=10.13.0" } }, + "node_modules/entities": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/es-module-lexer": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", @@ -3241,6 +3844,33 @@ "dev": true, "license": "MIT" }, + "node_modules/fast-string-truncated-width": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz", + "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-string-width": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz", + "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-string-truncated-width": "^3.0.2" + } + }, + "node_modules/fast-wrap-ansi": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.2.tgz", + "integrity": "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-string-width": "^3.0.2" + } + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -3294,6 +3924,29 @@ "node": ">=6.9.0" } }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/graceful-fs": { "version": "4.2.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", @@ -3330,6 +3983,30 @@ } } }, + "node_modules/headers-polyfill": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/headers-polyfill/-/headers-polyfill-5.0.1.tgz", + "integrity": "sha512-1TJ6Fih/b8h5TIcv+1+Hw0PDQWJTKDKzFZzcKOiW1wJza3XoAQlkCuXLbymPYB8+ZQyw8mHvdw560e8zVFIWyA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/set-cookie-parser": "^2.4.10", + "set-cookie-parser": "^3.0.1" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", + "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.15.1" + }, + "engines": { + "node": "^22.13.0 || >=24.0.0" + } + }, "node_modules/import-meta-resolve": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.2.0.tgz", @@ -3341,6 +4018,67 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-alphabetical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz", + "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-alphanumerical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz", + "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-decimal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz", + "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-node-process": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/is-node-process/-/is-node-process-1.2.0.tgz", + "integrity": "sha512-Vg4o6/fqPxIjtxgUH5QLJhwZ7gW5diGCVlXpuUfELC62CuxM1iHcRe51f2W1FDy04Ai4KJkagKjx3XaqyfRKXw==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -3375,6 +4113,44 @@ "dev": true, "license": "MIT" }, + "node_modules/jsdom": { + "version": "31.0.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-31.0.1.tgz", + "integrity": "sha512-CbhJL8ZQg3eKswxSZth4QO9tW0jPIhmR0vtSXQSbKSfWbwIT6hoRc17wdHIVTQ43KI0mdV5iTJr3281IDgVZ5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "bcp-47": "^2.1.2", + "bcp-47-match": "^2.0.3", + "data-urls": "^8.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^7.0.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3", + "parse5": "^8.1.0", + "parse5-parser-stream": "^8.1.0", + "saxes": "^6.0.0", + "tough-cookie": "^6.0.2", + "undici": "^8.12.3", + "w3c-xmlserializer": "^6.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.3.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "@napi-rs/canvas": "^1.0.13" + }, + "peerDependenciesMeta": { + "@napi-rs/canvas": { + "optional": true + } + } + }, "node_modules/jsesc": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", @@ -3692,6 +4468,16 @@ "url": "https://github.com/sponsors/antfu" } }, + "node_modules/lru-cache": { + "version": "11.5.4", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.4.tgz", + "integrity": "sha512-B8nJCTi8JuSaDBg0tBdnImV6j5O2CXaqKfdj24ZTCFbyivN8KZ2Z+RL3aHjwJAfLutD9cNnObG4SIgW4gMufiw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/lucide-react": { "version": "1.82.0", "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.82.0.tgz", @@ -3707,6 +4493,16 @@ } } }, + "node_modules/lz-string": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", + "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", + "dev": true, + "license": "MIT", + "bin": { + "lz-string": "bin/bin.js" + } + }, "node_modules/magic-string": { "version": "1.4.5", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", @@ -3717,6 +4513,28 @@ "@jridgewell/sourcemap-codec": "^1.6.0" } }, + "node_modules/magicast": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz", + "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7", + "source-map-js": "^1.2.1" + } + }, + "node_modules/min-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", + "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, "node_modules/mlly": { "version": "1.8.2", "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz", @@ -3749,6 +4567,69 @@ "pathe": "^2.0.1" } }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/msw": { + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/msw/-/msw-3.0.8.tgz", + "integrity": "sha512-impdVoyKxfwDM1v9gr9wAsAPYbPgt+xv58pHduptDEA6pPERX8bNRqEyvv+7CWObpqVDUg2PWeitdvj7Xk22Fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/confirm": "^6.0.11", + "@msw/url": "^0.1.3", + "@mswjs/interceptors": "^0.45.11", + "cookie": "^2.0.1", + "headers-polyfill": "^5.0.1", + "is-node-process": "^1.2.0", + "outvariant": "^1.4.3", + "rettime": "^0.11.12", + "tough-cookie": "^6.0.2", + "type-fest": "^5.5.0", + "until-async": "^3.0.2", + "yargs": "^18.2.0" + }, + "bin": { + "msw": "cli/index.js" + }, + "engines": { + "node": ">=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/mswjs" + }, + "peerDependencies": { + "graphql": ">=16", + "typescript": ">=5.9.x", + "vite": ">=6" + }, + "peerDependenciesMeta": { + "graphql": { + "optional": true + }, + "typescript": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/mute-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-3.0.0.tgz", + "integrity": "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, "node_modules/nanoid": { "version": "3.3.20", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", @@ -3817,6 +4698,13 @@ "node": ">=12.20.0" } }, + "node_modules/outvariant": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/outvariant/-/outvariant-1.4.3.tgz", + "integrity": "sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA==", + "dev": true, + "license": "MIT" + }, "node_modules/oxlint": { "version": "1.95.0", "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.95.0.tgz", @@ -3891,6 +4779,32 @@ "dev": true, "license": "MIT" }, + "node_modules/parse5": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", + "integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^9.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-parser-stream": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-8.1.1.tgz", + "integrity": "sha512-hMcVbbUJcQmP8rURWUdYrT1flRiBiBVjq/RYGguJpDUgIXSqdYKlE0CxthmdMWoSlBAuL5bUBa73g0pttSy7Hw==", + "dev": true, + "license": "MIT", + "dependencies": { + "parse5": "^8.1.1" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", @@ -3979,6 +4893,31 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/quansync": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/quansync/-/quansync-1.0.0.tgz", @@ -4017,6 +4956,13 @@ "react": "^19.3.1" } }, + "node_modules/react-is": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "dev": true, + "license": "MIT" + }, "node_modules/react-router": { "version": "8.5.3", "resolved": "https://registry.npmjs.org/react-router/-/react-router-8.5.3.tgz", @@ -4047,12 +4993,33 @@ } } }, + "node_modules/redent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", + "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "indent-string": "^4.0.0", + "strip-indent": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/reselect": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.3.0.tgz", "integrity": "sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg==", "license": "MIT" }, + "node_modules/rettime": { + "version": "0.11.13", + "resolved": "https://registry.npmjs.org/rettime/-/rettime-0.11.13.tgz", + "integrity": "sha512-kzDWDmrxn6KPqqyFaBcXtV+GzaUzgYulSrWBetyxsPZjlXabWoeg3uZJU+zK/TnFUtkWC2Yw7J/VAWYnzy0tRA==", + "dev": true, + "license": "MIT" + }, "node_modules/rolldown": { "version": "1.3.4", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.4.tgz", @@ -4098,12 +5065,32 @@ "node": ">=20.19.0" } }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, "node_modules/scheduler": { "version": "0.28.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", "license": "MIT" }, + "node_modules/set-cookie-parser": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-3.2.3.tgz", + "integrity": "sha512-bDO7NdAkLprNt3BNl3LAh0oVnOS5+WspzxOxiboo7vRIyTqj2pvFmNWYEFynSGQgpJ+7yG/9nc/aSG20UDBUpg==", + "dev": true, + "license": "MIT" + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -4127,6 +5114,19 @@ "node": ">=8" } }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/source-map-js": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz", @@ -4157,6 +5157,78 @@ "dev": true, "license": "MIT" }, + "node_modules/string-width": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz", + "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi/node_modules/ansi-regex": { + "version": "6.6.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.6.0.tgz", + "integrity": "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/strip-indent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", + "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "min-indent": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tagged-tag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz", + "integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/tailwindcss": { "version": "4.3.5", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.5.tgz", @@ -4215,6 +5287,62 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tinyrainbow": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.2.0.tgz", + "integrity": "sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "7.6.4", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.6.4.tgz", + "integrity": "sha512-wp+ZdvQyov404xynNcjbXoJyeGM28W/aCwMmry/rJ+Y0SsObukJYkWwuxWGbNpIjeqMaEbNUtXPNtPPfI5cTFA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.6.4" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.6.4", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.6.4.tgz", + "integrity": "sha512-QywQ9lgQyZMuc3NVlqmuxHOhlwirSdvgD/vDLvX8dZYcYgy1cdri5rY/TXDHcF4J3VBSdJLcJNIJI6zGJ7jE+w==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.1.0.tgz", + "integrity": "sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz", + "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/tw-animate-css": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/tw-animate-css/-/tw-animate-css-1.4.0.tgz", @@ -4225,6 +5353,22 @@ "url": "https://github.com/sponsors/Wombosvideo" } }, + "node_modules/type-fest": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.10.0.tgz", + "integrity": "sha512-NoSdpq/WEiAg5sjmBkmV/hfxv6HJH4NqPNrqjtSO5CwRmpsDfaf4begxW34KdJykH/l1yHtwBWQkCRdoXO8mPA==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "dependencies": { + "tagged-tag": "^1.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/typescript": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", @@ -4267,6 +5411,16 @@ "dev": true, "license": "MIT" }, + "node_modules/undici": { + "version": "8.14.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.14.0.tgz", + "integrity": "sha512-MqM6wqORYo0jb1WFUwFKZTFWFz6VeBMPj9op5Hq+RvlrQjISQCyLEfx5+/iqOLWC/LL1HliJ5t0NP1BgYpXeVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, "node_modules/undici-types": { "version": "8.9.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", @@ -4274,6 +5428,16 @@ "dev": true, "license": "MIT" }, + "node_modules/until-async": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/until-async/-/until-async-3.0.3.tgz", + "integrity": "sha512-Ix78tBf1shsd8V8zc+msjiUk8Yf6upBuqR9iTgcWTyNFkTPy7hMonnsG/W6jhu53vrNTB0VZHxSNayRHrF+Auw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/kettanaito" + } + }, "node_modules/update-browserslist-db": { "version": "1.3.4", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", @@ -4489,6 +5653,54 @@ } } }, + "node_modules/w3c-xmlserializer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", + "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-url": { + "version": "17.3.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz", + "integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "tr46": "^7.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -4518,6 +5730,110 @@ "node": ">=20.11" } }, + "node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.2.0.tgz", + "integrity": "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^9.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "string-width": "^8.2.1", + "y18n": "^5.0.5", + "yargs-parser": "^22.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/yargs-parser": { + "version": "22.0.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz", + "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, "node_modules/zigpty": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/zigpty/-/zigpty-0.2.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index b74d729..5231587 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -16,6 +16,7 @@ "preview": "vite preview", "test": "vitest", "test:run": "vitest run", + "test:coverage": "vitest run --coverage", "check": "npm run lint:ci && npm run test:run && npm run build" }, "dependencies": { @@ -37,6 +38,10 @@ "@babel/core": "^8.1.3", "@rolldown/plugin-babel": "^0.3.1", "@tailwindcss/vite": "^4.3.5", + "@testing-library/dom": "^10.4.2", + "@testing-library/jest-dom": "^8.0.0", + "@testing-library/react": "^16.3.3", + "@testing-library/user-event": "^14.6.13", "@types/babel__core": "^7.20.5", "@types/d3-chord": "^3.0.6", "@types/d3-shape": "^3.2.0", @@ -46,7 +51,10 @@ "@vitejs/devtools": "^0.8.3", "@vitejs/devtools-rolldown": "^0.8.0", "@vitejs/plugin-react": "^6.3.0", + "@vitest/coverage-v8": "^5.1.2", "babel-plugin-react-compiler": "^1.0.0", + "jsdom": "^31.0.1", + "msw": "^3.0.8", "oxlint": "^1.95.0", "oxlint-tsgolint": "^7.0.2009", "tailwindcss": "^4.3.3", diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 65c34f3..ac528ea 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -1,9 +1,8 @@ import react, { reactCompilerPreset } from "@vitejs/plugin-react"; import babel from "@rolldown/plugin-babel"; -import { defineConfig } from "vite"; +import { defineConfig } from "vitest/config"; import tailwindcss from "@tailwindcss/vite"; -// https://vite.dev/config/ export default defineConfig({ plugins: [ react(), @@ -26,4 +25,23 @@ export default defineConfig({ apply: "serve", embeddedVisibility: "passive", }, + test: { + environment: "node", + globals: false, + include: ["src/**/*.{test,spec}.{ts,tsx}"], + env: { + VITE_API_URL: "http://pdataviewer.example.test/api", + }, + coverage: { + provider: "v8", + reportsDirectory: "./coverage", + include: ["src/**/*.{ts,tsx}"], + exclude: [ + "src/**/*.{test,spec}.{ts,tsx}", + "src/**/*.d.ts", + "src/test/**", + ], + reporter: ["text", "html", "lcov", "json-summary"], + }, + }, }); From f287886970f58326ea73d824c311a917c8efbdcf Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 16:49:06 +0100 Subject: [PATCH 002/102] test(frontend): configure shared Vitest setup and cleanup --- frontend/src/test/setup.test.tsx | 18 ++++++++++++++++++ frontend/src/test/setup.ts | 21 +++++++++++++++++++++ frontend/vite.config.ts | 6 ++++++ 3 files changed, 45 insertions(+) create mode 100644 frontend/src/test/setup.test.tsx create mode 100644 frontend/src/test/setup.ts diff --git a/frontend/src/test/setup.test.tsx b/frontend/src/test/setup.test.tsx new file mode 100644 index 0000000..77a6788 --- /dev/null +++ b/frontend/src/test/setup.test.tsx @@ -0,0 +1,18 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +describe("Testing infrastructure", () => { + it("supports React rendering and DOM assertions", () => { + render(); + + const button = screen.getByRole("button", { + name: "Test button", + }); + + expect(button).toBeInTheDocument(); + expect(button).toBeEnabled(); + expect(button).toBeVisible(); + }); +}); diff --git a/frontend/src/test/setup.ts b/frontend/src/test/setup.ts new file mode 100644 index 0000000..b687a59 --- /dev/null +++ b/frontend/src/test/setup.ts @@ -0,0 +1,21 @@ +import { afterEach, vi } from "vitest"; + +const cleanup = + typeof document !== "undefined" + ? (await import("@testing-library/react")).cleanup + : undefined; + +if (typeof document !== "undefined") { + await import("@testing-library/jest-dom/vitest"); +} + +afterEach(() => { + try { + cleanup?.(); + } finally { + vi.restoreAllMocks(); + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + } +}); diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index ac528ea..c1b8b4b 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -29,6 +29,12 @@ export default defineConfig({ environment: "node", globals: false, include: ["src/**/*.{test,spec}.{ts,tsx}"], + setupFiles: ["./src/test/setup.ts"], + environmentOptions: { + jsdom: { + url: "http://pdataviewer.example.test/", + }, + }, env: { VITE_API_URL: "http://pdataviewer.example.test/api", }, From 6ccd6206673f9583e14f1c92866d62b9c5032587 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 16:52:49 +0100 Subject: [PATCH 003/102] test(frontend): configure MSW network interception --- frontend/src/test/mocks/server.test.ts | 20 ++++++++++++++++++++ frontend/src/test/mocks/server.ts | 3 +++ frontend/src/test/setup.ts | 15 ++++++++++++++- 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 frontend/src/test/mocks/server.test.ts create mode 100644 frontend/src/test/mocks/server.ts diff --git a/frontend/src/test/mocks/server.test.ts b/frontend/src/test/mocks/server.test.ts new file mode 100644 index 0000000..9d5f40c --- /dev/null +++ b/frontend/src/test/mocks/server.test.ts @@ -0,0 +1,20 @@ +import { http, HttpResponse } from "msw"; +import { describe, expect, it } from "vitest"; + +import { api } from "@/lib/api/client"; + +import { server } from "./server"; + +describe("MSW server", () => { + it("intercepts API requests", async () => { + server.use( + http.get("http://pdataviewer.example.test/api/cohorts/", () => + HttpResponse.json(["Study A", "Study B"]), + ), + ); + + const cohorts = await api.get("/cohorts/"); + + expect(cohorts).toEqual(["Study A", "Study B"]); + }); +}); diff --git a/frontend/src/test/mocks/server.ts b/frontend/src/test/mocks/server.ts new file mode 100644 index 0000000..bd0bda5 --- /dev/null +++ b/frontend/src/test/mocks/server.ts @@ -0,0 +1,3 @@ +import { setupServer } from "msw/node"; + +export const server = setupServer(); diff --git a/frontend/src/test/setup.ts b/frontend/src/test/setup.ts index b687a59..96fa687 100644 --- a/frontend/src/test/setup.ts +++ b/frontend/src/test/setup.ts @@ -1,4 +1,6 @@ -import { afterEach, vi } from "vitest"; +import { afterAll, afterEach, beforeAll, vi } from "vitest"; + +import { server } from "./mocks/server"; const cleanup = typeof document !== "undefined" @@ -9,13 +11,24 @@ if (typeof document !== "undefined") { await import("@testing-library/jest-dom/vitest"); } +beforeAll(() => { + server.listen({ + onUnhandledFrame: "error", + }); +}); + afterEach(() => { try { cleanup?.(); } finally { + server.resetHandlers(); vi.restoreAllMocks(); vi.useRealTimers(); vi.unstubAllGlobals(); vi.unstubAllEnvs(); } }); + +afterAll(() => { + server.close(); +}); From 0715d5602049702b1c18aeff48770d00457f07ec Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 16:56:28 +0100 Subject: [PATCH 004/102] test(frontend): add shared mock API handlers and fixtures --- frontend/src/test/mocks/handlers.test.ts | 56 ++++ frontend/src/test/mocks/handlers.ts | 368 +++++++++++++++++++++++ frontend/src/test/mocks/server.ts | 4 +- 3 files changed, 427 insertions(+), 1 deletion(-) create mode 100644 frontend/src/test/mocks/handlers.test.ts create mode 100644 frontend/src/test/mocks/handlers.ts diff --git a/frontend/src/test/mocks/handlers.test.ts b/frontend/src/test/mocks/handlers.test.ts new file mode 100644 index 0000000..ae0bb38 --- /dev/null +++ b/frontend/src/test/mocks/handlers.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "vitest"; + +import { fetchBiomarkerMeasurements } from "@/features/biomarkers/api"; +import { fetchLongitudinalDataForCohort } from "@/features/longitudinal/api"; +import { fetchChordDiagram } from "@/features/mappings/api"; +import { fetchRaceDistribution } from "@/features/races/api"; +import { rankCohorts } from "@/features/study-picker/api"; +import { fetchMetadata } from "@/lib/api/cohorts"; + +import { + mockChordData, + mockMetadata, + mockRaceDistribution, + mockRankings, +} from "./handlers"; + +describe("Default MSW handlers", () => { + it("returns cohort metadata", async () => { + await expect(fetchMetadata()).resolves.toEqual(mockMetadata); + }); + + it("returns filtered biomarker measurements", async () => { + await expect( + fetchBiomarkerMeasurements({ + biomarker: "Age", + cohort: "Study A", + diagnosis: "PD", + }), + ).resolves.toEqual([65, 70, 75]); + }); + + it("returns cohort-specific longitudinal data", async () => { + const data = await fetchLongitudinalDataForCohort("Age", "Study B"); + + expect(data).toHaveLength(2); + expect(data.every((row) => row.cohort === "Study B")).toBe(true); + }); + + it("returns chord diagram data", async () => { + await expect(fetchChordDiagram("Demographics")).resolves.toEqual( + mockChordData, + ); + }); + + it("returns aggregated race distributions", async () => { + await expect( + fetchRaceDistribution(["Study A", "Study B"]), + ).resolves.toEqual(mockRaceDistribution); + }); + + it("returns cohort rankings", async () => { + await expect(rankCohorts(["Age", "Motor score"])).resolves.toEqual( + mockRankings, + ); + }); +}); diff --git a/frontend/src/test/mocks/handlers.ts b/frontend/src/test/mocks/handlers.ts new file mode 100644 index 0000000..935e146 --- /dev/null +++ b/frontend/src/test/mocks/handlers.ts @@ -0,0 +1,368 @@ +import { http, HttpResponse } from "msw"; + +import type { LongitudinalData } from "@/features/longitudinal/types"; +import type { ChordDiagramData } from "@/features/mappings/types"; +import type { RaceDistributionData } from "@/features/races/types"; +import type { RankedCohort } from "@/features/study-picker/types"; +import type { Metadata } from "@/lib/api/cohorts"; + +export const TEST_API_URL = "http://pdataviewer.example.test/api"; + +export const mockCohorts = ["Study A", "Study B"]; + +export const mockMetadata = { + "Study A": { + participants: 100, + controlParticipants: 30, + prodromalParticipants: 10, + pdParticipants: 60, + longitudinalParticipants: 80, + longitudinalDataAvailable: true, + followUpInterval: "12 months", + location: "Germany", + doi: "10.0000/study-a", + link: "https://example.test/study-a", + color: "#2563eb", + }, + "Study B": { + participants: 50, + controlParticipants: 20, + prodromalParticipants: 0, + pdParticipants: 30, + longitudinalParticipants: 40, + longitudinalDataAvailable: true, + followUpInterval: "6 months", + location: "United Kingdom", + doi: null, + link: null, + color: "#059669", + }, +} satisfies Metadata; + +export const mockVariables = ["Age", "Motor score"]; +export const mockModalities = ["Clinical", "Demographics"]; +export const mockBiomarkers = ["Age", "Motor score"]; + +const biomarkerGroups = [ + { + biomarker: "Age", + cohort: "Study A", + diagnosis: "HC", + values: [50, 55, 60], + }, + { + biomarker: "Age", + cohort: "Study A", + diagnosis: "PD", + values: [65, 70, 75], + }, + { + biomarker: "Age", + cohort: "Study B", + diagnosis: "PD", + values: [60, 65, 70], + }, + { + biomarker: "Motor score", + cohort: "Study A", + diagnosis: "PD", + values: [10, 20, 30], + }, +]; + +export const mockLongitudinalVariables = ["Age", "Study Visit"]; + +export const mockLongitudinalData = [ + { + months: 0, + cohort: "Study A", + patientCount: 80, + totalPatientCount: 100, + }, + { + months: 12, + cohort: "Study A", + patientCount: 60, + totalPatientCount: 100, + }, + { + months: 0, + cohort: "Study B", + patientCount: 40, + totalPatientCount: 50, + }, + { + months: 6, + cohort: "Study B", + patientCount: 30, + totalPatientCount: 50, + }, +] satisfies LongitudinalData[]; + +export const mockChordData = { + nodes: [ + { name: "Age", group: "Study A" }, + { name: "Enrollment age", group: "Study B" }, + ], + links: [ + { + source: "Age", + target: "Enrollment age", + }, + ], +} satisfies ChordDiagramData; + +export const mockRaceDistribution = [ + { + name: "White", + value: 95, + validCount: 135, + unknownCount: 8, + missingCount: 7, + }, + { + name: "Asian", + value: 30, + validCount: 135, + unknownCount: 8, + missingCount: 7, + }, +] satisfies RaceDistributionData[]; + +const studyARaceDistribution = [ + { + name: "White", + value: 60, + validCount: 90, + unknownCount: 5, + missingCount: 5, + }, + { + name: "Asian", + value: 20, + validCount: 90, + unknownCount: 5, + missingCount: 5, + }, +] satisfies RaceDistributionData[]; + +const studyBRaceDistribution = [ + { + name: "White", + value: 35, + validCount: 45, + unknownCount: 3, + missingCount: 2, + }, + { + name: "Asian", + value: 10, + validCount: 45, + unknownCount: 3, + missingCount: 2, + }, +] satisfies RaceDistributionData[]; + +export const mockRankings = [ + { + cohort: "Study A", + found: "2/2 (100.0%)", + missing: "", + }, + { + cohort: "Study B", + found: "1/2 (50.0%)", + missing: "Motor score", + }, +] satisfies RankedCohort[]; + +export const handlers = [ + // Cohorts + + http.get(`${TEST_API_URL}/cohorts/`, () => { + return HttpResponse.json(mockCohorts); + }), + + http.get(`${TEST_API_URL}/cohorts/metadata`, () => { + return HttpResponse.json(mockMetadata); + }), + + // Common data model + + http.get(`${TEST_API_URL}/cdm/variables`, () => { + return HttpResponse.json(mockVariables); + }), + + http.get(`${TEST_API_URL}/cdm/modalities`, () => { + return HttpResponse.json(mockModalities); + }), + + // Biomarkers + + http.get(`${TEST_API_URL}/biomarkers/`, () => { + return HttpResponse.json(mockBiomarkers); + }), + + http.get(`${TEST_API_URL}/biomarkers/cohorts`, ({ request }) => { + const biomarker = new URL(request.url).searchParams.get("biomarker"); + + const cohorts = [ + ...new Set( + biomarkerGroups + .filter((group) => group.biomarker === biomarker) + .map((group) => group.cohort), + ), + ]; + + return HttpResponse.json(cohorts); + }), + + http.get(`${TEST_API_URL}/biomarkers/diagnoses`, ({ request }) => { + const biomarker = new URL(request.url).searchParams.get("biomarker"); + + const options = mockCohorts.flatMap((cohort) => { + const groups = biomarkerGroups.filter( + (group) => group.biomarker === biomarker && group.cohort === cohort, + ); + + const labels = groups.map( + (group) => `${cohort} (${group.diagnosis} Group)`, + ); + + if (groups.length > 1) { + labels.push(`${cohort} (Complete)`); + } + + return labels; + }); + + return HttpResponse.json(options); + }), + + http.get( + `${TEST_API_URL}/biomarkers/cohorts/:cohort/diagnoses/:diagnosis`, + ({ request, params }) => { + const biomarker = new URL(request.url).searchParams.get("biomarker"); + + const values = biomarkerGroups + .filter( + (group) => + group.biomarker === biomarker && + group.cohort === params.cohort && + (params.diagnosis === "Complete" || + group.diagnosis === params.diagnosis), + ) + .flatMap((group) => group.values); + + return HttpResponse.json(values); + }, + ), + + // Longitudinal + + http.get(`${TEST_API_URL}/longitudinal/`, () => { + return HttpResponse.json(mockLongitudinalVariables); + }), + + http.get(`${TEST_API_URL}/longitudinal/:variable`, ({ params }) => { + const available = + typeof params.variable === "string" && + mockLongitudinalVariables.includes(params.variable); + + return HttpResponse.json(available ? mockLongitudinalData : []); + }), + + http.get(`${TEST_API_URL}/longitudinal/:variable/:cohort`, ({ params }) => { + const available = + typeof params.variable === "string" && + mockLongitudinalVariables.includes(params.variable); + + const data = available + ? mockLongitudinalData.filter((row) => row.cohort === params.cohort) + : []; + + return HttpResponse.json(data); + }), + + // Mappings + + http.get(`${TEST_API_URL}/visualization/chords/`, ({ request }) => { + const modality = new URL(request.url).searchParams.get("modality"); + + return HttpResponse.json( + modality === "Demographics" ? mockChordData : { nodes: [], links: [] }, + ); + }), + + // Race distribution + + http.get(`${TEST_API_URL}/races/cohorts`, () => { + return HttpResponse.json(mockCohorts); + }), + + http.get(`${TEST_API_URL}/races/distribution`, ({ request }) => { + const cohorts = new URL(request.url).searchParams.getAll("cohorts"); + + const includesStudyA = cohorts.includes("Study A"); + const includesStudyB = cohorts.includes("Study B"); + + if (cohorts.length === 0 || (includesStudyA && includesStudyB)) { + return HttpResponse.json(mockRaceDistribution); + } + + if (includesStudyA) { + return HttpResponse.json(studyARaceDistribution); + } + + if (includesStudyB) { + return HttpResponse.json(studyBRaceDistribution); + } + + return HttpResponse.json([]); + }), + + // Study Picker + + http.get(`${TEST_API_URL}/study-picker/variables`, () => { + return HttpResponse.json(mockVariables); + }), + + http.post(`${TEST_API_URL}/study-picker/rank`, async ({ request }) => { + const body: unknown = await request.json(); + + switch (JSON.stringify(body)) { + case '["Age","Motor score"]': + case '["Motor score","Age"]': + return HttpResponse.json(mockRankings); + + case '["Age"]': + return HttpResponse.json([ + { + cohort: "Study A", + found: "1/1 (100.0%)", + missing: "", + }, + { + cohort: "Study B", + found: "1/1 (100.0%)", + missing: "", + }, + ] satisfies RankedCohort[]); + + case '["Motor score"]': + return HttpResponse.json([ + { + cohort: "Study A", + found: "1/1 (100.0%)", + missing: "", + }, + ] satisfies RankedCohort[]); + + default: + return HttpResponse.json( + { detail: "Unsupported variable selection in test fixture." }, + { status: 422 }, + ); + } + }), +]; diff --git a/frontend/src/test/mocks/server.ts b/frontend/src/test/mocks/server.ts index bd0bda5..fa95245 100644 --- a/frontend/src/test/mocks/server.ts +++ b/frontend/src/test/mocks/server.ts @@ -1,3 +1,5 @@ import { setupServer } from "msw/node"; -export const server = setupServer(); +import { handlers } from "./handlers"; + +export const server = setupServer(...handlers); From dbf26577d21fde5eefa6d6d96d28afe23ed367cf Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 16:58:44 +0100 Subject: [PATCH 005/102] test(frontend): add isolated React rendering and query client utilities --- frontend/src/test/render.test.tsx | 79 +++++++++++++++++++++++++++++++ frontend/src/test/render.tsx | 78 ++++++++++++++++++++++++++++++ 2 files changed, 157 insertions(+) create mode 100644 frontend/src/test/render.test.tsx create mode 100644 frontend/src/test/render.tsx diff --git a/frontend/src/test/render.test.tsx b/frontend/src/test/render.test.tsx new file mode 100644 index 0000000..b962ba9 --- /dev/null +++ b/frontend/src/test/render.test.tsx @@ -0,0 +1,79 @@ +// @vitest-environment jsdom + +import { useQuery } from "@tanstack/react-query"; +import { renderHook, screen, waitFor } from "@testing-library/react"; +import { Link, useLocation } from "react-router"; +import { describe, expect, it } from "vitest"; + +import { fetchCohorts } from "@/lib/api/cohorts"; + +import { + createTestQueryClient, + createTestWrapper, + renderWithProviders, +} from "./render"; + +function NavigationProbe() { + const { pathname } = useLocation(); + + return ( + <> + {pathname} + Cohorts + + ); +} + +describe("Testing infrastructure", () => { + it("creates independent query clients", () => { + const first = createTestQueryClient(); + const second = createTestQueryClient(); + + first.setQueryData(["cohorts"], ["Study A"]); + + expect(first).not.toBe(second); + + expect(first.getQueryData(["cohorts"])).toEqual(["Study A"]); + + expect(second.getQueryData(["cohorts"])).toBeUndefined(); + + first.clear(); + second.clear(); + }); + + it("supports router navigation", async () => { + const { user } = renderWithProviders(, { + route: "/study-picker", + }); + + expect(screen.getByRole("status")).toHaveTextContent("/study-picker"); + + await user.click(screen.getByRole("link", { name: "Cohorts" })); + + expect(screen.getByRole("status")).toHaveTextContent("/cohorts"); + }); + + it("supports TanStack Query hooks and MSW", async () => { + const { wrapper, queryClient } = createTestWrapper(); + + const { result } = renderHook( + () => + useQuery({ + queryKey: ["cohorts"], + queryFn: ({ signal }) => fetchCohorts(signal), + }), + { wrapper }, + ); + + await waitFor(() => { + expect(result.current.isSuccess).toBe(true); + }); + + expect(result.current.data).toEqual(["Study A", "Study B"]); + + expect(queryClient.getQueryData(["cohorts"])).toEqual([ + "Study A", + "Study B", + ]); + }); +}); diff --git a/frontend/src/test/render.tsx b/frontend/src/test/render.tsx new file mode 100644 index 0000000..8ee5eee --- /dev/null +++ b/frontend/src/test/render.tsx @@ -0,0 +1,78 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { render, type RenderOptions } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import type { PropsWithChildren, ReactElement } from "react"; +import { MemoryRouter } from "react-router"; +import { onTestFinished } from "vitest"; + +interface TestProviderOptions { + route?: string | null; + queryClient?: QueryClient; +} + +type TestRenderOptions = Omit & TestProviderOptions; + +export function createTestQueryClient(): QueryClient { + return new QueryClient({ + defaultOptions: { + queries: { + retry: false, + staleTime: 60_000, + gcTime: Infinity, + refetchOnWindowFocus: false, + refetchOnReconnect: false, + }, + mutations: { + retry: false, + gcTime: Infinity, + }, + }, + }); +} + +export function createTestWrapper({ + route = "/", + queryClient = createTestQueryClient(), +}: TestProviderOptions = {}) { + onTestFinished(() => { + queryClient.clear(); + }); + + function TestProviders({ children }: PropsWithChildren) { + return ( + + {route === null ? ( + children + ) : ( + {children} + )} + + ); + } + + return { + queryClient, + wrapper: TestProviders, + }; +} + +export function renderWithProviders( + ui: ReactElement, + { route = "/", queryClient, ...renderOptions }: TestRenderOptions = {}, +) { + const { wrapper, queryClient: client } = createTestWrapper({ + route, + queryClient, + }); + + const user = userEvent.setup(); + + return { + ...render(ui, { + ...renderOptions, + wrapper, + }), + queryClient: client, + user, + }; +} From 7fd04a2a52da40efc685345348152074f98778af Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:00:12 +0100 Subject: [PATCH 006/102] test(frontend): add number formatting utility tests --- frontend/src/lib/formatters.test.ts | 65 +++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 frontend/src/lib/formatters.test.ts diff --git a/frontend/src/lib/formatters.test.ts b/frontend/src/lib/formatters.test.ts new file mode 100644 index 0000000..af6408b --- /dev/null +++ b/frontend/src/lib/formatters.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from "vitest"; + +import { formatMeasurement, formatNumber } from "./formatters"; + +const invalidValues = [ + { label: "null", value: null }, + { label: "undefined", value: undefined }, + { label: "NaN", value: NaN }, + { label: "positive infinity", value: Infinity }, + { label: "negative infinity", value: -Infinity }, +]; + +describe("formatNumber", () => { + it.each([ + { value: 0, expected: "0" }, + { value: 1234, expected: "1,234" }, + { value: -1234, expected: "-1,234" }, + { value: 1234567, expected: "1,234,567" }, + { value: 12.5, expected: "12.5" }, + { value: 1234.56789, expected: "1,234.568" }, + ])("formats $value as $expected", ({ value, expected }) => { + expect(formatNumber(value)).toBe(expected); + }); + + it.each(invalidValues)("returns the fallback for $label", ({ value }) => { + expect(formatNumber(value)).toBe("N/R"); + expect(formatNumber(value, "Unavailable")).toBe("Unavailable"); + }); + + it("does not use the fallback for finite values", () => { + expect(formatNumber(0, "Unavailable")).toBe("0"); + expect(formatNumber(42, "Unavailable")).toBe("42"); + }); + + it("supports an empty fallback", () => { + expect(formatNumber(null, "")).toBe(""); + }); +}); + +describe("formatMeasurement", () => { + it.each([ + { value: 0, expected: "0" }, + { value: 12.5, expected: "12.5" }, + { value: 1.234567, expected: "1.2346" }, + { value: 12345.678, expected: "12,346" }, + { value: -1234.567, expected: "-1,234.6" }, + { value: 0.000123456, expected: "0.00012346" }, + ])("formats $value as $expected", ({ value, expected }) => { + expect(formatMeasurement(value)).toBe(expected); + }); + + it.each(invalidValues)("returns the fallback for $label", ({ value }) => { + expect(formatMeasurement(value)).toBe("N/R"); + expect(formatMeasurement(value, "Unavailable")).toBe("Unavailable"); + }); + + it("does not use the fallback for finite values", () => { + expect(formatMeasurement(0, "Unavailable")).toBe("0"); + expect(formatMeasurement(42, "Unavailable")).toBe("42"); + }); + + it("supports an empty fallback", () => { + expect(formatMeasurement(undefined, "")).toBe(""); + }); +}); From edc56012e624cf7702ed54331ff79245e49533d2 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:01:39 +0100 Subject: [PATCH 007/102] test(frontend): add HTML escaping utility tests --- frontend/src/lib/html.test.ts | 65 +++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 frontend/src/lib/html.test.ts diff --git a/frontend/src/lib/html.test.ts b/frontend/src/lib/html.test.ts new file mode 100644 index 0000000..250f916 --- /dev/null +++ b/frontend/src/lib/html.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from "vitest"; + +import { escapeHtml } from "./html"; + +describe("escapeHtml", () => { + it.each([ + { value: "&", expected: "&" }, + { value: "<", expected: "<" }, + { value: ">", expected: ">" }, + { value: '"', expected: """ }, + { value: "'", expected: "'" }, + ])("escapes $value as $expected", ({ value, expected }) => { + expect(escapeHtml(value)).toBe(expected); + }); + + it.each([ + "", + "PPMI", + "Study A", + "UPDRS III - Total Score", + "123.45", + "Parkinson’s disease", + "München", + "İstanbul", + "研究", + ])("preserves plain text: %s", (value) => { + expect(escapeHtml(value)).toBe(value); + }); + + it("escapes multiple special characters", () => { + expect(escapeHtml(`A & B < C > D "E" 'F'`)).toBe( + "A & B < C > D "E" 'F'", + ); + }); + + it("escapes repeated special characters", () => { + expect(escapeHtml("&&<<>>")).toBe("&&<<>>"); + }); + + it("escapes HTML elements", () => { + expect(escapeHtml("Study A")).toBe( + "<strong>Study A</strong>", + ); + }); + + it("escapes script elements", () => { + expect(escapeHtml("")).toBe( + "<script>alert('test')</script>", + ); + }); + + it("escapes HTML containing event handlers", () => { + expect(escapeHtml('')).toBe( + "<img src="invalid" onerror="alert(1)">", + ); + }); + + it("escapes existing HTML entities", () => { + expect(escapeHtml("<script>")).toBe("&lt;script&gt;"); + }); + + it("preserves whitespace and line breaks", () => { + expect(escapeHtml(" Study A\nStudy B\t")).toBe(" Study A\nStudy B\t"); + }); +}); From f38977421aa334805e47d569c3db3fe2d48149c1 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:02:51 +0100 Subject: [PATCH 008/102] test(frontend): add external URL validation tests --- frontend/src/lib/url.test.ts | 113 +++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 frontend/src/lib/url.test.ts diff --git a/frontend/src/lib/url.test.ts b/frontend/src/lib/url.test.ts new file mode 100644 index 0000000..1484547 --- /dev/null +++ b/frontend/src/lib/url.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, it } from "vitest"; + +import { safeExternalUrl } from "./url"; + +describe("safeExternalUrl", () => { + it.each([ + { + value: "https://example.test", + expected: "https://example.test/", + }, + { + value: "http://example.test", + expected: "http://example.test/", + }, + { + value: "https://example.test/study", + expected: "https://example.test/study", + }, + { + value: "https://doi.org/10.0000/example", + expected: "https://doi.org/10.0000/example", + }, + { + value: "https://example.test/study?id=123#metadata", + expected: "https://example.test/study?id=123#metadata", + }, + { + value: "https://example.test:8443/study", + expected: "https://example.test:8443/study", + }, + ])("accepts valid HTTP(S) URL: $value", ({ value, expected }) => { + expect(safeExternalUrl(value)).toBe(expected); + }); + + it.each([ + { + value: "HTTPS://EXAMPLE.TEST", + expected: "https://example.test/", + }, + { + value: " https://example.test/study ", + expected: "https://example.test/study", + }, + { + value: "https://example.test/Study A", + expected: "https://example.test/Study%20A", + }, + { + value: "https://example.test:443/study", + expected: "https://example.test/study", + }, + { + value: "http://example.test:80/study", + expected: "http://example.test/study", + }, + { + value: "https://example.test/a/../study", + expected: "https://example.test/study", + }, + ])("normalizes $value", ({ value, expected }) => { + expect(safeExternalUrl(value)).toBe(expected); + }); + + it.each([null, "", " ", "\t\n"])( + "rejects missing or blank URLs: %s", + (value) => { + expect(safeExternalUrl(value)).toBeNull(); + }, + ); + + it.each([ + "example.test", + "not a URL", + "https://", + "http://", + "https://invalid host.test", + "https://example.test:invalid", + "https://example.test:99999", + "https://[invalid]", + ])("rejects malformed or incomplete URLs: %s", (value) => { + expect(safeExternalUrl(value)).toBeNull(); + }); + + it.each([ + "/cohorts", + "./study", + "../study", + "//example.test/study", + "#metadata", + "?id=123", + ])("rejects relative URLs: %s", (value) => { + expect(safeExternalUrl(value)).toBeNull(); + }); + + it.each([ + "javascript:alert(1)", + "JAVASCRIPT:alert(1)", + " javascript:alert(1)", + "java\tscript:alert(1)", + "data:text/html,", + "vbscript:msgbox(1)", + "file:///etc/passwd", + "ftp://example.test/study", + "mailto:test@example.test", + "tel:+49123456789", + "blob:https://example.test/resource", + "about:blank", + "ws://example.test", + "wss://example.test", + ])("rejects unsupported URL protocols: %s", (value) => { + expect(safeExternalUrl(value)).toBeNull(); + }); +}); From 532d9624e1f78bb49363a2720cb7b47825ce5575 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:05:57 +0100 Subject: [PATCH 009/102] test(frontend): add SVG chart download utility tests --- frontend/src/lib/charts/download-svg.test.ts | 156 +++++++++++++++++++ frontend/src/lib/charts/download-svg.ts | 2 +- 2 files changed, 157 insertions(+), 1 deletion(-) create mode 100644 frontend/src/lib/charts/download-svg.test.ts diff --git a/frontend/src/lib/charts/download-svg.test.ts b/frontend/src/lib/charts/download-svg.test.ts new file mode 100644 index 0000000..f597415 --- /dev/null +++ b/frontend/src/lib/charts/download-svg.test.ts @@ -0,0 +1,156 @@ +// @vitest-environment jsdom + +import { describe, expect, it, vi } from "vitest"; + +import { downloadChartSvg } from "./download-svg"; + +const SVG_DATA_URL = "data:image/svg+xml;charset=UTF-8,%3Csvg%3E%3C%2Fsvg%3E"; + +type ExportChart = NonNullable[0]>; + +function createMockChart(disposed = false) { + return { + isDisposed: vi.fn(() => disposed), + getDataURL: vi.fn(() => SVG_DATA_URL), + }; +} + +function captureDownloads() { + const downloads: { + anchor: HTMLAnchorElement; + attached: boolean; + }[] = []; + + const click = vi + .spyOn(HTMLAnchorElement.prototype, "click") + .mockImplementation(function (this: HTMLAnchorElement) { + downloads.push({ + anchor: this, + attached: document.body.contains(this), + }); + }); + + return { click, downloads }; +} + +describe("downloadChartSvg", () => { + it("exports the chart as an SVG with a white background", () => { + const chart = createMockChart(); + const { click, downloads } = captureDownloads(); + + downloadChartSvg(chart, "Biomarker distributions"); + + expect(chart.isDisposed).toHaveBeenCalledTimes(1); + + expect(chart.getDataURL).toHaveBeenCalledExactlyOnceWith({ + type: "svg", + backgroundColor: "#ffffff", + }); + + expect(click).toHaveBeenCalledTimes(1); + expect(downloads).toHaveLength(1); + + const { anchor, attached } = downloads[0]; + + expect(anchor).toHaveAttribute("href", SVG_DATA_URL); + + expect(anchor).toHaveAttribute("download", "biomarker-distributions.svg"); + + expect(attached).toBe(true); + expect(anchor).not.toBeInTheDocument(); + }); + + it.each([ + { + title: "Participant Retention", + filename: "participant-retention.svg", + }, + { + title: " UPDRS III / Total Score ", + filename: "updrs-iii-total-score.svg", + }, + { + title: "Age___at---baseline", + filename: "age-at-baseline.svg", + }, + { + title: "Age 12", + filename: "age-12.svg", + }, + { + title: "MÜNCHEN 研究 42", + filename: "münchen-研究-42.svg", + }, + { + title: "../../Study A\\Age", + filename: "study-a-age.svg", + }, + { + title: "", + filename: "chart.svg", + }, + { + title: " ", + filename: "chart.svg", + }, + { + title: "!@#$%^&*()", + filename: "chart.svg", + }, + { + title: "a".repeat(150), + filename: `${"a".repeat(100)}.svg`, + }, + { + title: `${"a".repeat(99)} - b`, + filename: `${"a".repeat(99)}.svg`, + }, + ])("normalizes the filename: $title", ({ title, filename }) => { + const chart = createMockChart(); + const { click, downloads } = captureDownloads(); + + downloadChartSvg(chart, title); + + expect(click).toHaveBeenCalledTimes(1); + expect(downloads).toHaveLength(1); + + const { anchor } = downloads[0]; + + expect(anchor).toHaveAttribute("download", filename); + expect(anchor).not.toBeInTheDocument(); + }); + + it("does not initiate a download when the chart is null", () => { + const { click, downloads } = captureDownloads(); + + downloadChartSvg(null, "Missing chart"); + + expect(click).not.toHaveBeenCalled(); + expect(downloads).toEqual([]); + }); + + it("does not export a disposed chart", () => { + const chart = createMockChart(true); + const { click, downloads } = captureDownloads(); + + downloadChartSvg(chart, "Disposed chart"); + + expect(chart.isDisposed).toHaveBeenCalledTimes(1); + expect(chart.getDataURL).not.toHaveBeenCalled(); + expect(click).not.toHaveBeenCalled(); + expect(downloads).toEqual([]); + }); + + it("propagates chart export errors without initiating a download", () => { + const chart = createMockChart(); + const { click } = captureDownloads(); + + chart.getDataURL.mockImplementation(() => { + throw new Error("SVG export failed"); + }); + + expect(() => downloadChartSvg(chart, "Age")).toThrow("SVG export failed"); + + expect(click).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/lib/charts/download-svg.ts b/frontend/src/lib/charts/download-svg.ts index 802ca0d..c782d8e 100644 --- a/frontend/src/lib/charts/download-svg.ts +++ b/frontend/src/lib/charts/download-svg.ts @@ -1,7 +1,7 @@ import type { EChartsType } from "echarts/core"; export function downloadChartSvg( - chart: EChartsType | null, + chart: Pick | null, title: string, ): void { if (!chart || chart.isDisposed()) return; From fc8e8a48a8d8f7b2c70d10709c4a5d870c69e2f3 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:08:00 +0100 Subject: [PATCH 010/102] test(frontend): add study picker ranking utility tests --- .../study-picker/utils/ranking.test.ts | 256 ++++++++++++++++++ 1 file changed, 256 insertions(+) create mode 100644 frontend/src/features/study-picker/utils/ranking.test.ts diff --git a/frontend/src/features/study-picker/utils/ranking.test.ts b/frontend/src/features/study-picker/utils/ranking.test.ts new file mode 100644 index 0000000..ecd7580 --- /dev/null +++ b/frontend/src/features/study-picker/utils/ranking.test.ts @@ -0,0 +1,256 @@ +import { describe, expect, it } from "vitest"; + +import { mockMetadata, mockRankings } from "@/test/mocks/handlers"; + +import { + getLongitudinalHref, + prepareRankingRows, + type RankingRow, +} from "./ranking"; + +const submittedVariables = ["Age", "Motor score"]; + +const sampleRow: RankingRow = { + cohort: "Study A", + found: "2/2 (100.0%)", + missing: "", + rank: 1, + color: "#2563eb", + accessLink: "https://example.test/study-a", + availableVariables: ["Age", "Motor score"], + longitudinalDataAvailable: true, +}; + +describe("prepareRankingRows", () => { + it("enriches ranking results with cohort metadata", () => { + const rows = prepareRankingRows( + mockRankings, + mockMetadata, + submittedVariables, + ); + + expect(rows).toEqual([ + sampleRow, + { + cohort: "Study B", + found: "1/2 (50.0%)", + missing: "Motor score", + rank: 2, + color: "#059669", + accessLink: null, + availableVariables: ["Age"], + longitudinalDataAvailable: true, + }, + ]); + }); + + it("preserves the ranking order returned by the backend", () => { + const rankings = mockRankings.toReversed(); + + const rows = prepareRankingRows(rankings, mockMetadata, submittedVariables); + + expect(rows.map(({ cohort, rank }) => ({ cohort, rank }))).toEqual([ + { cohort: "Study B", rank: 1 }, + { cohort: "Study A", rank: 2 }, + ]); + }); + + it("handles missing cohort metadata", () => { + const rows = prepareRankingRows( + [ + { + cohort: "Unknown study", + found: "1/1 (100.0%)", + missing: "", + }, + ], + mockMetadata, + ["Age"], + ); + + expect(rows).toEqual([ + { + cohort: "Unknown study", + found: "1/1 (100.0%)", + missing: "", + rank: 1, + color: null, + accessLink: null, + availableVariables: ["Age"], + longitudinalDataAvailable: null, + }, + ]); + }); + + it("preserves explicitly unavailable longitudinal data", () => { + const metadata = { + ...mockMetadata, + "Study A": { + ...mockMetadata["Study A"], + longitudinalDataAvailable: false, + }, + }; + + const rows = prepareRankingRows(mockRankings, metadata, submittedVariables); + + expect(rows[0]?.longitudinalDataAvailable).toBe(false); + expect(rows[1]?.longitudinalDataAvailable).toBe(true); + }); + + it.each([ + { + missing: "", + found: "3/3 (100.0%)", + expected: ["Age", "Motor score", "Sex"], + }, + { + missing: "Motor score", + found: "2/3 (66.67%)", + expected: ["Age", "Sex"], + }, + { + missing: "Age, Motor score, Sex", + found: "0/3 (0.0%)", + expected: [], + }, + { + missing: " Motor score , , Motor score, Age ", + found: "1/3 (33.33%)", + expected: ["Sex"], + }, + ])( + "determines available variables for missing values: $missing", + ({ missing, found, expected }) => { + const rows = prepareRankingRows( + [ + { + cohort: "Study A", + found, + missing, + }, + ], + mockMetadata, + ["Age", "Motor score", "Sex"], + ); + + expect(rows[0]?.availableVariables).toEqual(expected); + }, + ); + + it("returns no rows for empty ranking results", () => { + expect(prepareRankingRows([], mockMetadata, submittedVariables)).toEqual( + [], + ); + }); + + it("handles an empty submitted variable selection", () => { + const rows = prepareRankingRows(mockRankings, mockMetadata, []); + + expect(rows.map((row) => row.availableVariables)).toEqual([[], []]); + }); + + it("does not mutate the supplied ranking data or variables", () => { + const ranking = Object.freeze({ + cohort: "Study A", + found: "1/2 (50.0%)", + missing: "Motor score", + }); + + const rankings = Object.freeze([ranking]); + const variables = Object.freeze(["Age", "Motor score"]); + + const metadata = Object.freeze({ + "Study A": Object.freeze({ + ...mockMetadata["Study A"], + }), + }); + + const rows = prepareRankingRows(rankings, metadata, variables); + + expect(rows[0]).not.toBe(ranking); + + expect(rows[0]?.availableVariables).toEqual(["Age"]); + + expect(rankings).toEqual([ + { + cohort: "Study A", + found: "1/2 (50.0%)", + missing: "Motor score", + }, + ]); + + expect(variables).toEqual(["Age", "Motor score"]); + }); +}); + +describe("getLongitudinalHref", () => { + it("constructs a URL containing all available variables", () => { + expect(getLongitudinalHref(sampleRow)).toBe( + "/plot-longitudinal?cohort=Study+A&variables=Age&variables=Motor+score", + ); + }); + + it("supports a single available variable", () => { + const row: RankingRow = { + ...sampleRow, + availableVariables: ["Age"], + }; + + expect(getLongitudinalHref(row)).toBe( + "/plot-longitudinal?cohort=Study+A&variables=Age", + ); + }); + + it("correctly encodes special characters and Unicode", () => { + const row: RankingRow = { + ...sampleRow, + cohort: "Study A & B (München)", + availableVariables: [ + "UPDRS III / Total Score", + "Age + follow-up", + "α-synuclein (%)", + ], + }; + + const href = getLongitudinalHref(row); + + expect(href).not.toBeNull(); + + const url = new URL(href ?? "", "https://example.test"); + + expect(url.pathname).toBe("/plot-longitudinal"); + + expect(url.searchParams.get("cohort")).toBe("Study A & B (München)"); + + expect(url.searchParams.getAll("variables")).toEqual([ + "UPDRS III / Total Score", + "Age + follow-up", + "α-synuclein (%)", + ]); + }); + + it.each([ + { + longitudinalDataAvailable: false, + availableVariables: ["Age"], + }, + { + longitudinalDataAvailable: null, + availableVariables: ["Age"], + }, + { + longitudinalDataAvailable: true, + availableVariables: [], + }, + ])( + "returns no URL when longitudinal navigation is unavailable: %j", + (overrides) => { + const row: RankingRow = { + ...sampleRow, + ...overrides, + }; + + expect(getLongitudinalHref(row)).toBeNull(); + }, + ); +}); From 00fee05550f6840dd070b95b092863f460e42a5e Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:10:45 +0100 Subject: [PATCH 011/102] test(frontend): extend biomarker statistics coverage --- .../biomarkers/utils/statistics.test.ts | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/frontend/src/features/biomarkers/utils/statistics.test.ts b/frontend/src/features/biomarkers/utils/statistics.test.ts index 58a36f7..46d6410 100644 --- a/frontend/src/features/biomarkers/utils/statistics.test.ts +++ b/frontend/src/features/biomarkers/utils/statistics.test.ts @@ -108,6 +108,101 @@ describe("calculateBoxplotStatistics", () => { expect(observations).toEqual([5, 1, 4, 2, 3]); expect(stats?.values).toEqual([1, 2, 3, 4, 5]); }); + + it("handles exactly two observations", () => { + const stats = calculateBoxplotStatistics([2, 8]); + + expect(stats).toMatchObject({ + n: 2, + excludedCount: 0, + q1: 2, + median: 5, + q3: 8, + iqr: 6, + lowerWhisker: 2, + upperWhisker: 8, + mean: 5, + outliers: [], + values: [2, 8], + }); + + expect(stats?.standardDeviation).toBeCloseTo(Math.sqrt(18)); + }); + + it("handles negative values and zero", () => { + const stats = calculateBoxplotStatistics([-2, -1, 0, 1, 2]); + + expect(stats).toMatchObject({ + q1: -1.25, + median: 0, + q3: 1.25, + iqr: 2.5, + lowerWhisker: -2, + upperWhisker: 2, + mean: 0, + outliers: [], + }); + + expect(stats?.standardDeviation).toBeCloseTo(Math.sqrt(2.5)); + }); + + it("includes observations exactly on the outlier fences", () => { + const stats = calculateBoxplotStatistics([-3, 0, 0, 1, 1, 2, 2, 5]); + + expect(stats).toMatchObject({ + q1: 0, + median: 1, + q3: 2, + iqr: 2, + lowerWhisker: -3, + upperWhisker: 5, + outliers: [], + }); + }); + + it("includes outliers when calculating the mean and standard deviation", () => { + const stats = calculateBoxplotStatistics([0, 0, 0, 0, 0, 6]); + + expect(stats).toMatchObject({ + n: 6, + mean: 1, + lowerWhisker: 0, + upperWhisker: 0, + outliers: [6], + }); + + expect(stats?.standardDeviation).toBeCloseTo(Math.sqrt(6)); + }); + + it("maintains numerical precision for large offsets", () => { + const offset = 1e12; + + const observations = [1, 2, 3, 4, 5].map((value) => offset + value); + + const stats = calculateBoxplotStatistics(observations); + + expect(stats).toMatchObject({ + q1: offset + 1.75, + median: offset + 3, + q3: offset + 4.25, + iqr: 2.5, + mean: offset + 3, + outliers: [], + }); + + expect(stats?.standardDeviation).toBeCloseTo(Math.sqrt(2.5)); + }); + + it("returns null when numerical overflow leaves no valid inliers", () => { + const observations = [ + -Number.MAX_VALUE, + Number.MAX_VALUE, + Number.MAX_VALUE, + ]; + + expect(observations.every(Number.isFinite)).toBe(true); + expect(calculateBoxplotStatistics(observations)).toBeNull(); + }); }); describe("toBoxplotTuple", () => { From 6494f2a1efdff3fd2992343a981494d3b3dffafc Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:13:57 +0100 Subject: [PATCH 012/102] test(frontend): extend longitudinal retention utility coverage --- .../longitudinal/utils/retention.test.ts | 155 ++++++++++++++++++ 1 file changed, 155 insertions(+) diff --git a/frontend/src/features/longitudinal/utils/retention.test.ts b/frontend/src/features/longitudinal/utils/retention.test.ts index f81086a..417f86a 100644 --- a/frontend/src/features/longitudinal/utils/retention.test.ts +++ b/frontend/src/features/longitudinal/utils/retention.test.ts @@ -45,9 +45,30 @@ describe("getRetentionPercentage", () => { { patientCount: NaN, totalPatientCount: 100 }, { patientCount: Infinity, totalPatientCount: 100 }, { patientCount: 20.5, totalPatientCount: 100 }, + { patientCount: 50, totalPatientCount: NaN }, + { patientCount: 50, totalPatientCount: Infinity }, + { patientCount: 50, totalPatientCount: -Infinity }, + { patientCount: 50, totalPatientCount: 100.5 }, + { + patientCount: 50, + totalPatientCount: Number.MAX_SAFE_INTEGER + 1, + }, + { + patientCount: Number.MAX_SAFE_INTEGER + 1, + totalPatientCount: Number.MAX_SAFE_INTEGER + 1, + }, ])("rejects invalid counts: %j", (counts) => { expect(getRetentionPercentage(counts)).toBeNull(); }); + + it("accepts counts at the safe integer boundary", () => { + expect( + getRetentionPercentage({ + patientCount: Number.MAX_SAFE_INTEGER, + totalPatientCount: Number.MAX_SAFE_INTEGER, + }), + ).toBe(100); + }); }); describe("toRetentionPoints", () => { @@ -94,6 +115,47 @@ describe("toRetentionPoints", () => { it("handles empty input", () => { expect(toRetentionPoints([])).toEqual([]); }); + + it("preserves participant counts and fractional visit times", () => { + const points = toRetentionPoints([ + sample({ + months: 1.5, + patientCount: 75, + totalPatientCount: 100, + }), + sample({ + months: 0, + patientCount: 200, + totalPatientCount: 200, + }), + sample({ + months: 3.5, + patientCount: 120, + totalPatientCount: 100, + }), + ]); + + expect(points).toEqual([ + { + months: 0, + patientCount: 200, + totalPatientCount: 200, + retentionPercent: 100, + }, + { + months: 1.5, + patientCount: 75, + totalPatientCount: 100, + retentionPercent: 75, + }, + { + months: 3.5, + patientCount: 120, + totalPatientCount: 100, + retentionPercent: null, + }, + ]); + }); }); describe("createRetentionSeries", () => { @@ -106,6 +168,13 @@ describe("createRetentionSeries", () => { expect(series.name).toBe("Age"); expect(series.points.map((point) => point.months)).toEqual([0, 6]); }); + + it("creates an empty named series when no measurements exist", () => { + expect(createRetentionSeries("Age", [])).toEqual({ + name: "Age", + points: [], + }); + }); }); describe("groupRetentionByCohort", () => { @@ -130,4 +199,90 @@ describe("groupRetentionByCohort", () => { it("returns no series for empty data", () => { expect(groupRetentionByCohort([])).toEqual([]); }); + + it("excludes nonfinite visit times while preserving invalid counts", () => { + const data = [ + sample({ + cohort: "PPMI", + months: 12, + patientCount: 60, + }), + sample({ + cohort: "PPMI", + months: NaN, + }), + sample({ + cohort: "PPMI", + months: 0, + patientCount: 100, + }), + sample({ + cohort: "PPMI", + months: 6, + patientCount: 120, + }), + sample({ + cohort: "BIOFIND", + months: 0, + patientCount: 50, + }), + sample({ + cohort: "BIOFIND", + months: Infinity, + }), + sample({ + cohort: "Unknown study", + months: -Infinity, + }), + ]; + + const series = groupRetentionByCohort(data); + + expect(series).toEqual([ + { + name: "BIOFIND", + points: [ + { + months: 0, + patientCount: 50, + totalPatientCount: 100, + retentionPercent: 50, + }, + ], + }, + { + name: "PPMI", + points: [ + { + months: 0, + patientCount: 100, + totalPatientCount: 100, + retentionPercent: 100, + }, + { + months: 6, + patientCount: 120, + totalPatientCount: 100, + retentionPercent: null, + }, + { + months: 12, + patientCount: 60, + totalPatientCount: 100, + retentionPercent: 60, + }, + ], + }, + ]); + }); + + it("returns no series when all time coordinates are invalid", () => { + const data = [ + sample({ cohort: "PPMI", months: NaN }), + sample({ cohort: "BIOFIND", months: Infinity }), + sample({ cohort: "PDBP", months: -Infinity }), + ]; + + expect(groupRetentionByCohort(data)).toEqual([]); + }); }); From fd9a64f94f550e6a83b8c5c05daa00f163ecac68 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:16:46 +0100 Subject: [PATCH 013/102] test(frontend): extend chord diagram transformation coverage --- .../mappings/utils/chord-data.test.ts | 254 ++++++++++++++++++ 1 file changed, 254 insertions(+) diff --git a/frontend/src/features/mappings/utils/chord-data.test.ts b/frontend/src/features/mappings/utils/chord-data.test.ts index a1623c9..af38a52 100644 --- a/frontend/src/features/mappings/utils/chord-data.test.ts +++ b/frontend/src/features/mappings/utils/chord-data.test.ts @@ -239,4 +239,258 @@ describe("prepareChordData", () => { expect(nodes[1]?.name).toBe("A"); expect(links[0]?.source).toBe("B"); }); + + it("rejects nodes with empty names or cohort identifiers", () => { + const data: ChordDiagramData = { + nodes: [ + { name: "", group: "PPMI" }, + { name: " ", group: "BioFIND" }, + { name: "Age", group: "" }, + { name: "Score", group: " " }, + { name: "Age", group: "PPMI" }, + ], + links: [], + }; + + const result = prepareChordData(data); + + expect(result.chunks).toEqual([ + { + nodes: [ + { + id: JSON.stringify(["PPMI", "Age"]), + name: "Age", + group: "PPMI", + }, + ], + links: [], + }, + ]); + + expect(result.diagnostics).toEqual({ + unresolvedLinks: 0, + duplicateLinks: 0, + duplicateNodes: 0, + invalidNodes: 4, + unlinkedNodes: 1, + oversizedComponents: 0, + }); + }); + + it("normalizes whitespace before deduplicating nodes and links", () => { + const data: ChordDiagramData = { + nodes: [ + { name: " Age ", group: " PPMI " }, + { name: "Age", group: "PPMI" }, + { name: " Enrollment age ", group: " BioFIND " }, + ], + links: [ + { source: " Age ", target: " Enrollment age " }, + { source: "Enrollment age", target: "Age" }, + ], + }; + + const result = prepareChordData(data); + + expect(result.chunks).toEqual([ + { + nodes: [ + { + id: JSON.stringify(["BioFIND", "Enrollment age"]), + name: "Enrollment age", + group: "BioFIND", + }, + { + id: JSON.stringify(["PPMI", "Age"]), + name: "Age", + group: "PPMI", + }, + ], + links: [ + { + sourceId: JSON.stringify(["BioFIND", "Enrollment age"]), + targetId: JSON.stringify(["PPMI", "Age"]), + }, + ], + }, + ]); + + expect(result.diagnostics).toEqual({ + unresolvedLinks: 0, + duplicateLinks: 1, + duplicateNodes: 1, + invalidNodes: 0, + unlinkedNodes: 0, + oversizedComponents: 0, + }); + }); + + it("reports links with blank or missing endpoints", () => { + const data: ChordDiagramData = { + nodes: [ + { name: "Age", group: "PPMI" }, + { name: "Enrollment age", group: "BioFIND" }, + ], + links: [ + { source: "", target: "Enrollment age" }, + { source: "Age", target: " " }, + { source: "", target: "" }, + { source: "Unknown source", target: "Enrollment age" }, + { source: "Age", target: "Unknown target" }, + { source: "Age", target: "Enrollment age" }, + ], + }; + + const result = prepareChordData(data); + + expect(result.chunks).toHaveLength(1); + expect(result.chunks[0]?.nodes).toHaveLength(2); + expect(result.chunks[0]?.links).toEqual([ + { + sourceId: JSON.stringify(["BioFIND", "Enrollment age"]), + targetId: JSON.stringify(["PPMI", "Age"]), + }, + ]); + + expect(result.diagnostics.unresolvedLinks).toBe(5); + expect(result.diagnostics.unlinkedNodes).toBe(0); + }); + + it("deduplicates resolved edges between identically named variables", () => { + const data: ChordDiagramData = { + nodes: [ + { name: "Age", group: "PPMI" }, + { name: "Age", group: "BioFIND" }, + ], + links: [{ source: "Age", target: "Age" }], + }; + + const result = prepareChordData(data); + + expect(result.chunks).toHaveLength(1); + expect(result.chunks[0]?.nodes).toHaveLength(2); + + expect(result.chunks[0]?.links).toEqual([ + { + sourceId: JSON.stringify(["BioFIND", "Age"]), + targetId: JSON.stringify(["PPMI", "Age"]), + }, + ]); + + expect(result.diagnostics.unresolvedLinks).toBe(0); + expect(result.diagnostics.duplicateLinks).toBe(0); + expect(result.diagnostics.unlinkedNodes).toBe(0); + }); + + it("traverses cyclic graphs without duplicating nodes or edges", () => { + const data: ChordDiagramData = { + nodes: [ + { name: "A1", group: "A" }, + { name: "B1", group: "B" }, + { name: "C1", group: "C" }, + ], + links: [ + { source: "A1", target: "B1" }, + { source: "B1", target: "C1" }, + { source: "C1", target: "A1" }, + ], + }; + + const result = prepareChordData(data); + + expect(result.chunks).toHaveLength(1); + + expect(result.chunks[0]?.nodes.map((node) => node.id)).toEqual([ + JSON.stringify(["A", "A1"]), + JSON.stringify(["B", "B1"]), + JSON.stringify(["C", "C1"]), + ]); + + expect(result.chunks[0]?.links).toEqual([ + { + sourceId: JSON.stringify(["A", "A1"]), + targetId: JSON.stringify(["B", "B1"]), + }, + { + sourceId: JSON.stringify(["B", "B1"]), + targetId: JSON.stringify(["C", "C1"]), + }, + { + sourceId: JSON.stringify(["A", "A1"]), + targetId: JSON.stringify(["C", "C1"]), + }, + ]); + + expect(result.diagnostics).toEqual({ + unresolvedLinks: 0, + duplicateLinks: 0, + duplicateNodes: 0, + invalidNodes: 0, + unlinkedNodes: 0, + oversizedComponents: 0, + }); + }); + + it("packs independent components up to the exact page capacity", () => { + const data: ChordDiagramData = { + nodes: [ + { name: "A1", group: "A" }, + { name: "B1", group: "B" }, + { name: "A2", group: "A" }, + { name: "B2", group: "B" }, + { name: "Isolated", group: "C" }, + ], + links: [ + { source: "A1", target: "B1" }, + { source: "A2", target: "B2" }, + ], + }; + + const result = prepareChordData(data, 4); + + expect(result.chunks).toHaveLength(2); + + expect(result.chunks.map((chunk) => chunk.nodes.length)).toEqual([4, 1]); + + expect(result.chunks.map((chunk) => chunk.links.length)).toEqual([2, 0]); + + expect(result.chunks[1]?.nodes.map((node) => node.name)).toEqual([ + "Isolated", + ]); + + for (const chunk of result.chunks) { + const nodeIds = new Set(chunk.nodes.map((node) => node.id)); + + for (const link of chunk.links) { + expect(nodeIds.has(link.sourceId)).toBe(true); + expect(nodeIds.has(link.targetId)).toBe(true); + } + } + + expect(result.diagnostics.oversizedComponents).toBe(0); + expect(result.diagnostics.unlinkedNodes).toBe(1); + }); + + it("returns no chunks when all nodes are invalid", () => { + const data: ChordDiagramData = { + nodes: [ + { name: "", group: "PPMI" }, + { name: "Age", group: "" }, + ], + links: [{ source: "Age", target: "Score" }], + }; + + const result = prepareChordData(data); + + expect(result.chunks).toEqual([]); + + expect(result.diagnostics).toEqual({ + unresolvedLinks: 1, + duplicateLinks: 0, + duplicateNodes: 0, + invalidNodes: 2, + unlinkedNodes: 0, + oversizedComponents: 0, + }); + }); }); From addb8f79c7355ce22a13d47b6f9b20e9d518e545 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:20:55 +0100 Subject: [PATCH 014/102] test(frontend): add biomarker chart configuration tests --- .../biomarker-chart-options.test.ts | 427 ++++++++++++++++++ 1 file changed, 427 insertions(+) create mode 100644 frontend/src/features/biomarkers/components/biomarker-chart-options.test.ts diff --git a/frontend/src/features/biomarkers/components/biomarker-chart-options.test.ts b/frontend/src/features/biomarkers/components/biomarker-chart-options.test.ts new file mode 100644 index 0000000..5608a79 --- /dev/null +++ b/frontend/src/features/biomarkers/components/biomarker-chart-options.test.ts @@ -0,0 +1,427 @@ +import { describe, expect, it } from "vitest"; + +import type { BiomarkerDistribution } from "../types"; + +import { + buildBiomarkerChartOptions, + prepareBiomarkerDistributions, + type BiomarkerChartOption, +} from "./biomarker-chart-options"; + +function sample( + overrides: Partial = {}, +): BiomarkerDistribution { + return { + label: "Study A (PD Group)", + cohort: "Study A", + diagnosis: "PD", + values: [1, 2, 3, 4, 5, 100], + ...overrides, + }; +} + +function getFormatter(option: unknown) { + if ( + typeof option !== "object" || + option === null || + !("formatter" in option) || + typeof option.formatter !== "function" + ) { + throw new Error("Expected a callable chart formatter"); + } + + const formatter = option.formatter; + + return (params: unknown): unknown => + Reflect.apply(formatter, undefined, [params]); +} + +function getAxisLabelFormatter(options: BiomarkerChartOption) { + const axis = options.xAxis; + + if (!axis || Array.isArray(axis)) { + throw new Error("Expected a single x-axis configuration"); + } + + return getFormatter(axis.axisLabel); +} + +function createTooltipGroups() { + return prepareBiomarkerDistributions([ + sample({ + label: ' & "PD"', + values: [0, 0, 0, 0, 0, 6], + }), + sample({ + label: "Study B (PD Group)", + cohort: "Study B", + values: [42], + }), + ]); +} + +describe("prepareBiomarkerDistributions", () => { + it("excludes invalid distributions and nonfinite measurements", () => { + const distributions = [ + sample({ + label: "Empty distribution", + values: [], + }), + sample({ + label: "Invalid distribution", + values: [NaN, Infinity, -Infinity], + }), + sample({ + label: "Valid distribution", + values: [3, NaN, 1, Infinity, 2], + }), + ]; + + const prepared = prepareBiomarkerDistributions(distributions); + + expect(prepared).toHaveLength(1); + + expect(prepared[0]).toMatchObject({ + label: "Valid distribution", + stats: { + n: 3, + excludedCount: 2, + median: 2, + values: [1, 2, 3], + }, + }); + + expect(distributions[2].values).toEqual([3, NaN, 1, Infinity, 2]); + }); + + it("uses metadata colors and consistent fallback colors", () => { + const distributions = [ + sample({ + cohort: "Study B", + label: "Study B (PD Group)", + }), + sample({ + cohort: "Study A", + label: "Study A (PD Group)", + }), + sample({ + cohort: "Study B", + diagnosis: "HC", + label: "Study B (HC Group)", + }), + ]; + + const prepared = prepareBiomarkerDistributions(distributions, { + "Study A": "#123456", + }); + + expect(prepared.map((group) => group.color)).toEqual([ + "#d97706", + "#123456", + "#d97706", + ]); + + expect(prepared.map((group) => group.label)).toEqual([ + "Study B (PD Group)", + "Study A (PD Group)", + "Study B (HC Group)", + ]); + + const reversed = prepareBiomarkerDistributions(distributions.toReversed(), { + "Study A": "#123456", + }); + + expect(reversed.map((group) => group.color)).toEqual( + prepared.map((group) => group.color).toReversed(), + ); + }); + + it("reuses palette colors when the number of cohorts exceeds the palette", () => { + const distributions = Array.from({ length: 9 }, (_, index) => + sample({ + cohort: `Study ${index + 1}`, + label: `Study ${index + 1} (PD Group)`, + }), + ); + + const prepared = prepareBiomarkerDistributions(distributions); + + expect(prepared.map((group) => group.color)).toEqual([ + "#2563eb", + "#d97706", + "#059669", + "#9333ea", + "#dc2626", + "#0f766e", + "#4f46e5", + "#be185d", + "#2563eb", + ]); + }); + + it("returns no prepared distributions for empty input", () => { + expect(prepareBiomarkerDistributions([])).toEqual([]); + }); +}); + +describe("buildBiomarkerChartOptions", () => { + it("constructs boxplot and outlier scatter series", () => { + const groups = prepareBiomarkerDistributions( + [ + sample(), + sample({ + label: "Study B (PD Group)", + cohort: "Study B", + values: [-6, 0, 0, 0, 0, 0], + }), + sample({ + label: "Study C (PD Group)", + cohort: "Study C", + values: [10, 20, 30, 40], + }), + ], + { + "Study A": "#123456", + "Study B": "#654321", + "Study C": "#abcdef", + }, + ); + + const options = buildBiomarkerChartOptions(groups); + + expect(options.series).toMatchObject([ + { + type: "boxplot", + name: "Distributions", + data: [ + { + name: "Study A (PD Group)", + value: [1, 2, 3.5, 5, 5], + itemStyle: { + color: "#123456", + borderColor: "#123456", + }, + }, + { + name: "Study B (PD Group)", + value: [0, 0, 0, 0, 0], + itemStyle: { + color: "#654321", + borderColor: "#654321", + }, + }, + { + name: "Study C (PD Group)", + value: [10, 15, 25, 35, 40], + itemStyle: { + color: "#abcdef", + borderColor: "#abcdef", + }, + }, + ], + }, + { + type: "scatter", + name: "Outliers", + data: [ + { + name: "Study A (PD Group)", + value: [0, 100], + itemStyle: { + color: "#123456", + }, + }, + { + name: "Study B (PD Group)", + value: [1, -6], + itemStyle: { + color: "#654321", + }, + }, + ], + }, + ]); + + expect(options.xAxis).toMatchObject({ + type: "category", + data: ["Study A (PD Group)", "Study B (PD Group)", "Study C (PD Group)"], + }); + + expect(options.yAxis).toMatchObject({ + type: "value", + scale: true, + name: "Measurement value", + }); + }); + + it("constructs an empty chart with default accessibility information", () => { + const options = buildBiomarkerChartOptions([]); + + expect(options).toMatchObject({ + animation: false, + backgroundColor: "#ffffff", + aria: { + enabled: true, + label: { + description: + "Biomarker distributions. Boxplots showing medians, " + + "quartiles, whiskers, and statistical outliers.", + }, + }, + xAxis: { + data: [], + }, + series: [ + { + type: "boxplot", + data: [], + }, + { + type: "scatter", + data: [], + }, + ], + }); + }); + + it.each([ + { + compact: false, + left: 100, + right: 32, + bottom: 110, + rotation: 25, + limit: 22, + truncated: "ABCDEFGHIJKLMNOPQRS...", + }, + { + compact: true, + left: 80, + right: 20, + bottom: 90, + rotation: 35, + limit: 16, + truncated: "ABCDEFGHIJKLM...", + }, + ])( + "configures responsive chart options with compact=$compact", + ({ compact, left, right, bottom, rotation, limit, truncated }) => { + const options = buildBiomarkerChartOptions( + prepareBiomarkerDistributions([sample()]), + compact, + "Age distributions", + ); + + expect(options.grid).toMatchObject({ + left, + right, + top: 30, + bottom, + }); + + expect(options.xAxis).toMatchObject({ + axisLabel: { + rotate: rotation, + }, + }); + + expect(options.aria).toMatchObject({ + enabled: true, + label: { + description: + "Age distributions. Boxplots showing medians, " + + "quartiles, whiskers, and statistical outliers.", + }, + }); + + const formatter = getAxisLabelFormatter(options); + + expect(formatter("Age")).toBe("Age"); + + expect(formatter("A".repeat(limit))).toBe("A".repeat(limit)); + + expect(formatter("ABCDEFGHIJKLMNOPQRSTUVWXYZ")).toBe(truncated); + }, + ); +}); + +describe("biomarker tooltip formatter", () => { + it("formats boxplot statistics and escapes the group label", () => { + const options = buildBiomarkerChartOptions(createTooltipGroups()); + const formatter = getFormatter(options.tooltip); + + expect(formatter({ seriesIndex: 0, dataIndex: 0 })).toBe( + [ + "<Study A> & "PD"", + "Participants: 6", + "Median: 0", + "Q1: 0", + "Q3: 0", + "Whiskers: 0 - 0", + "Mean: 1", + "SD: 2.4495", + "Outliers: 1", + ].join("
"), + ); + }); + + it("formats outlier measurements using the corresponding group index", () => { + const options = buildBiomarkerChartOptions(createTooltipGroups()); + const formatter = getFormatter(options.tooltip); + + expect( + formatter({ + seriesIndex: 1, + dataIndex: 0, + value: [0, 6], + }), + ).toBe( + [ + "<Study A> & "PD"", + "Measurement: 6", + "Outlier", + ].join("
"), + ); + }); + + it("displays unavailable standard deviations for single observations", () => { + const options = buildBiomarkerChartOptions(createTooltipGroups()); + const formatter = getFormatter(options.tooltip); + + expect(formatter({ seriesIndex: 0, dataIndex: 1 })).toBe( + [ + "Study B (PD Group)", + "Participants: 1", + "Median: 42", + "Q1: 42", + "Q3: 42", + "Whiskers: 42 - 42", + "Mean: 42", + "SD: N/R", + "Outliers: 0", + ].join("
"), + ); + }); + + it.each([ + null, + undefined, + "invalid", + {}, + { dataIndex: 0 }, + { seriesIndex: 0 }, + { seriesIndex: "0", dataIndex: 0 }, + { seriesIndex: 0, dataIndex: "0" }, + { seriesIndex: 0, dataIndex: 99 }, + { seriesIndex: 1, dataIndex: 0 }, + { seriesIndex: 1, dataIndex: 0, value: 100 }, + { seriesIndex: 1, dataIndex: 0, value: ["0", 6] }, + { seriesIndex: 1, dataIndex: 0, value: [0, "6"] }, + { seriesIndex: 1, dataIndex: 0, value: [99, 6] }, + ])("returns an empty tooltip for invalid parameters: %j", (params) => { + const options = buildBiomarkerChartOptions(createTooltipGroups()); + const formatter = getFormatter(options.tooltip); + + expect(formatter(params)).toBe(""); + }); +}); From f18cd3a2e55183cac8a2313540b276f9f9d1fe84 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:23:54 +0100 Subject: [PATCH 015/102] refactor(frontend): reuse shared HTML escaping utility --- .../components/longitudinal-chart-options.ts | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/frontend/src/features/longitudinal/components/longitudinal-chart-options.ts b/frontend/src/features/longitudinal/components/longitudinal-chart-options.ts index 4e4b5d6..71c06e6 100644 --- a/frontend/src/features/longitudinal/components/longitudinal-chart-options.ts +++ b/frontend/src/features/longitudinal/components/longitudinal-chart-options.ts @@ -9,6 +9,7 @@ import type { } from "echarts/components"; import { formatNumber } from "@/lib/formatters"; +import { escapeHtml } from "@/lib/html"; import type { RetentionSeries } from "../utils/retention"; export type LongitudinalChartOption = ComposeOption< @@ -35,15 +36,6 @@ const SYMBOLS = ["circle", "rect", "diamond", "triangle", "roundRect"] as const; const LINE_STYLES = ["solid", "dashed", "dotted"] as const; -function escapeHtml(value: string): string { - return value - .replaceAll("&", "&") - .replaceAll("<", "<") - .replaceAll(">", ">") - .replaceAll('"', """) - .replaceAll("'", "'"); -} - interface TooltipPoint { seriesIndex: number; dataIndex: number; From 9079dd7301c5fc9ea3a1f0bae483b73705165dd9 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:23:59 +0100 Subject: [PATCH 016/102] test(frontend): add longitudinal chart configuration tests --- .../longitudinal-chart-options.test.ts | 468 ++++++++++++++++++ 1 file changed, 468 insertions(+) create mode 100644 frontend/src/features/longitudinal/components/longitudinal-chart-options.test.ts diff --git a/frontend/src/features/longitudinal/components/longitudinal-chart-options.test.ts b/frontend/src/features/longitudinal/components/longitudinal-chart-options.test.ts new file mode 100644 index 0000000..fa967d9 --- /dev/null +++ b/frontend/src/features/longitudinal/components/longitudinal-chart-options.test.ts @@ -0,0 +1,468 @@ +import { describe, expect, it } from "vitest"; + +import type { RetentionSeries } from "../utils/retention"; + +import { + buildLongitudinalChartOptions, + getSeriesColor, + type LongitudinalChartOption, +} from "./longitudinal-chart-options"; + +const sampleSeries: RetentionSeries[] = [ + { + name: "Study A", + points: [ + { + months: 0, + retentionPercent: 100, + patientCount: 1500, + totalPatientCount: 1500, + }, + { + months: 6, + retentionPercent: 83.33333333333334, + patientCount: 1250, + totalPatientCount: 1500, + }, + { + months: 12, + retentionPercent: null, + patientCount: 1600, + totalPatientCount: 1500, + }, + { + months: 18, + retentionPercent: 0, + patientCount: 0, + totalPatientCount: 1500, + }, + ], + }, + { + name: "Study B", + points: [ + { + months: 6, + retentionPercent: 50, + patientCount: 50, + totalPatientCount: 100, + }, + { + months: 12, + retentionPercent: 20, + patientCount: 20, + totalPatientCount: 100, + }, + ], + }, +]; + +function getTooltipFormatter(options: LongitudinalChartOption) { + const tooltip = options.tooltip; + + if ( + typeof tooltip !== "object" || + tooltip === null || + !("formatter" in tooltip) || + typeof tooltip.formatter !== "function" + ) { + throw new Error("Expected a callable tooltip formatter"); + } + + const formatter = tooltip.formatter; + + return (params: unknown): unknown => + Reflect.apply(formatter, undefined, [params]); +} + +describe("getSeriesColor", () => { + it("prioritizes explicitly configured cohort colors", () => { + expect( + getSeriesColor("Study A", 0, { + "Study A": "#123456", + }), + ).toBe("#123456"); + }); + + it.each([ + { index: 0, expected: "#2563eb" }, + { index: 1, expected: "#d97706" }, + { index: 7, expected: "#4f46e5" }, + { index: 8, expected: "#2563eb" }, + { index: 9, expected: "#d97706" }, + ])("returns the palette color for index $index", ({ index, expected }) => { + expect(getSeriesColor("Unknown study", index, {})).toBe(expected); + }); + + it.each([-1, NaN, Infinity, 1.5])( + "returns the defensive fallback for invalid index %s", + (index) => { + expect(getSeriesColor("Unknown study", index, {})).toBe("#610030"); + }, + ); +}); + +describe("buildLongitudinalChartOptions", () => { + it("constructs line series and preserves missing measurements", () => { + const options = buildLongitudinalChartOptions(sampleSeries, { + "Study A": "#123456", + }); + + expect(options.series).toMatchObject([ + { + type: "line", + name: "Study A", + data: [ + [0, 100], + [6, 83.33333333333334], + [12, null], + [18, 0], + ], + symbol: "circle", + symbolSize: 7, + showSymbol: true, + smooth: false, + connectNulls: false, + lineStyle: { + color: "#123456", + width: 2.5, + type: "solid", + }, + itemStyle: { + color: "#123456", + }, + emphasis: { + focus: "series", + }, + markLine: { + silent: true, + symbol: "none", + label: { + show: true, + formatter: "50% retention", + }, + data: [{ yAxis: 50 }], + }, + }, + { + type: "line", + name: "Study B", + data: [ + [6, 50], + [12, 20], + ], + symbol: "rect", + smooth: false, + connectNulls: false, + lineStyle: { + color: "#d97706", + type: "dashed", + }, + itemStyle: { + color: "#d97706", + }, + markLine: undefined, + }, + ]); + + expect(options.yAxis).toMatchObject({ + type: "value", + min: 0, + max: 100, + interval: 20, + }); + + expect(options.xAxis).toMatchObject({ + type: "value", + min: 0, + }); + }); + + it("constructs an empty chart with default accessibility information", () => { + const options = buildLongitudinalChartOptions([]); + + expect(options).toMatchObject({ + animation: false, + backgroundColor: "#ffffff", + aria: { + enabled: true, + label: { + description: + "Participant retention. Participant retention over months in study.", + }, + }, + series: [], + }); + }); + + it("cycles symbols and line styles for multiple series", () => { + const series: RetentionSeries[] = Array.from({ length: 6 }, (_, index) => ({ + name: `Study ${index + 1}`, + points: [], + })); + + const options = buildLongitudinalChartOptions(series); + + expect(options.series).toMatchObject([ + { + symbol: "circle", + lineStyle: { type: "solid" }, + }, + { + symbol: "rect", + lineStyle: { type: "dashed" }, + }, + { + symbol: "diamond", + lineStyle: { type: "dotted" }, + }, + { + symbol: "triangle", + lineStyle: { type: "solid" }, + }, + { + symbol: "roundRect", + lineStyle: { type: "dashed" }, + }, + { + symbol: "circle", + lineStyle: { type: "dotted" }, + }, + ]); + }); + + it.each([ + { + compact: false, + trigger: "axis", + showLegend: true, + left: 16, + right: 20, + top: 24, + bottom: 90, + xAxisName: "Months in Study", + yAxisName: "Retention (%)", + splitNumber: 6, + }, + { + compact: true, + trigger: "item", + showLegend: false, + left: 8, + right: 8, + top: 12, + bottom: 55, + xAxisName: "Months", + yAxisName: "", + splitNumber: 4, + }, + ])( + "configures responsive chart options with compact=$compact", + ({ + compact, + trigger, + showLegend, + left, + right, + top, + bottom, + xAxisName, + yAxisName, + splitNumber, + }) => { + const options = buildLongitudinalChartOptions( + sampleSeries, + {}, + "Age availability", + compact, + ); + + expect(options.tooltip).toMatchObject({ + trigger, + confine: true, + renderMode: "html", + }); + + expect(options.legend).toMatchObject({ + show: showLegend, + type: "scroll", + }); + + expect(options.grid).toMatchObject({ + left, + right, + top, + bottom, + containLabel: true, + }); + + expect(options.xAxis).toMatchObject({ + name: xAxisName, + splitNumber, + }); + + expect(options.yAxis).toMatchObject({ + name: yAxisName, + axisLabel: { + formatter: "{value}%", + }, + }); + + expect(options.series).toMatchObject([ + { + markLine: { + label: { + show: !compact, + }, + data: [{ yAxis: 50 }], + }, + }, + { + markLine: undefined, + }, + ]); + + expect(options.aria).toMatchObject({ + enabled: true, + label: { + description: + "Age availability. Participant retention over months in study.", + }, + }); + }, + ); +}); + +describe("longitudinal tooltip formatter", () => { + it("formats participant counts and retention percentages", () => { + const options = buildLongitudinalChartOptions(sampleSeries); + const formatter = getTooltipFormatter(options); + + const tooltip = formatter({ + seriesIndex: 0, + dataIndex: 1, + }); + + expect(tooltip).toContain("Study A"); + expect(tooltip).toContain("Month: 6"); + expect(tooltip).toContain("Retention: 83.3%"); + expect(tooltip).toMatch(/Participants: 1,250\s*\/ 1,500/); + }); + + it("escapes HTML characters in series names", () => { + const series: RetentionSeries[] = [ + { + ...sampleSeries[0], + name: ` & "PD" 'Group'`, + }, + ]; + + const options = buildLongitudinalChartOptions(series); + const formatter = getTooltipFormatter(options); + + const tooltip = formatter({ + seriesIndex: 0, + dataIndex: 0, + }); + + expect(tooltip).toContain( + "<Study A> & "PD" 'Group'", + ); + + expect(tooltip).not.toContain(""); + }); + + it("displays unavailable retention as N/R", () => { + const options = buildLongitudinalChartOptions(sampleSeries); + const formatter = getTooltipFormatter(options); + + const tooltip = formatter({ + seriesIndex: 0, + dataIndex: 2, + }); + + expect(tooltip).toContain("Month: 12"); + expect(tooltip).toContain("Retention: N/R"); + expect(tooltip).toMatch(/Participants: 1,600\s*\/ 1,500/); + }); + + it("displays zero retention as a valid percentage", () => { + const options = buildLongitudinalChartOptions(sampleSeries); + const formatter = getTooltipFormatter(options); + + const tooltip = formatter({ + seriesIndex: 0, + dataIndex: 3, + }); + + expect(tooltip).toContain("Retention: 0.0%"); + expect(tooltip).toMatch(/Participants: 0\s*\/ 1,500/); + }); + + it("formats multiple series and ignores invalid tooltip entries", () => { + const options = buildLongitudinalChartOptions(sampleSeries); + const formatter = getTooltipFormatter(options); + + const first = { + seriesIndex: 0, + dataIndex: 1, + }; + + const second = { + seriesIndex: 1, + dataIndex: 0, + }; + + const tooltip = formatter([ + first, + null, + { seriesIndex: 99, dataIndex: 0 }, + { seriesIndex: 0, dataIndex: 99 }, + second, + "invalid", + ]); + + expect(tooltip).toBe([formatter(first), formatter(second)].join("")); + + expect(tooltip).toContain("Study A"); + expect(tooltip).toContain("Study B"); + expect(tooltip).toContain("Retention: 83.3%"); + expect(tooltip).toContain("Retention: 50.0%"); + }); + + it.each([ + { params: null }, + { params: undefined }, + { params: "invalid" }, + { params: {} }, + { params: { dataIndex: 0 } }, + { params: { seriesIndex: 0 } }, + { params: { seriesIndex: "0", dataIndex: 0 } }, + { params: { seriesIndex: 0, dataIndex: "0" } }, + { params: { seriesIndex: 99, dataIndex: 0 } }, + { params: { seriesIndex: 0, dataIndex: 99 } }, + { params: { seriesIndex: -1, dataIndex: 0 } }, + { params: { seriesIndex: 0, dataIndex: -1 } }, + { params: [] }, + ])( + "returns an empty tooltip for invalid parameters: $params", + ({ params }) => { + const options = buildLongitudinalChartOptions(sampleSeries); + const formatter = getTooltipFormatter(options); + + expect(formatter(params)).toBe(""); + }, + ); + + it("returns an empty tooltip when no series exist", () => { + const options = buildLongitudinalChartOptions([]); + const formatter = getTooltipFormatter(options); + + expect( + formatter({ + seriesIndex: 0, + dataIndex: 0, + }), + ).toBe(""); + }); +}); From 38db8b43816ff32a7dfd72d0339e743f9f07a78b Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:26:43 +0100 Subject: [PATCH 017/102] fix(frontend): prevent inherited properties in race color lookup --- frontend/src/features/races/components/race-chart-options.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/features/races/components/race-chart-options.ts b/frontend/src/features/races/components/race-chart-options.ts index a213444..f6399dd 100644 --- a/frontend/src/features/races/components/race-chart-options.ts +++ b/frontend/src/features/races/components/race-chart-options.ts @@ -32,7 +32,7 @@ const EXTRA_COLORS = [ ] as const; export function getRaceColor(name: string): string { - if (COLORS[name]) return COLORS[name]; + if (Object.hasOwn(COLORS, name)) return COLORS[name]; let hash = 0; for (const character of name) hash = (hash * 31 + character.codePointAt(0)!) >>> 0; From 7b60050627dfbec313e89a4550d1d9c4ab713b89 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:26:47 +0100 Subject: [PATCH 018/102] test(frontend): add race distribution chart configuration tests --- .../components/race-chart-options.test.ts | 282 ++++++++++++++++++ 1 file changed, 282 insertions(+) create mode 100644 frontend/src/features/races/components/race-chart-options.test.ts diff --git a/frontend/src/features/races/components/race-chart-options.test.ts b/frontend/src/features/races/components/race-chart-options.test.ts new file mode 100644 index 0000000..74bf283 --- /dev/null +++ b/frontend/src/features/races/components/race-chart-options.test.ts @@ -0,0 +1,282 @@ +import { describe, expect, it } from "vitest"; + +import type { RaceDistributionData } from "../types"; + +import { + buildRaceChartOptions, + getRaceColor, + getTotalSelections, + type RaceChartOption, +} from "./race-chart-options"; + +function sample( + overrides: Partial = {}, +): RaceDistributionData { + return { + name: "White", + value: 1250, + validCount: 1300, + unknownCount: 100, + missingCount: 100, + ...overrides, + }; +} + +const sampleRows = [ + sample({ + name: "American Indian or Alaska Native", + value: 0, + }), + sample(), + sample({ + name: "Asian", + value: 250, + }), +]; + +function getTooltipFormatter(options: RaceChartOption) { + const tooltip = options.tooltip; + + if ( + typeof tooltip !== "object" || + tooltip === null || + !("formatter" in tooltip) || + typeof tooltip.formatter !== "function" + ) { + throw new Error("Expected a callable tooltip formatter"); + } + + const formatter = tooltip.formatter; + + return (params: unknown): unknown => + Reflect.apply(formatter, undefined, [params]); +} + +describe("getRaceColor", () => { + it.each([ + { name: "White", expected: "#610030" }, + { name: "Asian", expected: "#2563eb" }, + { + name: "Black or African American", + expected: "#059669", + }, + { + name: "Native Hawaiian or Other Pacific Islander", + expected: "#d97706", + }, + { + name: "American Indian or Alaska Native", + expected: "#7c3aed", + }, + ])("returns the configured color for $name", ({ name, expected }) => { + expect(getRaceColor(name)).toBe(expected); + }); + + it.each([ + { name: "Other", expected: "#a21caf" }, + { name: "Unknown category", expected: "#a21caf" }, + { name: "𐐀", expected: "#9a3412" }, + { name: "", expected: "#be123c" }, + ])( + "returns a deterministic fallback color for $name", + ({ name, expected }) => { + expect(getRaceColor(name)).toBe(expected); + expect(getRaceColor(name)).toBe(expected); + }, + ); + + it.each(["constructor", "toString", "__proto__"])( + "does not use inherited object properties: %s", + (name) => { + expect(getRaceColor(name)).toMatch(/^#[0-9a-f]{6}$/); + }, + ); +}); + +describe("getTotalSelections", () => { + it("sums recorded selections rather than participant counts", () => { + expect(getTotalSelections(sampleRows)).toBe(1500); + }); + + it("returns zero for empty input", () => { + expect(getTotalSelections([])).toBe(0); + }); + + it("returns zero when all selection counts are zero", () => { + expect( + getTotalSelections([ + sample({ value: 0 }), + sample({ name: "Asian", value: 0 }), + ]), + ).toBe(0); + }); +}); + +describe("buildRaceChartOptions", () => { + it("constructs a pie chart using positive selection counts", () => { + const options = buildRaceChartOptions(sampleRows); + + expect(options).toMatchObject({ + animation: false, + backgroundColor: "#ffffff", + aria: { + enabled: true, + label: { + description: + "Pie chart with 1,500 recorded race selections. " + + "Participants may select multiple categories.", + }, + }, + tooltip: { + trigger: "item", + confine: true, + renderMode: "html", + }, + series: [ + { + name: "Race selections", + type: "pie", + radius: ["50%", "73%"], + center: ["50%", "50%"], + stillShowZeroSum: false, + label: { + show: false, + }, + labelLine: { + show: false, + }, + data: [ + { + name: "White", + value: 1250, + itemStyle: { + color: "#610030", + }, + }, + { + name: "Asian", + value: 250, + itemStyle: { + color: "#2563eb", + }, + }, + ], + }, + ], + }); + + expect(sampleRows).toHaveLength(3); + expect(sampleRows[0].value).toBe(0); + }); + + it.each([ + { + label: "empty input", + rows: [], + }, + { + label: "zero selections", + rows: [sample({ value: 0 }), sample({ name: "Asian", value: 0 })], + }, + ])("constructs an empty chart for $label", ({ rows }) => { + const options = buildRaceChartOptions(rows); + + expect(options).toMatchObject({ + aria: { + enabled: true, + label: { + description: + "Pie chart with 0 recorded race selections. " + + "Participants may select multiple categories.", + }, + }, + series: [ + { + type: "pie", + stillShowZeroSum: false, + data: [], + }, + ], + }); + }); +}); + +describe("race tooltip formatter", () => { + it("formats counts and percentages using filtered chart indices", () => { + const options = buildRaceChartOptions(sampleRows); + const formatter = getTooltipFormatter(options); + + expect(formatter({ dataIndex: 0 })).toBe( + "White" + + "
1,250 selections
" + + "
83.3% of recorded selections
", + ); + + expect(formatter({ dataIndex: 1 })).toBe( + "Asian" + + "
250 selections
" + + "
16.7% of recorded selections
", + ); + }); + + it("escapes HTML characters in category names", () => { + const options = buildRaceChartOptions([ + sample({ + name: ` & "Other" 'Group'`, + value: 100, + }), + ]); + + const formatter = getTooltipFormatter(options); + + expect(formatter({ dataIndex: 0 })).toBe( + "<Category> & "Other" 'Group'" + + "
100 selections
" + + "
100.0% of recorded selections
", + ); + }); + + it("formats small selection percentages", () => { + const options = buildRaceChartOptions([ + sample({ value: 999 }), + sample({ + name: "Asian", + value: 1, + }), + ]); + + const formatter = getTooltipFormatter(options); + + expect(formatter({ dataIndex: 1 })).toContain( + "0.1% of recorded selections", + ); + }); + + it.each([ + { params: null }, + { params: undefined }, + { params: "invalid" }, + { params: {} }, + { params: { dataIndex: "0" } }, + { params: { dataIndex: -1 } }, + { params: { dataIndex: 99 } }, + { params: { dataIndex: NaN } }, + { params: { dataIndex: 0.5 } }, + ])( + "returns an empty tooltip for invalid parameters: $params", + ({ params }) => { + const options = buildRaceChartOptions(sampleRows); + const formatter = getTooltipFormatter(options); + + expect(formatter(params)).toBe(""); + }, + ); + + it("returns an empty tooltip when no selections exist", () => { + const options = buildRaceChartOptions([sample({ value: 0 })]); + + const formatter = getTooltipFormatter(options); + + expect(formatter({ dataIndex: 0 })).toBe(""); + }); +}); From a7ac63e297598cb36bacc3178c5aeaab9e3b18d6 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:46:17 +0100 Subject: [PATCH 019/102] test(frontend): add comprehensive API client tests --- frontend/src/lib/api/client.test.ts | 435 ++++++++++++++++++++++++++++ 1 file changed, 435 insertions(+) create mode 100644 frontend/src/lib/api/client.test.ts diff --git a/frontend/src/lib/api/client.test.ts b/frontend/src/lib/api/client.test.ts new file mode 100644 index 0000000..7a0140d --- /dev/null +++ b/frontend/src/lib/api/client.test.ts @@ -0,0 +1,435 @@ +import { http, HttpResponse } from "msw"; +import { describe, expect, it, vi } from "vitest"; + +import { TEST_API_URL } from "@/test/mocks/handlers"; +import { server } from "@/test/mocks/server"; + +import { api, ApiError } from "./client"; + +const TEST_PATH = "/test-client"; +const TEST_URL = `${TEST_API_URL}${TEST_PATH}`; + +describe("api.get", () => { + it.each(["test-client", "/test-client", "///test-client"])( + "normalizes the request path: %s", + async (path) => { + server.use( + http.get(TEST_URL, ({ request }) => { + return HttpResponse.json({ + method: request.method, + url: request.url, + accept: request.headers.get("Accept"), + }); + }), + ); + + await expect(api.get(path)).resolves.toEqual({ + method: "GET", + url: TEST_URL, + accept: "application/json", + }); + }, + ); + + it("preserves query parameters", async () => { + server.use( + http.get(TEST_URL, ({ request }) => { + const params = new URL(request.url).searchParams; + + return HttpResponse.json({ + cohort: params.get("cohort"), + variables: params.getAll("variables"), + }); + }), + ); + + const params = new URLSearchParams(); + + params.set("cohort", "Study A & B"); + params.append("variables", "Age"); + params.append("variables", "Motor score"); + + await expect(api.get(`${TEST_PATH}?${params}`)).resolves.toEqual({ + cohort: "Study A & B", + variables: ["Age", "Motor score"], + }); + }); + + it("preserves custom request headers", async () => { + server.use( + http.get(TEST_URL, ({ request }) => { + return HttpResponse.json({ + accept: request.headers.get("Accept"), + authorization: request.headers.get("Authorization"), + custom: request.headers.get("X-Test-Header"), + }); + }), + ); + + await expect( + api.get(TEST_PATH, { + headers: { + accept: "application/vnd.example+json", + Authorization: "Bearer synthetic-token", + "X-Test-Header": "test-value", + }, + }), + ).resolves.toEqual({ + accept: "application/vnd.example+json", + authorization: "Bearer synthetic-token", + custom: "test-value", + }); + }); + + it("does not mutate supplied headers", async () => { + const headers = new Headers({ + "X-Test-Header": "test-value", + }); + + server.use( + http.get(TEST_URL, ({ request }) => { + return HttpResponse.json({ + accept: request.headers.get("Accept"), + custom: request.headers.get("X-Test-Header"), + }); + }), + ); + + await expect(api.get(TEST_PATH, { headers })).resolves.toEqual({ + accept: "application/json", + custom: "test-value", + }); + + expect(headers.has("Accept")).toBe(false); + expect(headers.get("X-Test-Header")).toBe("test-value"); + }); +}); + +describe("api.post", () => { + it.each([ + { body: ["Age", "Motor score"] }, + { body: { cohort: "Study A", variables: ["Age"] } }, + { body: null }, + ])("serializes the JSON request body: $body", async ({ body }) => { + server.use( + http.post(TEST_URL, async ({ request }) => { + const payload: unknown = await request.json(); + + return HttpResponse.json({ + method: request.method, + contentType: request.headers.get("Content-Type"), + accept: request.headers.get("Accept"), + body: payload, + }); + }), + ); + + await expect(api.post(TEST_PATH, body)).resolves.toEqual({ + method: "POST", + contentType: "application/json", + accept: "application/json", + body, + }); + }); + + it("preserves custom headers while enforcing JSON content type", async () => { + const headers = new Headers({ + "Content-Type": "text/plain", + Accept: "application/vnd.example+json", + Authorization: "Bearer synthetic-token", + }); + + server.use( + http.post(TEST_URL, ({ request }) => { + return HttpResponse.json({ + contentType: request.headers.get("Content-Type"), + accept: request.headers.get("Accept"), + authorization: request.headers.get("Authorization"), + }); + }), + ); + + await expect(api.post(TEST_PATH, ["Age"], { headers })).resolves.toEqual({ + contentType: "application/json", + accept: "application/vnd.example+json", + authorization: "Bearer synthetic-token", + }); + + expect(headers.get("Content-Type")).toBe("text/plain"); + }); +}); + +describe("API error handling", () => { + it.each([ + { + status: 400, + body: { detail: " Invalid request " }, + message: "Invalid request", + }, + { + status: 401, + body: { detail: "Could not validate credentials" }, + message: "Could not validate credentials", + }, + { + status: 422, + body: { + detail: [ + { msg: " First validation error " }, + { msg: "Second validation error" }, + ], + }, + message: "First validation error; Second validation error", + }, + { + status: 422, + body: { + detail: [ + null, + "invalid", + {}, + { msg: 42 }, + { msg: "" }, + { msg: " " }, + { msg: "Valid validation error" }, + ], + }, + message: "Valid validation error", + }, + { + status: 503, + body: { message: " Service unavailable " }, + message: "Service unavailable", + }, + { + status: 400, + body: { + detail: "Preferred detail", + message: "Secondary message", + }, + message: "Preferred detail", + }, + { + status: 400, + body: { + detail: " ", + message: "Fallback message", + }, + message: "Fallback message", + }, + { + status: 422, + body: { + detail: [{ msg: " " }, {}], + message: "Validation failed", + }, + message: "Validation failed", + }, + { + status: 500, + body: { detail: 42 }, + message: "Request failed (HTTP 500)", + }, + { + status: 500, + body: { message: 42 }, + message: "Request failed (HTTP 500)", + }, + { + status: 500, + body: { message: " " }, + message: "Request failed (HTTP 500)", + }, + { + status: 500, + body: {}, + message: "Request failed (HTTP 500)", + }, + { + status: 500, + body: null, + message: "Request failed (HTTP 500)", + }, + { + status: 500, + body: "Internal server error", + message: "Request failed (HTTP 500)", + }, + ])( + "extracts the error message for HTTP $status: $message", + async ({ status, body, message }) => { + server.use( + http.get(TEST_URL, () => { + return HttpResponse.json(body, { status }); + }), + ); + + const request = api.get(TEST_PATH); + + await expect(request).rejects.toBeInstanceOf(ApiError); + + await expect(request).rejects.toMatchObject({ + name: "ApiError", + status, + message, + }); + }, + ); + + it("handles non-JSON error responses", async () => { + server.use( + http.get(TEST_URL, () => { + return HttpResponse.text("Bad Gateway", { + status: 502, + }); + }), + ); + + await expect(api.get(TEST_PATH)).rejects.toMatchObject({ + name: "ApiError", + status: 502, + message: "Request failed (HTTP 502)", + }); + }); + + it("handles POST error responses", async () => { + server.use( + http.post(TEST_URL, () => { + return HttpResponse.json( + { detail: "Invalid variable selection" }, + { status: 422 }, + ); + }), + ); + + await expect( + api.post(TEST_PATH, ["Unknown variable"]), + ).rejects.toMatchObject({ + name: "ApiError", + status: 422, + message: "Invalid variable selection", + }); + }); + + it("rejects HTTP 204 responses when JSON is expected", async () => { + server.use( + http.get(TEST_URL, () => { + return new HttpResponse(null, { status: 204 }); + }), + ); + + await expect(api.get(TEST_PATH)).rejects.toThrow( + "Expected a JSON response, but the server returned HTTP 204.", + ); + }); + + it("propagates JSON parsing errors from successful responses", async () => { + server.use( + http.get(TEST_URL, () => { + return HttpResponse.text("Invalid JSON", { + status: 200, + headers: { + "Content-Type": "application/json", + }, + }); + }), + ); + + await expect(api.get(TEST_PATH)).rejects.toBeInstanceOf(SyntaxError); + }); + + it("propagates network failures", async () => { + server.use(http.get(TEST_URL, () => HttpResponse.error())); + + await expect(api.get(TEST_PATH)).rejects.toBeInstanceOf(TypeError); + }); +}); + +describe("request cancellation", () => { + it("forwards the abort signal for GET requests", async () => { + const controller = new AbortController(); + const fetch = vi.spyOn(globalThis, "fetch"); + + server.use(http.get(TEST_URL, () => HttpResponse.json(["Age"]))); + + await expect( + api.get(TEST_PATH, { signal: controller.signal }), + ).resolves.toEqual(["Age"]); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + TEST_URL, + expect.objectContaining({ + method: "GET", + signal: controller.signal, + }), + ); + }); + + it("forwards the abort signal for POST requests", async () => { + const controller = new AbortController(); + const fetch = vi.spyOn(globalThis, "fetch"); + + server.use(http.post(TEST_URL, () => HttpResponse.json([]))); + + await expect( + api.post(TEST_PATH, ["Age"], { + signal: controller.signal, + }), + ).resolves.toEqual([]); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + TEST_URL, + expect.objectContaining({ + method: "POST", + signal: controller.signal, + }), + ); + }); + + it("rejects requests with an already aborted signal", async () => { + const controller = new AbortController(); + + controller.abort(); + + server.use(http.get(TEST_URL, () => HttpResponse.json(["Age"]))); + + await expect( + api.get(TEST_PATH, { signal: controller.signal }), + ).rejects.toMatchObject({ + name: "AbortError", + }); + }); +}); + +describe("API configuration", () => { + it("removes trailing slashes from the API base URL", async () => { + vi.resetModules(); + vi.stubEnv("VITE_API_URL", `${TEST_API_URL}///`); + + const { api: configuredApi } = await import("./client"); + + server.use( + http.get(TEST_URL, ({ request }) => { + return HttpResponse.json({ + url: request.url, + }); + }), + ); + + await expect(configuredApi.get("///test-client")).resolves.toEqual({ + url: TEST_URL, + }); + }); + + it.each([{ value: undefined }, { value: "" }, { value: "///" }])( + "rejects missing API configuration: $value", + async ({ value }) => { + vi.resetModules(); + vi.stubEnv("VITE_API_URL", value); + + await expect(import("./client")).rejects.toThrow( + "VITE_API_URL is not configured", + ); + }, + ); +}); From 342bdf5d7aa0e539a747012d7470f97b738b762b Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:47:35 +0100 Subject: [PATCH 020/102] test(frontend): add CDM API tests --- frontend/src/lib/api/cdm.test.ts | 94 ++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 frontend/src/lib/api/cdm.test.ts diff --git a/frontend/src/lib/api/cdm.test.ts b/frontend/src/lib/api/cdm.test.ts new file mode 100644 index 0000000..0816949 --- /dev/null +++ b/frontend/src/lib/api/cdm.test.ts @@ -0,0 +1,94 @@ +import { http, HttpResponse } from "msw"; +import { describe, expect, it, vi } from "vitest"; + +import { TEST_API_URL } from "@/test/mocks/handlers"; +import { server } from "@/test/mocks/server"; + +import { fetchModalities, fetchVariables } from "./cdm"; +import { ApiError } from "./client"; + +describe.each([ + { + name: "fetchVariables", + fetchData: fetchVariables, + path: "/cdm/variables", + expected: ["Age", "Motor score"], + alternative: ["UPDRS III - Total Score", "Age", "α-synuclein"], + }, + { + name: "fetchModalities", + fetchData: fetchModalities, + path: "/cdm/modalities", + expected: ["Clinical", "Demographics"], + alternative: ["Neuroimaging", "Clinical Assessments", "Demographics"], + }, +])("$name", ({ fetchData, path, expected, alternative }) => { + it("retrieves data from the correct endpoint", async () => { + const fetch = vi.spyOn(globalThis, "fetch"); + + await expect(fetchData()).resolves.toEqual(expected); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}${path}`, + expect.objectContaining({ + method: "GET", + }), + ); + }); + + it("preserves the values and ordering returned by the backend", async () => { + server.use( + http.get(`${TEST_API_URL}${path}`, () => { + return HttpResponse.json(alternative); + }), + ); + + await expect(fetchData()).resolves.toEqual(alternative); + }); + + it("handles empty datasets", async () => { + server.use( + http.get(`${TEST_API_URL}${path}`, () => { + return HttpResponse.json([]); + }), + ); + + await expect(fetchData()).resolves.toEqual([]); + }); + + it("propagates API errors", async () => { + server.use( + http.get(`${TEST_API_URL}${path}`, () => { + return HttpResponse.json( + { detail: "CDM data unavailable" }, + { status: 503 }, + ); + }), + ); + + const request = fetchData(); + + await expect(request).rejects.toBeInstanceOf(ApiError); + + await expect(request).rejects.toMatchObject({ + name: "ApiError", + status: 503, + message: "CDM data unavailable", + }); + }); + + it("forwards the abort signal", async () => { + const controller = new AbortController(); + const fetch = vi.spyOn(globalThis, "fetch"); + + await expect(fetchData(controller.signal)).resolves.toEqual(expected); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}${path}`, + expect.objectContaining({ + method: "GET", + signal: controller.signal, + }), + ); + }); +}); From b93349c94522e5e6b6ba2a44caf460be3e9445e3 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:48:47 +0100 Subject: [PATCH 021/102] test(frontend): add cohort API and metadata contract tests --- frontend/src/lib/api/cohorts.test.ts | 214 +++++++++++++++++++++++++++ 1 file changed, 214 insertions(+) create mode 100644 frontend/src/lib/api/cohorts.test.ts diff --git a/frontend/src/lib/api/cohorts.test.ts b/frontend/src/lib/api/cohorts.test.ts new file mode 100644 index 0000000..42740ef --- /dev/null +++ b/frontend/src/lib/api/cohorts.test.ts @@ -0,0 +1,214 @@ +import { http, HttpResponse } from "msw"; +import { describe, expect, it, vi } from "vitest"; + +import { mockCohorts, mockMetadata, TEST_API_URL } from "@/test/mocks/handlers"; +import { server } from "@/test/mocks/server"; + +import { ApiError } from "./client"; +import { fetchCohorts, fetchMetadata, type Metadata } from "./cohorts"; + +describe.each([ + { + name: "fetchCohorts", + fetchData: fetchCohorts, + path: "/cohorts/", + expected: mockCohorts, + emptyResponse: [], + }, + { + name: "fetchMetadata", + fetchData: fetchMetadata, + path: "/cohorts/metadata", + expected: mockMetadata, + emptyResponse: {}, + }, +])("$name", ({ fetchData, path, expected, emptyResponse }) => { + it("retrieves data from the correct endpoint", async () => { + const fetch = vi.spyOn(globalThis, "fetch"); + + await expect(fetchData()).resolves.toEqual(expected); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}${path}`, + expect.objectContaining({ + method: "GET", + }), + ); + }); + + it("handles empty datasets", async () => { + server.use( + http.get(`${TEST_API_URL}${path}`, () => { + return HttpResponse.json(emptyResponse); + }), + ); + + await expect(fetchData()).resolves.toEqual(emptyResponse); + }); + + it("propagates API errors", async () => { + server.use( + http.get(`${TEST_API_URL}${path}`, () => { + return HttpResponse.json( + { detail: "Cohort data unavailable" }, + { status: 503 }, + ); + }), + ); + + const request = fetchData(); + + await expect(request).rejects.toBeInstanceOf(ApiError); + + await expect(request).rejects.toMatchObject({ + name: "ApiError", + status: 503, + message: "Cohort data unavailable", + }); + }); + + it("forwards the abort signal", async () => { + const controller = new AbortController(); + const fetch = vi.spyOn(globalThis, "fetch"); + + await expect(fetchData(controller.signal)).resolves.toEqual(expected); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}${path}`, + expect.objectContaining({ + method: "GET", + signal: controller.signal, + }), + ); + }); +}); + +describe("fetchCohorts response handling", () => { + it("preserves cohort names and backend ordering", async () => { + const cohorts = [ + "Study B", + "Study A", + "Study (Extended)", + "München & Partners", + ]; + + server.use( + http.get(`${TEST_API_URL}/cohorts/`, () => { + return HttpResponse.json(cohorts); + }), + ); + + await expect(fetchCohorts()).resolves.toEqual(cohorts); + }); +}); + +describe("fetchMetadata response handling", () => { + it("preserves metadata indexed by cohort name", async () => { + const metadata = await fetchMetadata(); + + expect(Object.keys(metadata).toSorted()).toEqual(["Study A", "Study B"]); + + expect(metadata["Study A"]).toEqual(mockMetadata["Study A"]); + + expect(metadata["Study B"]).toEqual(mockMetadata["Study B"]); + }); + + it("preserves nullable metadata fields", async () => { + const metadata = { + "Incomplete study": { + participants: null, + controlParticipants: null, + prodromalParticipants: null, + pdParticipants: null, + longitudinalParticipants: null, + longitudinalDataAvailable: false, + followUpInterval: null, + location: null, + doi: null, + link: null, + color: "#123456", + }, + } satisfies Metadata; + + server.use( + http.get(`${TEST_API_URL}/cohorts/metadata`, () => { + return HttpResponse.json(metadata); + }), + ); + + await expect(fetchMetadata()).resolves.toEqual(metadata); + }); + + it("preserves zero participant counts", async () => { + const metadata = { + "Empty study": { + participants: 0, + controlParticipants: 0, + prodromalParticipants: 0, + pdParticipants: 0, + longitudinalParticipants: 0, + longitudinalDataAvailable: false, + followUpInterval: null, + location: "Germany", + doi: null, + link: null, + color: "#654321", + }, + } satisfies Metadata; + + server.use( + http.get(`${TEST_API_URL}/cohorts/metadata`, () => { + return HttpResponse.json(metadata); + }), + ); + + await expect(fetchMetadata()).resolves.toEqual(metadata); + }); + + it("preserves metadata for cohort names containing special characters", async () => { + const metadata = { + "Study A & B (München)": { + ...mockMetadata["Study A"], + }, + "Study / Extended": { + ...mockMetadata["Study B"], + }, + } satisfies Metadata; + + server.use( + http.get(`${TEST_API_URL}/cohorts/metadata`, () => { + return HttpResponse.json(metadata); + }), + ); + + await expect(fetchMetadata()).resolves.toEqual(metadata); + }); + + it("preserves longitudinal availability independently of participant counts", async () => { + const metadata = { + "Study A": { + ...mockMetadata["Study A"], + longitudinalParticipants: null, + longitudinalDataAvailable: true, + }, + "Study B": { + ...mockMetadata["Study B"], + longitudinalParticipants: 40, + longitudinalDataAvailable: false, + }, + } satisfies Metadata; + + server.use( + http.get(`${TEST_API_URL}/cohorts/metadata`, () => { + return HttpResponse.json(metadata); + }), + ); + + const result = await fetchMetadata(); + + expect(result).toEqual(metadata); + + expect(result["Study A"].longitudinalDataAvailable).toBe(true); + expect(result["Study B"].longitudinalDataAvailable).toBe(false); + }); +}); From 042f86c899b3e3c7bb86c9cfe02d540da2194015 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:51:21 +0100 Subject: [PATCH 022/102] test(frontend): add biomarker API tests --- frontend/src/features/biomarkers/api.test.ts | 278 +++++++++++++++++++ 1 file changed, 278 insertions(+) create mode 100644 frontend/src/features/biomarkers/api.test.ts diff --git a/frontend/src/features/biomarkers/api.test.ts b/frontend/src/features/biomarkers/api.test.ts new file mode 100644 index 0000000..48e5a93 --- /dev/null +++ b/frontend/src/features/biomarkers/api.test.ts @@ -0,0 +1,278 @@ +import { http, HttpResponse } from "msw"; +import { describe, expect, it, vi } from "vitest"; + +import { ApiError } from "@/lib/api/client"; +import { TEST_API_URL } from "@/test/mocks/handlers"; +import { server } from "@/test/mocks/server"; + +import { + fetchBiomarkers, + fetchBiomarkerCohorts, + fetchBiomarkerDiagnoses, + fetchBiomarkerMeasurements, +} from "./api"; + +const MEASUREMENTS_PATH = "/biomarkers/cohorts/:cohort/diagnoses/:diagnosis"; + +const measurementRequest = { + biomarker: "Age", + cohort: "Study A", + diagnosis: "PD", +}; + +describe.each([ + { + name: "fetchBiomarkers", + fetchData: fetchBiomarkers, + path: "/biomarkers/", + handlerPath: "/biomarkers/", + expected: ["Age", "Motor score"], + }, + { + name: "fetchBiomarkerCohorts", + fetchData: (signal?: AbortSignal) => fetchBiomarkerCohorts("Age", signal), + path: "/biomarkers/cohorts?biomarker=Age", + handlerPath: "/biomarkers/cohorts", + expected: ["Study A", "Study B"], + }, + { + name: "fetchBiomarkerDiagnoses", + fetchData: (signal?: AbortSignal) => fetchBiomarkerDiagnoses("Age", signal), + path: "/biomarkers/diagnoses?biomarker=Age", + handlerPath: "/biomarkers/diagnoses", + expected: [ + "Study A (HC Group)", + "Study A (PD Group)", + "Study A (Complete)", + "Study B (PD Group)", + ], + }, + { + name: "fetchBiomarkerMeasurements", + fetchData: (signal?: AbortSignal) => + fetchBiomarkerMeasurements(measurementRequest, signal), + path: "/biomarkers/cohorts/Study%20A/diagnoses/PD?biomarker=Age", + handlerPath: MEASUREMENTS_PATH, + expected: [65, 70, 75], + }, +])("$name", ({ fetchData, path, handlerPath, expected }) => { + it("retrieves data from the correct endpoint", async () => { + const fetch = vi.spyOn(globalThis, "fetch"); + + await expect(fetchData()).resolves.toEqual(expected); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}${path}`, + expect.objectContaining({ + method: "GET", + }), + ); + }); + + it("handles empty datasets", async () => { + server.use( + http.get(`${TEST_API_URL}${handlerPath}`, () => { + return HttpResponse.json([]); + }), + ); + + await expect(fetchData()).resolves.toEqual([]); + }); + + it("propagates API errors", async () => { + server.use( + http.get(`${TEST_API_URL}${handlerPath}`, () => { + return HttpResponse.json( + { detail: "Biomarker data unavailable" }, + { status: 503 }, + ); + }), + ); + + const request = fetchData(); + + await expect(request).rejects.toBeInstanceOf(ApiError); + + await expect(request).rejects.toMatchObject({ + name: "ApiError", + status: 503, + message: "Biomarker data unavailable", + }); + }); + + it("forwards the abort signal", async () => { + const controller = new AbortController(); + const fetch = vi.spyOn(globalThis, "fetch"); + + await expect(fetchData(controller.signal)).resolves.toEqual(expected); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}${path}`, + expect.objectContaining({ + method: "GET", + signal: controller.signal, + }), + ); + }); +}); + +describe("biomarker cohort and diagnosis filtering", () => { + it("retrieves options for the requested biomarker", async () => { + await expect(fetchBiomarkerCohorts("Motor score")).resolves.toEqual([ + "Study A", + ]); + + await expect(fetchBiomarkerDiagnoses("Motor score")).resolves.toEqual([ + "Study A (PD Group)", + ]); + }); + + it("returns no options for an unknown biomarker", async () => { + await expect(fetchBiomarkerCohorts("Unknown biomarker")).resolves.toEqual( + [], + ); + + await expect(fetchBiomarkerDiagnoses("Unknown biomarker")).resolves.toEqual( + [], + ); + }); +}); + +describe("biomarker measurement filtering", () => { + it.each([ + { + biomarker: "Age", + cohort: "Study A", + diagnosis: "HC", + expected: [50, 55, 60], + }, + { + biomarker: "Age", + cohort: "Study A", + diagnosis: "Complete", + expected: [50, 55, 60, 65, 70, 75], + }, + { + biomarker: "Age", + cohort: "Study B", + diagnosis: "PD", + expected: [60, 65, 70], + }, + { + biomarker: "Motor score", + cohort: "Study A", + diagnosis: "PD", + expected: [10, 20, 30], + }, + { + biomarker: "Age", + cohort: "Study B", + diagnosis: "HC", + expected: [], + }, + { + biomarker: "Unknown biomarker", + cohort: "Study A", + diagnosis: "PD", + expected: [], + }, + { + biomarker: "Age", + cohort: "Unknown study", + diagnosis: "PD", + expected: [], + }, + ])( + "retrieves $biomarker measurements for $cohort ($diagnosis)", + async ({ biomarker, cohort, diagnosis, expected }) => { + await expect( + fetchBiomarkerMeasurements({ + biomarker, + cohort, + diagnosis, + }), + ).resolves.toEqual(expected); + }, + ); + + it("preserves negative, zero, fractional and repeated measurements", async () => { + const measurements = [-1.25, 0, 2.5, 2.5, 10.75]; + + server.use( + http.get(`${TEST_API_URL}${MEASUREMENTS_PATH}`, () => { + return HttpResponse.json(measurements); + }), + ); + + await expect( + fetchBiomarkerMeasurements(measurementRequest), + ).resolves.toEqual(measurements); + }); +}); + +describe("biomarker URL encoding", () => { + const biomarker = "α-synuclein + A/B (%)"; + + const encodedBiomarker = "%CE%B1-synuclein+%2B+A%2FB+%28%25%29"; + + it.each([ + { + fetchData: fetchBiomarkerCohorts, + path: "/biomarkers/cohorts", + expected: ["Study A"], + }, + { + fetchData: fetchBiomarkerDiagnoses, + path: "/biomarkers/diagnoses", + expected: ["Study A (PD Group)"], + }, + ])( + "encodes biomarker query parameters for $path", + async ({ fetchData, path, expected }) => { + const fetch = vi.spyOn(globalThis, "fetch"); + + server.use( + http.get(`${TEST_API_URL}${path}`, () => { + return HttpResponse.json(expected); + }), + ); + + await expect(fetchData(biomarker)).resolves.toEqual(expected); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}${path}?biomarker=${encodedBiomarker}`, + expect.objectContaining({ + method: "GET", + }), + ); + }, + ); + + it("encodes cohort and diagnosis path segments independently", async () => { + const fetch = vi.spyOn(globalThis, "fetch"); + + server.use( + http.get(`${TEST_API_URL}${MEASUREMENTS_PATH}`, () => { + return HttpResponse.json([1.5, 2.5]); + }), + ); + + await expect( + fetchBiomarkerMeasurements({ + biomarker, + cohort: "Study A & B (München)", + diagnosis: "At risk + PD #1", + }), + ).resolves.toEqual([1.5, 2.5]); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}/biomarkers/cohorts/` + + "Study%20A%20%26%20B%20(M%C3%BCnchen)" + + "/diagnoses/At%20risk%20%2B%20PD%20%231" + + `?biomarker=${encodedBiomarker}`, + expect.objectContaining({ + method: "GET", + }), + ); + }); +}); From 659096e202e106e3dcd6c9fe8ae917b2ec15be98 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:52:51 +0100 Subject: [PATCH 023/102] test(frontend): add longitudinal API tests --- .../src/features/longitudinal/api.test.ts | 291 ++++++++++++++++++ 1 file changed, 291 insertions(+) create mode 100644 frontend/src/features/longitudinal/api.test.ts diff --git a/frontend/src/features/longitudinal/api.test.ts b/frontend/src/features/longitudinal/api.test.ts new file mode 100644 index 0000000..11dd96d --- /dev/null +++ b/frontend/src/features/longitudinal/api.test.ts @@ -0,0 +1,291 @@ +import { http, HttpResponse } from "msw"; +import { describe, expect, it, vi } from "vitest"; + +import { ApiError } from "@/lib/api/client"; +import { + mockLongitudinalData, + mockLongitudinalVariables, + TEST_API_URL, +} from "@/test/mocks/handlers"; +import { server } from "@/test/mocks/server"; + +import { + fetchLongitudinalData, + fetchLongitudinalDataForCohort, + fetchLongitudinalVariables, +} from "./api"; +import type { LongitudinalData } from "./types"; + +const VARIABLE_PATH = "/longitudinal/:variable"; +const COHORT_PATH = "/longitudinal/:variable/:cohort"; + +const studyAData = mockLongitudinalData.filter( + (row) => row.cohort === "Study A", +); + +describe.each([ + { + name: "fetchLongitudinalVariables", + fetchData: fetchLongitudinalVariables, + path: "/longitudinal/", + handlerPath: "/longitudinal/", + expected: mockLongitudinalVariables, + }, + { + name: "fetchLongitudinalData", + fetchData: (signal?: AbortSignal) => fetchLongitudinalData("Age", signal), + path: "/longitudinal/Age", + handlerPath: VARIABLE_PATH, + expected: mockLongitudinalData, + }, + { + name: "fetchLongitudinalDataForCohort", + fetchData: (signal?: AbortSignal) => + fetchLongitudinalDataForCohort("Age", "Study A", signal), + path: "/longitudinal/Age/Study%20A", + handlerPath: COHORT_PATH, + expected: studyAData, + }, +])("$name", ({ fetchData, path, handlerPath, expected }) => { + it("retrieves data from the correct endpoint", async () => { + const fetch = vi.spyOn(globalThis, "fetch"); + + await expect(fetchData()).resolves.toEqual(expected); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}${path}`, + expect.objectContaining({ + method: "GET", + }), + ); + }); + + it("handles empty datasets", async () => { + server.use( + http.get(`${TEST_API_URL}${handlerPath}`, () => { + return HttpResponse.json([]); + }), + ); + + await expect(fetchData()).resolves.toEqual([]); + }); + + it("propagates API errors", async () => { + server.use( + http.get(`${TEST_API_URL}${handlerPath}`, () => { + return HttpResponse.json( + { detail: "Longitudinal data unavailable" }, + { status: 503 }, + ); + }), + ); + + const request = fetchData(); + + await expect(request).rejects.toBeInstanceOf(ApiError); + + await expect(request).rejects.toMatchObject({ + name: "ApiError", + status: 503, + message: "Longitudinal data unavailable", + }); + }); + + it("forwards the abort signal", async () => { + const controller = new AbortController(); + const fetch = vi.spyOn(globalThis, "fetch"); + + await expect(fetchData(controller.signal)).resolves.toEqual(expected); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}${path}`, + expect.objectContaining({ + method: "GET", + signal: controller.signal, + }), + ); + }); +}); + +describe("longitudinal variable retrieval", () => { + it("preserves variable names and backend ordering", async () => { + const variables = [ + "Study Visit", + "UPDRS III - Total Score", + "Age", + "α-synuclein", + ]; + + server.use( + http.get(`${TEST_API_URL}/longitudinal/`, () => { + return HttpResponse.json(variables); + }), + ); + + await expect(fetchLongitudinalVariables()).resolves.toEqual(variables); + }); + + it("retrieves measurements for the Study Visit variable", async () => { + const fetch = vi.spyOn(globalThis, "fetch"); + + await expect(fetchLongitudinalData("Study Visit")).resolves.toEqual( + mockLongitudinalData, + ); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}/longitudinal/Study%20Visit`, + expect.objectContaining({ + method: "GET", + }), + ); + }); +}); + +describe("longitudinal measurement filtering", () => { + it("retrieves measurements for an individual cohort", async () => { + await expect( + fetchLongitudinalDataForCohort("Age", "Study B"), + ).resolves.toEqual([ + { + months: 0, + cohort: "Study B", + patientCount: 40, + totalPatientCount: 50, + }, + { + months: 6, + cohort: "Study B", + patientCount: 30, + totalPatientCount: 50, + }, + ]); + }); + + it("returns no measurements for an unknown variable", async () => { + await expect(fetchLongitudinalData("Unknown variable")).resolves.toEqual( + [], + ); + }); + + it("returns no measurements for an unknown cohort", async () => { + await expect( + fetchLongitudinalDataForCohort("Age", "Unknown study"), + ).resolves.toEqual([]); + }); + + it("returns no cohort measurements for an unknown variable", async () => { + await expect( + fetchLongitudinalDataForCohort("Unknown variable", "Study A"), + ).resolves.toEqual([]); + }); +}); + +describe.each([ + { + name: "fetchLongitudinalData", + fetchData: () => fetchLongitudinalData("Age"), + handlerPath: VARIABLE_PATH, + }, + { + name: "fetchLongitudinalDataForCohort", + fetchData: () => fetchLongitudinalDataForCohort("Age", "Study A"), + handlerPath: COHORT_PATH, + }, +])("$name measurement preservation", ({ fetchData, handlerPath }) => { + it("preserves visit times, participant counts and response ordering", async () => { + const measurements = [ + { + months: 12, + cohort: "Study A", + patientCount: 0, + totalPatientCount: 100, + }, + { + months: 0, + cohort: "Study A", + patientCount: 100, + totalPatientCount: 100, + }, + { + months: 1.5, + cohort: "Study A", + patientCount: 75, + totalPatientCount: 100, + }, + { + months: 6, + cohort: "Study A", + patientCount: 120, + totalPatientCount: 100, + }, + ] satisfies LongitudinalData[]; + + server.use( + http.get(`${TEST_API_URL}${handlerPath}`, () => { + return HttpResponse.json(measurements); + }), + ); + + await expect(fetchData()).resolves.toEqual(measurements); + }); +}); + +describe("longitudinal URL encoding", () => { + const variable = "UPDRS III + α (%) #1"; + + const encodedVariable = "UPDRS%20III%20%2B%20%CE%B1%20(%25)%20%231"; + + it("encodes the variable path segment", async () => { + const fetch = vi.spyOn(globalThis, "fetch"); + + server.use( + http.get(`${TEST_API_URL}${VARIABLE_PATH}`, () => { + return HttpResponse.json(mockLongitudinalData); + }), + ); + + await expect(fetchLongitudinalData(variable)).resolves.toEqual( + mockLongitudinalData, + ); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}/longitudinal/${encodedVariable}`, + expect.objectContaining({ + method: "GET", + }), + ); + }); + + it("encodes variable and cohort path segments independently", async () => { + const fetch = vi.spyOn(globalThis, "fetch"); + + const cohort = "Study A & B (München)"; + + const measurements = [ + { + months: 0, + cohort, + patientCount: 80, + totalPatientCount: 100, + }, + ] satisfies LongitudinalData[]; + + server.use( + http.get(`${TEST_API_URL}${COHORT_PATH}`, () => { + return HttpResponse.json(measurements); + }), + ); + + await expect( + fetchLongitudinalDataForCohort(variable, cohort), + ).resolves.toEqual(measurements); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}/longitudinal/${encodedVariable}/` + + "Study%20A%20%26%20B%20(M%C3%BCnchen)", + expect.objectContaining({ + method: "GET", + }), + ); + }); +}); From d9091687e74e24c434950ea9eae1c409dd2da61e Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 17:58:07 +0100 Subject: [PATCH 024/102] refactor(frontend): simplify redundant API tests --- frontend/src/features/biomarkers/api.test.ts | 266 ++-------------- .../src/features/longitudinal/api.test.ts | 297 +++--------------- frontend/src/lib/api/cdm.test.ts | 65 +--- frontend/src/lib/api/cohorts.test.ts | 205 ++---------- 4 files changed, 103 insertions(+), 730 deletions(-) diff --git a/frontend/src/features/biomarkers/api.test.ts b/frontend/src/features/biomarkers/api.test.ts index 48e5a93..56b49f1 100644 --- a/frontend/src/features/biomarkers/api.test.ts +++ b/frontend/src/features/biomarkers/api.test.ts @@ -1,7 +1,6 @@ import { http, HttpResponse } from "msw"; -import { describe, expect, it, vi } from "vitest"; +import { expect, it, vi } from "vitest"; -import { ApiError } from "@/lib/api/client"; import { TEST_API_URL } from "@/test/mocks/handlers"; import { server } from "@/test/mocks/server"; @@ -12,15 +11,10 @@ import { fetchBiomarkerMeasurements, } from "./api"; -const MEASUREMENTS_PATH = "/biomarkers/cohorts/:cohort/diagnoses/:diagnosis"; +const biomarker = "α-synuclein + A/B (%)"; +const query = "biomarker=%CE%B1-synuclein+%2B+A%2FB+%28%25%29"; -const measurementRequest = { - biomarker: "Age", - cohort: "Study A", - diagnosis: "PD", -}; - -describe.each([ +it.each([ { name: "fetchBiomarkers", fetchData: fetchBiomarkers, @@ -30,80 +24,49 @@ describe.each([ }, { name: "fetchBiomarkerCohorts", - fetchData: (signal?: AbortSignal) => fetchBiomarkerCohorts("Age", signal), - path: "/biomarkers/cohorts?biomarker=Age", + fetchData: (signal: AbortSignal) => + fetchBiomarkerCohorts(biomarker, signal), + path: `/biomarkers/cohorts?${query}`, handlerPath: "/biomarkers/cohorts", expected: ["Study A", "Study B"], }, { name: "fetchBiomarkerDiagnoses", - fetchData: (signal?: AbortSignal) => fetchBiomarkerDiagnoses("Age", signal), - path: "/biomarkers/diagnoses?biomarker=Age", + fetchData: (signal: AbortSignal) => + fetchBiomarkerDiagnoses(biomarker, signal), + path: `/biomarkers/diagnoses?${query}`, handlerPath: "/biomarkers/diagnoses", - expected: [ - "Study A (HC Group)", - "Study A (PD Group)", - "Study A (Complete)", - "Study B (PD Group)", - ], + expected: ["Study A (PD Group)", "Study A (Complete)"], }, { name: "fetchBiomarkerMeasurements", - fetchData: (signal?: AbortSignal) => - fetchBiomarkerMeasurements(measurementRequest, signal), - path: "/biomarkers/cohorts/Study%20A/diagnoses/PD?biomarker=Age", - handlerPath: MEASUREMENTS_PATH, - expected: [65, 70, 75], + fetchData: (signal: AbortSignal) => + fetchBiomarkerMeasurements( + { + biomarker, + cohort: "Study A & B (München)", + diagnosis: "At risk + PD #1", + }, + signal, + ), + path: + "/biomarkers/cohorts/Study%20A%20%26%20B%20(M%C3%BCnchen)" + + `/diagnoses/At%20risk%20%2B%20PD%20%231?${query}`, + handlerPath: "/biomarkers/cohorts/:cohort/diagnoses/:diagnosis", + expected: [-1.25, 0, 2.5, 2.5, 10.75], }, -])("$name", ({ fetchData, path, handlerPath, expected }) => { - it("retrieves data from the correct endpoint", async () => { +])( + "$name retrieves data with encoded parameters", + async ({ fetchData, path, handlerPath, expected }) => { + const controller = new AbortController(); const fetch = vi.spyOn(globalThis, "fetch"); - await expect(fetchData()).resolves.toEqual(expected); - - expect(fetch).toHaveBeenCalledExactlyOnceWith( - `${TEST_API_URL}${path}`, - expect.objectContaining({ - method: "GET", - }), - ); - }); - - it("handles empty datasets", async () => { server.use( - http.get(`${TEST_API_URL}${handlerPath}`, () => { - return HttpResponse.json([]); - }), + http.get(`${TEST_API_URL}${handlerPath}`, () => + HttpResponse.json(expected), + ), ); - await expect(fetchData()).resolves.toEqual([]); - }); - - it("propagates API errors", async () => { - server.use( - http.get(`${TEST_API_URL}${handlerPath}`, () => { - return HttpResponse.json( - { detail: "Biomarker data unavailable" }, - { status: 503 }, - ); - }), - ); - - const request = fetchData(); - - await expect(request).rejects.toBeInstanceOf(ApiError); - - await expect(request).rejects.toMatchObject({ - name: "ApiError", - status: 503, - message: "Biomarker data unavailable", - }); - }); - - it("forwards the abort signal", async () => { - const controller = new AbortController(); - const fetch = vi.spyOn(globalThis, "fetch"); - await expect(fetchData(controller.signal)).resolves.toEqual(expected); expect(fetch).toHaveBeenCalledExactlyOnceWith( @@ -113,166 +76,5 @@ describe.each([ signal: controller.signal, }), ); - }); -}); - -describe("biomarker cohort and diagnosis filtering", () => { - it("retrieves options for the requested biomarker", async () => { - await expect(fetchBiomarkerCohorts("Motor score")).resolves.toEqual([ - "Study A", - ]); - - await expect(fetchBiomarkerDiagnoses("Motor score")).resolves.toEqual([ - "Study A (PD Group)", - ]); - }); - - it("returns no options for an unknown biomarker", async () => { - await expect(fetchBiomarkerCohorts("Unknown biomarker")).resolves.toEqual( - [], - ); - - await expect(fetchBiomarkerDiagnoses("Unknown biomarker")).resolves.toEqual( - [], - ); - }); -}); - -describe("biomarker measurement filtering", () => { - it.each([ - { - biomarker: "Age", - cohort: "Study A", - diagnosis: "HC", - expected: [50, 55, 60], - }, - { - biomarker: "Age", - cohort: "Study A", - diagnosis: "Complete", - expected: [50, 55, 60, 65, 70, 75], - }, - { - biomarker: "Age", - cohort: "Study B", - diagnosis: "PD", - expected: [60, 65, 70], - }, - { - biomarker: "Motor score", - cohort: "Study A", - diagnosis: "PD", - expected: [10, 20, 30], - }, - { - biomarker: "Age", - cohort: "Study B", - diagnosis: "HC", - expected: [], - }, - { - biomarker: "Unknown biomarker", - cohort: "Study A", - diagnosis: "PD", - expected: [], - }, - { - biomarker: "Age", - cohort: "Unknown study", - diagnosis: "PD", - expected: [], - }, - ])( - "retrieves $biomarker measurements for $cohort ($diagnosis)", - async ({ biomarker, cohort, diagnosis, expected }) => { - await expect( - fetchBiomarkerMeasurements({ - biomarker, - cohort, - diagnosis, - }), - ).resolves.toEqual(expected); - }, - ); - - it("preserves negative, zero, fractional and repeated measurements", async () => { - const measurements = [-1.25, 0, 2.5, 2.5, 10.75]; - - server.use( - http.get(`${TEST_API_URL}${MEASUREMENTS_PATH}`, () => { - return HttpResponse.json(measurements); - }), - ); - - await expect( - fetchBiomarkerMeasurements(measurementRequest), - ).resolves.toEqual(measurements); - }); -}); - -describe("biomarker URL encoding", () => { - const biomarker = "α-synuclein + A/B (%)"; - - const encodedBiomarker = "%CE%B1-synuclein+%2B+A%2FB+%28%25%29"; - - it.each([ - { - fetchData: fetchBiomarkerCohorts, - path: "/biomarkers/cohorts", - expected: ["Study A"], - }, - { - fetchData: fetchBiomarkerDiagnoses, - path: "/biomarkers/diagnoses", - expected: ["Study A (PD Group)"], - }, - ])( - "encodes biomarker query parameters for $path", - async ({ fetchData, path, expected }) => { - const fetch = vi.spyOn(globalThis, "fetch"); - - server.use( - http.get(`${TEST_API_URL}${path}`, () => { - return HttpResponse.json(expected); - }), - ); - - await expect(fetchData(biomarker)).resolves.toEqual(expected); - - expect(fetch).toHaveBeenCalledExactlyOnceWith( - `${TEST_API_URL}${path}?biomarker=${encodedBiomarker}`, - expect.objectContaining({ - method: "GET", - }), - ); - }, - ); - - it("encodes cohort and diagnosis path segments independently", async () => { - const fetch = vi.spyOn(globalThis, "fetch"); - - server.use( - http.get(`${TEST_API_URL}${MEASUREMENTS_PATH}`, () => { - return HttpResponse.json([1.5, 2.5]); - }), - ); - - await expect( - fetchBiomarkerMeasurements({ - biomarker, - cohort: "Study A & B (München)", - diagnosis: "At risk + PD #1", - }), - ).resolves.toEqual([1.5, 2.5]); - - expect(fetch).toHaveBeenCalledExactlyOnceWith( - `${TEST_API_URL}/biomarkers/cohorts/` + - "Study%20A%20%26%20B%20(M%C3%BCnchen)" + - "/diagnoses/At%20risk%20%2B%20PD%20%231" + - `?biomarker=${encodedBiomarker}`, - expect.objectContaining({ - method: "GET", - }), - ); - }); -}); + }, +); diff --git a/frontend/src/features/longitudinal/api.test.ts b/frontend/src/features/longitudinal/api.test.ts index 11dd96d..10ff164 100644 --- a/frontend/src/features/longitudinal/api.test.ts +++ b/frontend/src/features/longitudinal/api.test.ts @@ -1,12 +1,7 @@ import { http, HttpResponse } from "msw"; -import { describe, expect, it, vi } from "vitest"; +import { expect, it, vi } from "vitest"; -import { ApiError } from "@/lib/api/client"; -import { - mockLongitudinalData, - mockLongitudinalVariables, - TEST_API_URL, -} from "@/test/mocks/handlers"; +import { TEST_API_URL } from "@/test/mocks/handlers"; import { server } from "@/test/mocks/server"; import { @@ -16,85 +11,68 @@ import { } from "./api"; import type { LongitudinalData } from "./types"; -const VARIABLE_PATH = "/longitudinal/:variable"; -const COHORT_PATH = "/longitudinal/:variable/:cohort"; +const variable = "UPDRS III + α (%) #1"; +const cohort = "Study A & B (München)"; -const studyAData = mockLongitudinalData.filter( - (row) => row.cohort === "Study A", -); +const encodedVariable = "UPDRS%20III%20%2B%20%CE%B1%20(%25)%20%231"; +const encodedCohort = "Study%20A%20%26%20B%20(M%C3%BCnchen)"; + +const measurements = [ + { + months: 12, + cohort, + patientCount: 0, + totalPatientCount: 100, + }, + { + months: 1.5, + cohort, + patientCount: 75, + totalPatientCount: 100, + }, + { + months: 6, + cohort, + patientCount: 120, + totalPatientCount: 100, + }, +] satisfies LongitudinalData[]; -describe.each([ +it.each([ { name: "fetchLongitudinalVariables", fetchData: fetchLongitudinalVariables, path: "/longitudinal/", handlerPath: "/longitudinal/", - expected: mockLongitudinalVariables, + expected: ["Age", "Study Visit"], }, { name: "fetchLongitudinalData", - fetchData: (signal?: AbortSignal) => fetchLongitudinalData("Age", signal), - path: "/longitudinal/Age", - handlerPath: VARIABLE_PATH, - expected: mockLongitudinalData, + fetchData: (signal: AbortSignal) => fetchLongitudinalData(variable, signal), + path: `/longitudinal/${encodedVariable}`, + handlerPath: "/longitudinal/:variable", + expected: measurements, }, { name: "fetchLongitudinalDataForCohort", - fetchData: (signal?: AbortSignal) => - fetchLongitudinalDataForCohort("Age", "Study A", signal), - path: "/longitudinal/Age/Study%20A", - handlerPath: COHORT_PATH, - expected: studyAData, + fetchData: (signal: AbortSignal) => + fetchLongitudinalDataForCohort(variable, cohort, signal), + path: `/longitudinal/${encodedVariable}/${encodedCohort}`, + handlerPath: "/longitudinal/:variable/:cohort", + expected: measurements, }, -])("$name", ({ fetchData, path, handlerPath, expected }) => { - it("retrieves data from the correct endpoint", async () => { +])( + "$name retrieves data with encoded parameters", + async ({ fetchData, path, handlerPath, expected }) => { + const controller = new AbortController(); const fetch = vi.spyOn(globalThis, "fetch"); - await expect(fetchData()).resolves.toEqual(expected); - - expect(fetch).toHaveBeenCalledExactlyOnceWith( - `${TEST_API_URL}${path}`, - expect.objectContaining({ - method: "GET", - }), - ); - }); - - it("handles empty datasets", async () => { server.use( - http.get(`${TEST_API_URL}${handlerPath}`, () => { - return HttpResponse.json([]); - }), - ); - - await expect(fetchData()).resolves.toEqual([]); - }); - - it("propagates API errors", async () => { - server.use( - http.get(`${TEST_API_URL}${handlerPath}`, () => { - return HttpResponse.json( - { detail: "Longitudinal data unavailable" }, - { status: 503 }, - ); - }), + http.get(`${TEST_API_URL}${handlerPath}`, () => + HttpResponse.json(expected), + ), ); - const request = fetchData(); - - await expect(request).rejects.toBeInstanceOf(ApiError); - - await expect(request).rejects.toMatchObject({ - name: "ApiError", - status: 503, - message: "Longitudinal data unavailable", - }); - }); - - it("forwards the abort signal", async () => { - const controller = new AbortController(); - const fetch = vi.spyOn(globalThis, "fetch"); - await expect(fetchData(controller.signal)).resolves.toEqual(expected); expect(fetch).toHaveBeenCalledExactlyOnceWith( @@ -104,188 +82,5 @@ describe.each([ signal: controller.signal, }), ); - }); -}); - -describe("longitudinal variable retrieval", () => { - it("preserves variable names and backend ordering", async () => { - const variables = [ - "Study Visit", - "UPDRS III - Total Score", - "Age", - "α-synuclein", - ]; - - server.use( - http.get(`${TEST_API_URL}/longitudinal/`, () => { - return HttpResponse.json(variables); - }), - ); - - await expect(fetchLongitudinalVariables()).resolves.toEqual(variables); - }); - - it("retrieves measurements for the Study Visit variable", async () => { - const fetch = vi.spyOn(globalThis, "fetch"); - - await expect(fetchLongitudinalData("Study Visit")).resolves.toEqual( - mockLongitudinalData, - ); - - expect(fetch).toHaveBeenCalledExactlyOnceWith( - `${TEST_API_URL}/longitudinal/Study%20Visit`, - expect.objectContaining({ - method: "GET", - }), - ); - }); -}); - -describe("longitudinal measurement filtering", () => { - it("retrieves measurements for an individual cohort", async () => { - await expect( - fetchLongitudinalDataForCohort("Age", "Study B"), - ).resolves.toEqual([ - { - months: 0, - cohort: "Study B", - patientCount: 40, - totalPatientCount: 50, - }, - { - months: 6, - cohort: "Study B", - patientCount: 30, - totalPatientCount: 50, - }, - ]); - }); - - it("returns no measurements for an unknown variable", async () => { - await expect(fetchLongitudinalData("Unknown variable")).resolves.toEqual( - [], - ); - }); - - it("returns no measurements for an unknown cohort", async () => { - await expect( - fetchLongitudinalDataForCohort("Age", "Unknown study"), - ).resolves.toEqual([]); - }); - - it("returns no cohort measurements for an unknown variable", async () => { - await expect( - fetchLongitudinalDataForCohort("Unknown variable", "Study A"), - ).resolves.toEqual([]); - }); -}); - -describe.each([ - { - name: "fetchLongitudinalData", - fetchData: () => fetchLongitudinalData("Age"), - handlerPath: VARIABLE_PATH, - }, - { - name: "fetchLongitudinalDataForCohort", - fetchData: () => fetchLongitudinalDataForCohort("Age", "Study A"), - handlerPath: COHORT_PATH, }, -])("$name measurement preservation", ({ fetchData, handlerPath }) => { - it("preserves visit times, participant counts and response ordering", async () => { - const measurements = [ - { - months: 12, - cohort: "Study A", - patientCount: 0, - totalPatientCount: 100, - }, - { - months: 0, - cohort: "Study A", - patientCount: 100, - totalPatientCount: 100, - }, - { - months: 1.5, - cohort: "Study A", - patientCount: 75, - totalPatientCount: 100, - }, - { - months: 6, - cohort: "Study A", - patientCount: 120, - totalPatientCount: 100, - }, - ] satisfies LongitudinalData[]; - - server.use( - http.get(`${TEST_API_URL}${handlerPath}`, () => { - return HttpResponse.json(measurements); - }), - ); - - await expect(fetchData()).resolves.toEqual(measurements); - }); -}); - -describe("longitudinal URL encoding", () => { - const variable = "UPDRS III + α (%) #1"; - - const encodedVariable = "UPDRS%20III%20%2B%20%CE%B1%20(%25)%20%231"; - - it("encodes the variable path segment", async () => { - const fetch = vi.spyOn(globalThis, "fetch"); - - server.use( - http.get(`${TEST_API_URL}${VARIABLE_PATH}`, () => { - return HttpResponse.json(mockLongitudinalData); - }), - ); - - await expect(fetchLongitudinalData(variable)).resolves.toEqual( - mockLongitudinalData, - ); - - expect(fetch).toHaveBeenCalledExactlyOnceWith( - `${TEST_API_URL}/longitudinal/${encodedVariable}`, - expect.objectContaining({ - method: "GET", - }), - ); - }); - - it("encodes variable and cohort path segments independently", async () => { - const fetch = vi.spyOn(globalThis, "fetch"); - - const cohort = "Study A & B (München)"; - - const measurements = [ - { - months: 0, - cohort, - patientCount: 80, - totalPatientCount: 100, - }, - ] satisfies LongitudinalData[]; - - server.use( - http.get(`${TEST_API_URL}${COHORT_PATH}`, () => { - return HttpResponse.json(measurements); - }), - ); - - await expect( - fetchLongitudinalDataForCohort(variable, cohort), - ).resolves.toEqual(measurements); - - expect(fetch).toHaveBeenCalledExactlyOnceWith( - `${TEST_API_URL}/longitudinal/${encodedVariable}/` + - "Study%20A%20%26%20B%20(M%C3%BCnchen)", - expect.objectContaining({ - method: "GET", - }), - ); - }); -}); +); diff --git a/frontend/src/lib/api/cdm.test.ts b/frontend/src/lib/api/cdm.test.ts index 0816949..1661dea 100644 --- a/frontend/src/lib/api/cdm.test.ts +++ b/frontend/src/lib/api/cdm.test.ts @@ -1,83 +1,22 @@ -import { http, HttpResponse } from "msw"; import { describe, expect, it, vi } from "vitest"; import { TEST_API_URL } from "@/test/mocks/handlers"; -import { server } from "@/test/mocks/server"; import { fetchModalities, fetchVariables } from "./cdm"; -import { ApiError } from "./client"; describe.each([ { - name: "fetchVariables", fetchData: fetchVariables, path: "/cdm/variables", expected: ["Age", "Motor score"], - alternative: ["UPDRS III - Total Score", "Age", "α-synuclein"], }, { - name: "fetchModalities", fetchData: fetchModalities, path: "/cdm/modalities", expected: ["Clinical", "Demographics"], - alternative: ["Neuroimaging", "Clinical Assessments", "Demographics"], }, -])("$name", ({ fetchData, path, expected, alternative }) => { - it("retrieves data from the correct endpoint", async () => { - const fetch = vi.spyOn(globalThis, "fetch"); - - await expect(fetchData()).resolves.toEqual(expected); - - expect(fetch).toHaveBeenCalledExactlyOnceWith( - `${TEST_API_URL}${path}`, - expect.objectContaining({ - method: "GET", - }), - ); - }); - - it("preserves the values and ordering returned by the backend", async () => { - server.use( - http.get(`${TEST_API_URL}${path}`, () => { - return HttpResponse.json(alternative); - }), - ); - - await expect(fetchData()).resolves.toEqual(alternative); - }); - - it("handles empty datasets", async () => { - server.use( - http.get(`${TEST_API_URL}${path}`, () => { - return HttpResponse.json([]); - }), - ); - - await expect(fetchData()).resolves.toEqual([]); - }); - - it("propagates API errors", async () => { - server.use( - http.get(`${TEST_API_URL}${path}`, () => { - return HttpResponse.json( - { detail: "CDM data unavailable" }, - { status: 503 }, - ); - }), - ); - - const request = fetchData(); - - await expect(request).rejects.toBeInstanceOf(ApiError); - - await expect(request).rejects.toMatchObject({ - name: "ApiError", - status: 503, - message: "CDM data unavailable", - }); - }); - - it("forwards the abort signal", async () => { +])("$path", ({ fetchData, path, expected }) => { + it("retrieves data and forwards the abort signal", async () => { const controller = new AbortController(); const fetch = vi.spyOn(globalThis, "fetch"); diff --git a/frontend/src/lib/api/cohorts.test.ts b/frontend/src/lib/api/cohorts.test.ts index 42740ef..3fc1711 100644 --- a/frontend/src/lib/api/cohorts.test.ts +++ b/frontend/src/lib/api/cohorts.test.ts @@ -1,76 +1,43 @@ import { http, HttpResponse } from "msw"; -import { describe, expect, it, vi } from "vitest"; +import { expect, it, vi } from "vitest"; import { mockCohorts, mockMetadata, TEST_API_URL } from "@/test/mocks/handlers"; import { server } from "@/test/mocks/server"; -import { ApiError } from "./client"; import { fetchCohorts, fetchMetadata, type Metadata } from "./cohorts"; -describe.each([ +const metadata = { + ...mockMetadata, + "Study B": { + ...mockMetadata["Study B"], + participants: null, + controlParticipants: 0, + longitudinalParticipants: null, + longitudinalDataAvailable: true, + }, +} satisfies Metadata; + +it.each([ { - name: "fetchCohorts", fetchData: fetchCohorts, path: "/cohorts/", expected: mockCohorts, - emptyResponse: [], }, { - name: "fetchMetadata", fetchData: fetchMetadata, path: "/cohorts/metadata", - expected: mockMetadata, - emptyResponse: {}, + expected: metadata, }, -])("$name", ({ fetchData, path, expected, emptyResponse }) => { - it("retrieves data from the correct endpoint", async () => { +])( + "retrieves $path and forwards the abort signal", + async ({ fetchData, path, expected }) => { + const controller = new AbortController(); const fetch = vi.spyOn(globalThis, "fetch"); - await expect(fetchData()).resolves.toEqual(expected); - - expect(fetch).toHaveBeenCalledExactlyOnceWith( - `${TEST_API_URL}${path}`, - expect.objectContaining({ - method: "GET", - }), - ); - }); - - it("handles empty datasets", async () => { - server.use( - http.get(`${TEST_API_URL}${path}`, () => { - return HttpResponse.json(emptyResponse); - }), - ); - - await expect(fetchData()).resolves.toEqual(emptyResponse); - }); - - it("propagates API errors", async () => { server.use( - http.get(`${TEST_API_URL}${path}`, () => { - return HttpResponse.json( - { detail: "Cohort data unavailable" }, - { status: 503 }, - ); - }), + http.get(`${TEST_API_URL}${path}`, () => HttpResponse.json(expected)), ); - const request = fetchData(); - - await expect(request).rejects.toBeInstanceOf(ApiError); - - await expect(request).rejects.toMatchObject({ - name: "ApiError", - status: 503, - message: "Cohort data unavailable", - }); - }); - - it("forwards the abort signal", async () => { - const controller = new AbortController(); - const fetch = vi.spyOn(globalThis, "fetch"); - await expect(fetchData(controller.signal)).resolves.toEqual(expected); expect(fetch).toHaveBeenCalledExactlyOnceWith( @@ -80,135 +47,5 @@ describe.each([ signal: controller.signal, }), ); - }); -}); - -describe("fetchCohorts response handling", () => { - it("preserves cohort names and backend ordering", async () => { - const cohorts = [ - "Study B", - "Study A", - "Study (Extended)", - "München & Partners", - ]; - - server.use( - http.get(`${TEST_API_URL}/cohorts/`, () => { - return HttpResponse.json(cohorts); - }), - ); - - await expect(fetchCohorts()).resolves.toEqual(cohorts); - }); -}); - -describe("fetchMetadata response handling", () => { - it("preserves metadata indexed by cohort name", async () => { - const metadata = await fetchMetadata(); - - expect(Object.keys(metadata).toSorted()).toEqual(["Study A", "Study B"]); - - expect(metadata["Study A"]).toEqual(mockMetadata["Study A"]); - - expect(metadata["Study B"]).toEqual(mockMetadata["Study B"]); - }); - - it("preserves nullable metadata fields", async () => { - const metadata = { - "Incomplete study": { - participants: null, - controlParticipants: null, - prodromalParticipants: null, - pdParticipants: null, - longitudinalParticipants: null, - longitudinalDataAvailable: false, - followUpInterval: null, - location: null, - doi: null, - link: null, - color: "#123456", - }, - } satisfies Metadata; - - server.use( - http.get(`${TEST_API_URL}/cohorts/metadata`, () => { - return HttpResponse.json(metadata); - }), - ); - - await expect(fetchMetadata()).resolves.toEqual(metadata); - }); - - it("preserves zero participant counts", async () => { - const metadata = { - "Empty study": { - participants: 0, - controlParticipants: 0, - prodromalParticipants: 0, - pdParticipants: 0, - longitudinalParticipants: 0, - longitudinalDataAvailable: false, - followUpInterval: null, - location: "Germany", - doi: null, - link: null, - color: "#654321", - }, - } satisfies Metadata; - - server.use( - http.get(`${TEST_API_URL}/cohorts/metadata`, () => { - return HttpResponse.json(metadata); - }), - ); - - await expect(fetchMetadata()).resolves.toEqual(metadata); - }); - - it("preserves metadata for cohort names containing special characters", async () => { - const metadata = { - "Study A & B (München)": { - ...mockMetadata["Study A"], - }, - "Study / Extended": { - ...mockMetadata["Study B"], - }, - } satisfies Metadata; - - server.use( - http.get(`${TEST_API_URL}/cohorts/metadata`, () => { - return HttpResponse.json(metadata); - }), - ); - - await expect(fetchMetadata()).resolves.toEqual(metadata); - }); - - it("preserves longitudinal availability independently of participant counts", async () => { - const metadata = { - "Study A": { - ...mockMetadata["Study A"], - longitudinalParticipants: null, - longitudinalDataAvailable: true, - }, - "Study B": { - ...mockMetadata["Study B"], - longitudinalParticipants: 40, - longitudinalDataAvailable: false, - }, - } satisfies Metadata; - - server.use( - http.get(`${TEST_API_URL}/cohorts/metadata`, () => { - return HttpResponse.json(metadata); - }), - ); - - const result = await fetchMetadata(); - - expect(result).toEqual(metadata); - - expect(result["Study A"].longitudinalDataAvailable).toBe(true); - expect(result["Study B"].longitudinalDataAvailable).toBe(false); - }); -}); + }, +); From af998164e64b243fd98294c546a87e29784c0738 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 18:00:24 +0100 Subject: [PATCH 025/102] refactor(frontend): extract shared chart testing utility --- frontend/src/test/chart-utils.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 frontend/src/test/chart-utils.ts diff --git a/frontend/src/test/chart-utils.ts b/frontend/src/test/chart-utils.ts new file mode 100644 index 0000000..3a27067 --- /dev/null +++ b/frontend/src/test/chart-utils.ts @@ -0,0 +1,15 @@ +export function getFormatter(option: unknown) { + if ( + typeof option !== "object" || + option === null || + !("formatter" in option) || + typeof option.formatter !== "function" + ) { + throw new Error("Expected a callable chart formatter"); + } + + const formatter = option.formatter; + + return (params: unknown): unknown => + Reflect.apply(formatter, undefined, [params]); +} From 93e62972e841473a0440a237961eef6cf2669fae Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 18:01:30 +0100 Subject: [PATCH 026/102] refactor(frontend): simplify chart configuration tests --- .../biomarker-chart-options.test.ts | 430 ++++------------ .../longitudinal-chart-options.test.ts | 484 ++++-------------- .../components/race-chart-options.test.ts | 300 +++-------- 3 files changed, 258 insertions(+), 956 deletions(-) diff --git a/frontend/src/features/biomarkers/components/biomarker-chart-options.test.ts b/frontend/src/features/biomarkers/components/biomarker-chart-options.test.ts index 5608a79..a617155 100644 --- a/frontend/src/features/biomarkers/components/biomarker-chart-options.test.ts +++ b/frontend/src/features/biomarkers/components/biomarker-chart-options.test.ts @@ -1,413 +1,168 @@ import { describe, expect, it } from "vitest"; -import type { BiomarkerDistribution } from "../types"; +import { getFormatter } from "@/test/chart-utils"; +import type { BiomarkerDistribution } from "../types"; import { buildBiomarkerChartOptions, prepareBiomarkerDistributions, - type BiomarkerChartOption, } from "./biomarker-chart-options"; -function sample( - overrides: Partial = {}, +function distribution( + cohort: string, + values: readonly number[], + label = cohort, ): BiomarkerDistribution { - return { - label: "Study A (PD Group)", - cohort: "Study A", - diagnosis: "PD", - values: [1, 2, 3, 4, 5, 100], - ...overrides, - }; + return { cohort, diagnosis: "PD", label, values }; } -function getFormatter(option: unknown) { - if ( - typeof option !== "object" || - option === null || - !("formatter" in option) || - typeof option.formatter !== "function" - ) { - throw new Error("Expected a callable chart formatter"); - } - - const formatter = option.formatter; - - return (params: unknown): unknown => - Reflect.apply(formatter, undefined, [params]); -} - -function getAxisLabelFormatter(options: BiomarkerChartOption) { - const axis = options.xAxis; - - if (!axis || Array.isArray(axis)) { - throw new Error("Expected a single x-axis configuration"); - } - - return getFormatter(axis.axisLabel); -} +const distributions = [ + distribution("Study A", [1, 2, 3, 4, 5, 100]), + distribution("Study B", [-6, 0, 0, 0, 0, 0], ' & "PD"'), + distribution("Study C", [42]), +]; -function createTooltipGroups() { - return prepareBiomarkerDistributions([ - sample({ - label: ' & "PD"', - values: [0, 0, 0, 0, 0, 6], - }), - sample({ - label: "Study B (PD Group)", - cohort: "Study B", - values: [42], - }), - ]); -} +const groups = prepareBiomarkerDistributions(distributions, { + "Study A": "#123456", +}); describe("prepareBiomarkerDistributions", () => { - it("excludes invalid distributions and nonfinite measurements", () => { - const distributions = [ - sample({ - label: "Empty distribution", - values: [], - }), - sample({ - label: "Invalid distribution", - values: [NaN, Infinity, -Infinity], - }), - sample({ - label: "Valid distribution", - values: [3, NaN, 1, Infinity, 2], - }), - ]; - - const prepared = prepareBiomarkerDistributions(distributions); - - expect(prepared).toHaveLength(1); + it("excludes invalid distributions and measurements", () => { + const prepared = prepareBiomarkerDistributions([ + distribution("Empty", []), + distribution("Invalid", [NaN, Infinity]), + distribution("Valid", [3, NaN, 1, 2]), + ]); - expect(prepared[0]).toMatchObject({ - label: "Valid distribution", - stats: { - n: 3, - excludedCount: 2, - median: 2, - values: [1, 2, 3], + expect(prepared).toMatchObject([ + { + cohort: "Valid", + stats: { + n: 3, + excludedCount: 1, + values: [1, 2, 3], + median: 2, + }, }, - }); - - expect(distributions[2].values).toEqual([3, NaN, 1, Infinity, 2]); + ]); }); - it("uses metadata colors and consistent fallback colors", () => { - const distributions = [ - sample({ - cohort: "Study B", - label: "Study B (PD Group)", - }), - sample({ - cohort: "Study A", - label: "Study A (PD Group)", - }), - sample({ - cohort: "Study B", - diagnosis: "HC", - label: "Study B (HC Group)", - }), - ]; - - const prepared = prepareBiomarkerDistributions(distributions, { - "Study A": "#123456", - }); - - expect(prepared.map((group) => group.color)).toEqual([ - "#d97706", - "#123456", - "#d97706", - ]); + it("assigns consistent cohort colors independently of input order", () => { + const input = [distributions[1], distributions[0], distributions[1]]; - expect(prepared.map((group) => group.label)).toEqual([ - "Study B (PD Group)", - "Study A (PD Group)", - "Study B (HC Group)", - ]); + const colors = { "Study A": "#123456" }; - const reversed = prepareBiomarkerDistributions(distributions.toReversed(), { - "Study A": "#123456", - }); + expect( + prepareBiomarkerDistributions(input, colors).map((group) => group.color), + ).toEqual(["#d97706", "#123456", "#d97706"]); - expect(reversed.map((group) => group.color)).toEqual( - prepared.map((group) => group.color).toReversed(), - ); + expect( + prepareBiomarkerDistributions(input.toReversed(), colors).map( + (group) => group.color, + ), + ).toEqual(["#d97706", "#123456", "#d97706"]); }); - it("reuses palette colors when the number of cohorts exceeds the palette", () => { - const distributions = Array.from({ length: 9 }, (_, index) => - sample({ - cohort: `Study ${index + 1}`, - label: `Study ${index + 1} (PD Group)`, - }), + it("cycles the fallback palette", () => { + const prepared = prepareBiomarkerDistributions( + Array.from({ length: 9 }, (_, i) => distribution(`Study ${i}`, [1])), ); - const prepared = prepareBiomarkerDistributions(distributions); - - expect(prepared.map((group) => group.color)).toEqual([ - "#2563eb", - "#d97706", - "#059669", - "#9333ea", - "#dc2626", - "#0f766e", - "#4f46e5", - "#be185d", - "#2563eb", - ]); - }); - - it("returns no prepared distributions for empty input", () => { - expect(prepareBiomarkerDistributions([])).toEqual([]); + expect(new Set(prepared.map((group) => group.color)).size).toBe(8); + expect(prepared[8].color).toBe(prepared[0].color); }); }); describe("buildBiomarkerChartOptions", () => { - it("constructs boxplot and outlier scatter series", () => { - const groups = prepareBiomarkerDistributions( - [ - sample(), - sample({ - label: "Study B (PD Group)", - cohort: "Study B", - values: [-6, 0, 0, 0, 0, 0], - }), - sample({ - label: "Study C (PD Group)", - cohort: "Study C", - values: [10, 20, 30, 40], - }), - ], - { - "Study A": "#123456", - "Study B": "#654321", - "Study C": "#abcdef", - }, - ); - + it("constructs boxplots and outlier coordinates", () => { const options = buildBiomarkerChartOptions(groups); expect(options.series).toMatchObject([ { type: "boxplot", - name: "Distributions", data: [ - { - name: "Study A (PD Group)", - value: [1, 2, 3.5, 5, 5], - itemStyle: { - color: "#123456", - borderColor: "#123456", - }, - }, - { - name: "Study B (PD Group)", - value: [0, 0, 0, 0, 0], - itemStyle: { - color: "#654321", - borderColor: "#654321", - }, - }, - { - name: "Study C (PD Group)", - value: [10, 15, 25, 35, 40], - itemStyle: { - color: "#abcdef", - borderColor: "#abcdef", - }, - }, + { value: [1, 2, 3.5, 5, 5], itemStyle: { color: "#123456" } }, + { value: [0, 0, 0, 0, 0], itemStyle: { color: "#d97706" } }, + { value: [42, 42, 42, 42, 42] }, ], }, { type: "scatter", - name: "Outliers", - data: [ - { - name: "Study A (PD Group)", - value: [0, 100], - itemStyle: { - color: "#123456", - }, - }, - { - name: "Study B (PD Group)", - value: [1, -6], - itemStyle: { - color: "#654321", - }, - }, - ], + data: [{ value: [0, 100] }, { value: [1, -6] }], }, ]); expect(options.xAxis).toMatchObject({ - type: "category", - data: ["Study A (PD Group)", "Study B (PD Group)", "Study C (PD Group)"], - }); - - expect(options.yAxis).toMatchObject({ - type: "value", - scale: true, - name: "Measurement value", + data: distributions.map((group) => group.label), }); }); - it("constructs an empty chart with default accessibility information", () => { - const options = buildBiomarkerChartOptions([]); - - expect(options).toMatchObject({ - animation: false, - backgroundColor: "#ffffff", - aria: { - enabled: true, - label: { - description: - "Biomarker distributions. Boxplots showing medians, " + - "quartiles, whiskers, and statistical outliers.", - }, - }, - xAxis: { - data: [], - }, - series: [ - { - type: "boxplot", - data: [], - }, - { - type: "scatter", - data: [], - }, - ], + it("handles empty datasets", () => { + expect( + buildBiomarkerChartOptions(prepareBiomarkerDistributions([])), + ).toMatchObject({ + series: [{ data: [] }, { data: [] }], + xAxis: { data: [] }, }); }); it.each([ - { - compact: false, - left: 100, - right: 32, - bottom: 110, - rotation: 25, - limit: 22, - truncated: "ABCDEFGHIJKLMNOPQRS...", - }, - { - compact: true, - left: 80, - right: 20, - bottom: 90, - rotation: 35, - limit: 16, - truncated: "ABCDEFGHIJKLM...", - }, - ])( - "configures responsive chart options with compact=$compact", - ({ compact, left, right, bottom, rotation, limit, truncated }) => { - const options = buildBiomarkerChartOptions( - prepareBiomarkerDistributions([sample()]), - compact, - "Age distributions", - ); - - expect(options.grid).toMatchObject({ - left, - right, - top: 30, - bottom, - }); - - expect(options.xAxis).toMatchObject({ - axisLabel: { - rotate: rotation, - }, - }); - - expect(options.aria).toMatchObject({ - enabled: true, - label: { - description: - "Age distributions. Boxplots showing medians, " + - "quartiles, whiskers, and statistical outliers.", - }, - }); + { compact: false, limit: 22 }, + { compact: true, limit: 16 }, + ])("truncates axis labels with compact=$compact", ({ compact, limit }) => { + const options = buildBiomarkerChartOptions(groups, compact, "Age"); + + expect(options.aria).toMatchObject({ + enabled: true, + label: { + description: expect.stringContaining("Age"), + }, + }); - const formatter = getAxisLabelFormatter(options); + const axis = options.xAxis; - expect(formatter("Age")).toBe("Age"); + if (!axis || Array.isArray(axis)) { + throw new Error("Expected a single x-axis configuration"); + } - expect(formatter("A".repeat(limit))).toBe("A".repeat(limit)); + const format = getFormatter(axis.axisLabel); - expect(formatter("ABCDEFGHIJKLMNOPQRSTUVWXYZ")).toBe(truncated); - }, - ); + expect(format("A".repeat(limit))).toBe("A".repeat(limit)); + expect(format("A".repeat(limit + 1))).toBe(`${"A".repeat(limit - 3)}...`); + }); }); -describe("biomarker tooltip formatter", () => { - it("formats boxplot statistics and escapes the group label", () => { - const options = buildBiomarkerChartOptions(createTooltipGroups()); - const formatter = getFormatter(options.tooltip); +describe("biomarker tooltip", () => { + const format = getFormatter(buildBiomarkerChartOptions(groups).tooltip); - expect(formatter({ seriesIndex: 0, dataIndex: 0 })).toBe( + it("formats statistics and escapes group labels", () => { + expect(format({ seriesIndex: 0, dataIndex: 1 })).toBe( [ - "<Study A> & "PD"", + "<Study B> & "PD"", "Participants: 6", "Median: 0", "Q1: 0", "Q3: 0", "Whiskers: 0 - 0", - "Mean: 1", + "Mean: -1", "SD: 2.4495", "Outliers: 1", ].join("
"), ); }); - it("formats outlier measurements using the corresponding group index", () => { - const options = buildBiomarkerChartOptions(createTooltipGroups()); - const formatter = getFormatter(options.tooltip); - - expect( - formatter({ - seriesIndex: 1, - dataIndex: 0, - value: [0, 6], - }), - ).toBe( - [ - "<Study A> & "PD"", - "Measurement: 6", - "Outlier", - ].join("
"), + it("formats outliers and unavailable standard deviations", () => { + expect(format({ seriesIndex: 1, dataIndex: 0, value: [1, -6] })).toBe( + "<Study B> & "PD"" + + "
Measurement: -6
Outlier", ); - }); - - it("displays unavailable standard deviations for single observations", () => { - const options = buildBiomarkerChartOptions(createTooltipGroups()); - const formatter = getFormatter(options.tooltip); - expect(formatter({ seriesIndex: 0, dataIndex: 1 })).toBe( - [ - "Study B (PD Group)", - "Participants: 1", - "Median: 42", - "Q1: 42", - "Q3: 42", - "Whiskers: 42 - 42", - "Mean: 42", - "SD: N/R", - "Outliers: 0", - ].join("
"), - ); + expect(format({ seriesIndex: 0, dataIndex: 2 })).toContain("SD: N/R"); }); it.each([ null, - undefined, "invalid", - {}, { dataIndex: 0 }, { seriesIndex: 0 }, { seriesIndex: "0", dataIndex: 0 }, @@ -418,10 +173,7 @@ describe("biomarker tooltip formatter", () => { { seriesIndex: 1, dataIndex: 0, value: ["0", 6] }, { seriesIndex: 1, dataIndex: 0, value: [0, "6"] }, { seriesIndex: 1, dataIndex: 0, value: [99, 6] }, - ])("returns an empty tooltip for invalid parameters: %j", (params) => { - const options = buildBiomarkerChartOptions(createTooltipGroups()); - const formatter = getFormatter(options.tooltip); - - expect(formatter(params)).toBe(""); + ])("rejects invalid tooltip parameters: %j", (params) => { + expect(format(params)).toBe(""); }); }); diff --git a/frontend/src/features/longitudinal/components/longitudinal-chart-options.test.ts b/frontend/src/features/longitudinal/components/longitudinal-chart-options.test.ts index fa967d9..59c14cf 100644 --- a/frontend/src/features/longitudinal/components/longitudinal-chart-options.test.ts +++ b/frontend/src/features/longitudinal/components/longitudinal-chart-options.test.ts @@ -1,148 +1,76 @@ import { describe, expect, it } from "vitest"; -import type { RetentionSeries } from "../utils/retention"; +import { getFormatter } from "@/test/chart-utils"; +import type { RetentionPoint, RetentionSeries } from "../utils/retention"; import { buildLongitudinalChartOptions, getSeriesColor, - type LongitudinalChartOption, } from "./longitudinal-chart-options"; -const sampleSeries: RetentionSeries[] = [ +function point( + months: number, + retentionPercent: number | null, + patientCount: number, + totalPatientCount = 1500, +): RetentionPoint { + return { months, retentionPercent, patientCount, totalPatientCount }; +} + +const series: RetentionSeries[] = [ { - name: "Study A", + name: "", points: [ - { - months: 0, - retentionPercent: 100, - patientCount: 1500, - totalPatientCount: 1500, - }, - { - months: 6, - retentionPercent: 83.33333333333334, - patientCount: 1250, - totalPatientCount: 1500, - }, - { - months: 12, - retentionPercent: null, - patientCount: 1600, - totalPatientCount: 1500, - }, - { - months: 18, - retentionPercent: 0, - patientCount: 0, - totalPatientCount: 1500, - }, + point(0, 100, 1500), + point(6, 83.33333333333334, 1250), + point(12, null, 1600), + point(18, 0, 0), ], }, { name: "Study B", - points: [ - { - months: 6, - retentionPercent: 50, - patientCount: 50, - totalPatientCount: 100, - }, - { - months: 12, - retentionPercent: 20, - patientCount: 20, - totalPatientCount: 100, - }, - ], + points: [point(6, 50, 50, 100), point(12, 20, 20, 100)], }, ]; -function getTooltipFormatter(options: LongitudinalChartOption) { - const tooltip = options.tooltip; - - if ( - typeof tooltip !== "object" || - tooltip === null || - !("formatter" in tooltip) || - typeof tooltip.formatter !== "function" - ) { - throw new Error("Expected a callable tooltip formatter"); - } - - const formatter = tooltip.formatter; - - return (params: unknown): unknown => - Reflect.apply(formatter, undefined, [params]); -} - describe("getSeriesColor", () => { - it("prioritizes explicitly configured cohort colors", () => { - expect( - getSeriesColor("Study A", 0, { - "Study A": "#123456", - }), - ).toBe("#123456"); + it("prioritizes configured colors", () => { + expect(getSeriesColor("Study A", 0, { "Study A": "#123456" })).toBe( + "#123456", + ); }); it.each([ - { index: 0, expected: "#2563eb" }, - { index: 1, expected: "#d97706" }, - { index: 7, expected: "#4f46e5" }, - { index: 8, expected: "#2563eb" }, - { index: 9, expected: "#d97706" }, - ])("returns the palette color for index $index", ({ index, expected }) => { - expect(getSeriesColor("Unknown study", index, {})).toBe(expected); + { index: 0, color: "#2563eb" }, + { index: 7, color: "#4f46e5" }, + { index: 8, color: "#2563eb" }, + { index: -1, color: "#610030" }, + { index: NaN, color: "#610030" }, + ])("returns $color for index $index", ({ index, color }) => { + expect(getSeriesColor("Unknown", index, {})).toBe(color); }); - - it.each([-1, NaN, Infinity, 1.5])( - "returns the defensive fallback for invalid index %s", - (index) => { - expect(getSeriesColor("Unknown study", index, {})).toBe("#610030"); - }, - ); }); describe("buildLongitudinalChartOptions", () => { - it("constructs line series and preserves missing measurements", () => { - const options = buildLongitudinalChartOptions(sampleSeries, { - "Study A": "#123456", + it("preserves measurements without smoothing or connecting missing values", () => { + const options = buildLongitudinalChartOptions(series, { + "": "#123456", }); expect(options.series).toMatchObject([ { type: "line", - name: "Study A", + name: "", data: [ [0, 100], [6, 83.33333333333334], [12, null], [18, 0], ], - symbol: "circle", - symbolSize: 7, - showSymbol: true, smooth: false, connectNulls: false, - lineStyle: { - color: "#123456", - width: 2.5, - type: "solid", - }, - itemStyle: { - color: "#123456", - }, - emphasis: { - focus: "series", - }, - markLine: { - silent: true, - symbol: "none", - label: { - show: true, - formatter: "50% retention", - }, - data: [{ yAxis: 50 }], - }, + lineStyle: { color: "#123456" }, + markLine: { data: [{ yAxis: 50 }] }, }, { type: "line", @@ -151,318 +79,100 @@ describe("buildLongitudinalChartOptions", () => { [6, 50], [12, 20], ], - symbol: "rect", smooth: false, connectNulls: false, - lineStyle: { - color: "#d97706", - type: "dashed", - }, - itemStyle: { - color: "#d97706", - }, markLine: undefined, }, ]); - expect(options.yAxis).toMatchObject({ - type: "value", - min: 0, - max: 100, - interval: 20, - }); - - expect(options.xAxis).toMatchObject({ - type: "value", - min: 0, - }); + expect(options.yAxis).toMatchObject({ min: 0, max: 100 }); }); - it("constructs an empty chart with default accessibility information", () => { - const options = buildLongitudinalChartOptions([]); - - expect(options).toMatchObject({ - animation: false, - backgroundColor: "#ffffff", - aria: { - enabled: true, - label: { - description: - "Participant retention. Participant retention over months in study.", - }, - }, - series: [], - }); + it("handles empty datasets", () => { + expect(buildLongitudinalChartOptions([]).series).toEqual([]); }); - it("cycles symbols and line styles for multiple series", () => { - const series: RetentionSeries[] = Array.from({ length: 6 }, (_, index) => ({ - name: `Study ${index + 1}`, - points: [], - })); - - const options = buildLongitudinalChartOptions(series); + it("cycles symbols and line styles", () => { + const options = buildLongitudinalChartOptions( + Array.from({ length: 6 }, (_, index) => ({ + name: `Study ${index}`, + points: [], + })), + ); expect(options.series).toMatchObject([ - { - symbol: "circle", - lineStyle: { type: "solid" }, - }, - { - symbol: "rect", - lineStyle: { type: "dashed" }, - }, - { - symbol: "diamond", - lineStyle: { type: "dotted" }, - }, - { - symbol: "triangle", - lineStyle: { type: "solid" }, - }, - { - symbol: "roundRect", - lineStyle: { type: "dashed" }, - }, - { - symbol: "circle", - lineStyle: { type: "dotted" }, - }, + { symbol: "circle", lineStyle: { type: "solid" } }, + { symbol: "rect", lineStyle: { type: "dashed" } }, + { symbol: "diamond", lineStyle: { type: "dotted" } }, + { symbol: "triangle", lineStyle: { type: "solid" } }, + { symbol: "roundRect", lineStyle: { type: "dashed" } }, + { symbol: "circle", lineStyle: { type: "dotted" } }, ]); }); - it.each([ - { - compact: false, - trigger: "axis", - showLegend: true, - left: 16, - right: 20, - top: 24, - bottom: 90, - xAxisName: "Months in Study", - yAxisName: "Retention (%)", - splitNumber: 6, - }, - { - compact: true, - trigger: "item", - showLegend: false, - left: 8, - right: 8, - top: 12, - bottom: 55, - xAxisName: "Months", - yAxisName: "", - splitNumber: 4, - }, - ])( - "configures responsive chart options with compact=$compact", - ({ - compact, - trigger, - showLegend, - left, - right, - top, - bottom, - xAxisName, - yAxisName, - splitNumber, - }) => { - const options = buildLongitudinalChartOptions( - sampleSeries, - {}, - "Age availability", - compact, - ); - - expect(options.tooltip).toMatchObject({ - trigger, - confine: true, - renderMode: "html", - }); - - expect(options.legend).toMatchObject({ - show: showLegend, - type: "scroll", - }); - - expect(options.grid).toMatchObject({ - left, - right, - top, - bottom, - containLabel: true, - }); - - expect(options.xAxis).toMatchObject({ - name: xAxisName, - splitNumber, - }); - - expect(options.yAxis).toMatchObject({ - name: yAxisName, - axisLabel: { - formatter: "{value}%", - }, - }); - - expect(options.series).toMatchObject([ - { - markLine: { - label: { - show: !compact, - }, - data: [{ yAxis: 50 }], - }, - }, - { - markLine: undefined, - }, - ]); - - expect(options.aria).toMatchObject({ - enabled: true, - label: { - description: - "Age availability. Participant retention over months in study.", - }, - }); - }, - ); -}); - -describe("longitudinal tooltip formatter", () => { - it("formats participant counts and retention percentages", () => { - const options = buildLongitudinalChartOptions(sampleSeries); - const formatter = getTooltipFormatter(options); + it.each([false, true])("supports compact=%s", (compact) => { + const options = buildLongitudinalChartOptions(series, {}, "Age", compact); - const tooltip = formatter({ - seriesIndex: 0, - dataIndex: 1, + expect(options.tooltip).toMatchObject({ + trigger: compact ? "item" : "axis", }); - expect(tooltip).toContain("Study A"); - expect(tooltip).toContain("Month: 6"); - expect(tooltip).toContain("Retention: 83.3%"); - expect(tooltip).toMatch(/Participants: 1,250\s*\/ 1,500/); - }); - - it("escapes HTML characters in series names", () => { - const series: RetentionSeries[] = [ - { - ...sampleSeries[0], - name: ` & "PD" 'Group'`, - }, - ]; + expect(options.legend).toMatchObject({ show: !compact }); - const options = buildLongitudinalChartOptions(series); - const formatter = getTooltipFormatter(options); + expect(options.series).toMatchObject([ + { markLine: { label: { show: !compact } } }, + { markLine: undefined }, + ]); - const tooltip = formatter({ - seriesIndex: 0, - dataIndex: 0, + expect(options.aria).toMatchObject({ + enabled: true, + label: { + description: expect.stringContaining("Age"), + }, }); - - expect(tooltip).toContain( - "<Study A> & "PD" 'Group'", - ); - - expect(tooltip).not.toContain(""); }); +}); - it("displays unavailable retention as N/R", () => { - const options = buildLongitudinalChartOptions(sampleSeries); - const formatter = getTooltipFormatter(options); - - const tooltip = formatter({ - seriesIndex: 0, - dataIndex: 2, - }); +describe("longitudinal tooltip", () => { + const format = getFormatter(buildLongitudinalChartOptions(series).tooltip); - expect(tooltip).toContain("Month: 12"); - expect(tooltip).toContain("Retention: N/R"); - expect(tooltip).toMatch(/Participants: 1,600\s*\/ 1,500/); + it.each([ + { dataIndex: 1, expected: "83.3%" }, + { dataIndex: 2, expected: "N/R" }, + { dataIndex: 3, expected: "0.0%" }, + ])("formats retention as $expected", ({ dataIndex, expected }) => { + expect(format({ seriesIndex: 0, dataIndex })).toContain( + `Retention: ${expected}`, + ); }); - it("displays zero retention as a valid percentage", () => { - const options = buildLongitudinalChartOptions(sampleSeries); - const formatter = getTooltipFormatter(options); + it("formats participant counts and escapes cohort names", () => { + const tooltip = format({ seriesIndex: 0, dataIndex: 1 }); - const tooltip = formatter({ - seriesIndex: 0, - dataIndex: 3, - }); - - expect(tooltip).toContain("Retention: 0.0%"); - expect(tooltip).toMatch(/Participants: 0\s*\/ 1,500/); + expect(tooltip).toContain("<Study A>"); + expect(tooltip).toContain("Month: 6"); + expect(tooltip).toMatch(/Participants: 1,250\s*\/ 1,500/); }); - it("formats multiple series and ignores invalid tooltip entries", () => { - const options = buildLongitudinalChartOptions(sampleSeries); - const formatter = getTooltipFormatter(options); - - const first = { - seriesIndex: 0, - dataIndex: 1, - }; - - const second = { - seriesIndex: 1, - dataIndex: 0, - }; - - const tooltip = formatter([ - first, - null, - { seriesIndex: 99, dataIndex: 0 }, - { seriesIndex: 0, dataIndex: 99 }, - second, - "invalid", - ]); - - expect(tooltip).toBe([formatter(first), formatter(second)].join("")); + it("formats multiple series and ignores invalid entries", () => { + const first = { seriesIndex: 0, dataIndex: 1 }; + const second = { seriesIndex: 1, dataIndex: 0 }; - expect(tooltip).toContain("Study A"); - expect(tooltip).toContain("Study B"); - expect(tooltip).toContain("Retention: 83.3%"); - expect(tooltip).toContain("Retention: 50.0%"); + expect(format([first, null, second])).toBe( + [format(first), format(second)].join(""), + ); }); it.each([ - { params: null }, - { params: undefined }, - { params: "invalid" }, - { params: {} }, - { params: { dataIndex: 0 } }, - { params: { seriesIndex: 0 } }, - { params: { seriesIndex: "0", dataIndex: 0 } }, - { params: { seriesIndex: 0, dataIndex: "0" } }, - { params: { seriesIndex: 99, dataIndex: 0 } }, - { params: { seriesIndex: 0, dataIndex: 99 } }, - { params: { seriesIndex: -1, dataIndex: 0 } }, - { params: { seriesIndex: 0, dataIndex: -1 } }, - { params: [] }, - ])( - "returns an empty tooltip for invalid parameters: $params", - ({ params }) => { - const options = buildLongitudinalChartOptions(sampleSeries); - const formatter = getTooltipFormatter(options); - - expect(formatter(params)).toBe(""); - }, - ); - - it("returns an empty tooltip when no series exist", () => { - const options = buildLongitudinalChartOptions([]); - const formatter = getTooltipFormatter(options); - - expect( - formatter({ - seriesIndex: 0, - dataIndex: 0, - }), - ).toBe(""); + null, + "invalid", + { dataIndex: 0 }, + { seriesIndex: 0 }, + { seriesIndex: "0", dataIndex: 0 }, + { seriesIndex: 0, dataIndex: "0" }, + { seriesIndex: 99, dataIndex: 0 }, + { seriesIndex: 0, dataIndex: 99 }, + ])("rejects invalid tooltip parameters: %j", (params) => { + expect(format(params)).toBe(""); }); }); diff --git a/frontend/src/features/races/components/race-chart-options.test.ts b/frontend/src/features/races/components/race-chart-options.test.ts index 74bf283..b4cc7b9 100644 --- a/frontend/src/features/races/components/race-chart-options.test.ts +++ b/frontend/src/features/races/components/race-chart-options.test.ts @@ -1,282 +1,122 @@ import { describe, expect, it } from "vitest"; -import type { RaceDistributionData } from "../types"; +import { getFormatter } from "@/test/chart-utils"; +import type { RaceDistributionData } from "../types"; import { buildRaceChartOptions, getRaceColor, getTotalSelections, - type RaceChartOption, } from "./race-chart-options"; -function sample( - overrides: Partial = {}, -): RaceDistributionData { +function row(name: string, value: number): RaceDistributionData { return { - name: "White", - value: 1250, + name, + value, validCount: 1300, unknownCount: 100, missingCount: 100, - ...overrides, }; } -const sampleRows = [ - sample({ - name: "American Indian or Alaska Native", - value: 0, - }), - sample(), - sample({ - name: "Asian", - value: 250, - }), +const rows = [ + row("American Indian or Alaska Native", 0), + row("White", 1250), + row("Asian", 250), ]; -function getTooltipFormatter(options: RaceChartOption) { - const tooltip = options.tooltip; - - if ( - typeof tooltip !== "object" || - tooltip === null || - !("formatter" in tooltip) || - typeof tooltip.formatter !== "function" - ) { - throw new Error("Expected a callable tooltip formatter"); - } - - const formatter = tooltip.formatter; - - return (params: unknown): unknown => - Reflect.apply(formatter, undefined, [params]); -} - describe("getRaceColor", () => { it.each([ - { name: "White", expected: "#610030" }, - { name: "Asian", expected: "#2563eb" }, - { - name: "Black or African American", - expected: "#059669", - }, - { - name: "Native Hawaiian or Other Pacific Islander", - expected: "#d97706", - }, - { - name: "American Indian or Alaska Native", - expected: "#7c3aed", - }, - ])("returns the configured color for $name", ({ name, expected }) => { + ["White", "#610030"], + ["Asian", "#2563eb"], + ["Black or African American", "#059669"], + ["Native Hawaiian or Other Pacific Islander", "#d97706"], + ["American Indian or Alaska Native", "#7c3aed"], + ["Other", "#a21caf"], + ["𐐀", "#9a3412"], + ["", "#be123c"], + ["constructor", "#be123c"], + ["toString", "#9a3412"], + ["__proto__", "#9a3412"], + ])("returns the correct color for %s", (name, expected) => { expect(getRaceColor(name)).toBe(expected); }); - - it.each([ - { name: "Other", expected: "#a21caf" }, - { name: "Unknown category", expected: "#a21caf" }, - { name: "𐐀", expected: "#9a3412" }, - { name: "", expected: "#be123c" }, - ])( - "returns a deterministic fallback color for $name", - ({ name, expected }) => { - expect(getRaceColor(name)).toBe(expected); - expect(getRaceColor(name)).toBe(expected); - }, - ); - - it.each(["constructor", "toString", "__proto__"])( - "does not use inherited object properties: %s", - (name) => { - expect(getRaceColor(name)).toMatch(/^#[0-9a-f]{6}$/); - }, - ); }); describe("getTotalSelections", () => { - it("sums recorded selections rather than participant counts", () => { - expect(getTotalSelections(sampleRows)).toBe(1500); - }); - - it("returns zero for empty input", () => { + it("sums selections rather than participant counts", () => { + expect(getTotalSelections(rows)).toBe(1500); expect(getTotalSelections([])).toBe(0); }); - - it("returns zero when all selection counts are zero", () => { - expect( - getTotalSelections([ - sample({ value: 0 }), - sample({ name: "Asian", value: 0 }), - ]), - ).toBe(0); - }); }); describe("buildRaceChartOptions", () => { - it("constructs a pie chart using positive selection counts", () => { - const options = buildRaceChartOptions(sampleRows); + it("constructs a chart using positive selection counts", () => { + const options = buildRaceChartOptions(rows); - expect(options).toMatchObject({ - animation: false, - backgroundColor: "#ffffff", - aria: { - enabled: true, - label: { - description: - "Pie chart with 1,500 recorded race selections. " + - "Participants may select multiple categories.", - }, - }, - tooltip: { - trigger: "item", - confine: true, - renderMode: "html", + expect(options.series).toMatchObject([ + { + type: "pie", + stillShowZeroSum: false, + data: [ + { name: "White", value: 1250, itemStyle: { color: "#610030" } }, + { name: "Asian", value: 250, itemStyle: { color: "#2563eb" } }, + ], }, - series: [ - { - name: "Race selections", - type: "pie", - radius: ["50%", "73%"], - center: ["50%", "50%"], - stillShowZeroSum: false, - label: { - show: false, - }, - labelLine: { - show: false, - }, - data: [ - { - name: "White", - value: 1250, - itemStyle: { - color: "#610030", - }, - }, - { - name: "Asian", - value: 250, - itemStyle: { - color: "#2563eb", - }, - }, - ], - }, - ], - }); - - expect(sampleRows).toHaveLength(3); - expect(sampleRows[0].value).toBe(0); - }); - - it.each([ - { - label: "empty input", - rows: [], - }, - { - label: "zero selections", - rows: [sample({ value: 0 }), sample({ name: "Asian", value: 0 })], - }, - ])("constructs an empty chart for $label", ({ rows }) => { - const options = buildRaceChartOptions(rows); + ]); - expect(options).toMatchObject({ - aria: { - enabled: true, - label: { - description: - "Pie chart with 0 recorded race selections. " + - "Participants may select multiple categories.", - }, + expect(options.aria).toMatchObject({ + enabled: true, + label: { + description: + "Pie chart with 1,500 recorded race selections. " + + "Participants may select multiple categories.", }, - series: [ - { - type: "pie", - stillShowZeroSum: false, - data: [], - }, - ], }); }); -}); -describe("race tooltip formatter", () => { - it("formats counts and percentages using filtered chart indices", () => { - const options = buildRaceChartOptions(sampleRows); - const formatter = getTooltipFormatter(options); + it.each([{ data: [] }, { data: [row("White", 0)] }])( + "handles datasets without selections", + ({ data }) => { + const options = buildRaceChartOptions(data); - expect(formatter({ dataIndex: 0 })).toBe( - "White" + - "
1,250 selections
" + - "
83.3% of recorded selections
", - ); - - expect(formatter({ dataIndex: 1 })).toBe( - "Asian" + - "
250 selections
" + - "
16.7% of recorded selections
", - ); - }); - - it("escapes HTML characters in category names", () => { - const options = buildRaceChartOptions([ - sample({ - name: ` & "Other" 'Group'`, - value: 100, - }), - ]); + expect(options.series).toMatchObject([{ data: [] }]); + expect(getFormatter(options.tooltip)({ dataIndex: 0 })).toBe(""); + }, + ); +}); - const formatter = getTooltipFormatter(options); +describe("race tooltip", () => { + const format = getFormatter(buildRaceChartOptions(rows).tooltip); - expect(formatter({ dataIndex: 0 })).toBe( - "<Category> & "Other" 'Group'" + - "
100 selections
" + - "
100.0% of recorded selections
", + it.each([ + { dataIndex: 0, name: "White", count: "1,250", percent: "83.3" }, + { dataIndex: 1, name: "Asian", count: "250", percent: "16.7" }, + ])("formats selections for $name", ({ dataIndex, name, count, percent }) => { + expect(format({ dataIndex })).toBe( + `${name}` + + `
${count} selections
` + + `
${percent}% of recorded selections
`, ); }); - it("formats small selection percentages", () => { + it("escapes category names and formats small percentages", () => { const options = buildRaceChartOptions([ - sample({ value: 999 }), - sample({ - name: "Asian", - value: 1, - }), + row("White", 999), + row(' & "Group"', 1), ]); - const formatter = getTooltipFormatter(options); - - expect(formatter({ dataIndex: 1 })).toContain( - "0.1% of recorded selections", + expect(getFormatter(options.tooltip)({ dataIndex: 1 })).toBe( + "<Other> & "Group"" + + "
1 selections
" + + "
0.1% of recorded selections
", ); }); - it.each([ - { params: null }, - { params: undefined }, - { params: "invalid" }, - { params: {} }, - { params: { dataIndex: "0" } }, - { params: { dataIndex: -1 } }, - { params: { dataIndex: 99 } }, - { params: { dataIndex: NaN } }, - { params: { dataIndex: 0.5 } }, - ])( - "returns an empty tooltip for invalid parameters: $params", - ({ params }) => { - const options = buildRaceChartOptions(sampleRows); - const formatter = getTooltipFormatter(options); - - expect(formatter(params)).toBe(""); + it.each([null, "invalid", {}, { dataIndex: "0" }, { dataIndex: 99 }])( + "rejects invalid tooltip parameters: %j", + (params) => { + expect(format(params)).toBe(""); }, ); - - it("returns an empty tooltip when no selections exist", () => { - const options = buildRaceChartOptions([sample({ value: 0 })]); - - const formatter = getTooltipFormatter(options); - - expect(formatter({ dataIndex: 0 })).toBe(""); - }); }); From b85647a9c54cf866a28f264a1f4a94fbf3a119fe Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 18:02:45 +0100 Subject: [PATCH 027/102] test(frontend): add mappings API tests --- frontend/src/features/mappings/api.test.ts | 37 ++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 frontend/src/features/mappings/api.test.ts diff --git a/frontend/src/features/mappings/api.test.ts b/frontend/src/features/mappings/api.test.ts new file mode 100644 index 0000000..78f0218 --- /dev/null +++ b/frontend/src/features/mappings/api.test.ts @@ -0,0 +1,37 @@ +import { http, HttpResponse } from "msw"; +import { expect, it, vi } from "vitest"; + +import { mockChordData, TEST_API_URL } from "@/test/mocks/handlers"; +import { server } from "@/test/mocks/server"; + +import { fetchChordDiagram } from "./api"; + +it("retrieves chord data with an encoded modality and abort signal", async () => { + const controller = new AbortController(); + const fetch = vi.spyOn(globalThis, "fetch"); + + server.use( + http.get(`${TEST_API_URL}/visualization/chords/`, () => + HttpResponse.json(mockChordData), + ), + ); + + await expect( + fetchChordDiagram("Clinical & Imaging", controller.signal), + ).resolves.toEqual(mockChordData); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}/visualization/chords/?modality=Clinical+%26+Imaging`, + expect.objectContaining({ + method: "GET", + signal: controller.signal, + }), + ); +}); + +it("preserves empty chord diagrams", async () => { + await expect(fetchChordDiagram("Unknown modality")).resolves.toEqual({ + nodes: [], + links: [], + }); +}); From d27c23b6b21ba6077b5db579fbfda4c95cde8cdd Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 18:03:50 +0100 Subject: [PATCH 028/102] test(frontend): add race distribution API tests --- frontend/src/features/races/api.test.ts | 60 +++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 frontend/src/features/races/api.test.ts diff --git a/frontend/src/features/races/api.test.ts b/frontend/src/features/races/api.test.ts new file mode 100644 index 0000000..aa1d5d6 --- /dev/null +++ b/frontend/src/features/races/api.test.ts @@ -0,0 +1,60 @@ +import { http, HttpResponse } from "msw"; +import { expect, it, vi } from "vitest"; + +import { + mockCohorts, + mockRaceDistribution, + TEST_API_URL, +} from "@/test/mocks/handlers"; +import { server } from "@/test/mocks/server"; + +import { fetchRaceCohorts, fetchRaceDistribution } from "./api"; + +it("retrieves available cohorts and forwards the abort signal", async () => { + const controller = new AbortController(); + const fetch = vi.spyOn(globalThis, "fetch"); + + await expect(fetchRaceCohorts(controller.signal)).resolves.toEqual( + mockCohorts, + ); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}/races/cohorts`, + expect.objectContaining({ + method: "GET", + signal: controller.signal, + }), + ); +}); + +it.each([ + { + cohorts: [], + query: "", + }, + { + cohorts: ["Study A", "Study B & C (München)"], + query: "cohorts=Study+A&cohorts=Study+B+%26+C+%28M%C3%BCnchen%29", + }, +])("retrieves race distributions for $cohorts", async ({ cohorts, query }) => { + const controller = new AbortController(); + const fetch = vi.spyOn(globalThis, "fetch"); + + server.use( + http.get(`${TEST_API_URL}/races/distribution`, () => + HttpResponse.json(mockRaceDistribution), + ), + ); + + await expect( + fetchRaceDistribution(cohorts, controller.signal), + ).resolves.toEqual(mockRaceDistribution); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}/races/distribution?${query}`, + expect.objectContaining({ + method: "GET", + signal: controller.signal, + }), + ); +}); From 796dfcf26766f55af0782264f16a58588a46e770 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 18:04:52 +0100 Subject: [PATCH 029/102] test(frontend): add study picker API tests --- .../src/features/study-picker/api.test.ts | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 frontend/src/features/study-picker/api.test.ts diff --git a/frontend/src/features/study-picker/api.test.ts b/frontend/src/features/study-picker/api.test.ts new file mode 100644 index 0000000..1c5ef77 --- /dev/null +++ b/frontend/src/features/study-picker/api.test.ts @@ -0,0 +1,59 @@ +import { expect, it, vi } from "vitest"; + +import { + mockRankings, + mockVariables, + TEST_API_URL, +} from "@/test/mocks/handlers"; + +import { fetchStudyPickerVariables, rankCohorts } from "./api"; + +it("retrieves available variables and forwards the abort signal", async () => { + const controller = new AbortController(); + const fetch = vi.spyOn(globalThis, "fetch"); + + await expect(fetchStudyPickerVariables(controller.signal)).resolves.toEqual( + mockVariables, + ); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}/study-picker/variables`, + expect.objectContaining({ + method: "GET", + signal: controller.signal, + }), + ); +}); + +it("normalizes selected variables before requesting rankings", async () => { + const controller = new AbortController(); + const fetch = vi.spyOn(globalThis, "fetch"); + + const variables = [" Age ", "Motor score", "Age", "", " ", " Motor score "]; + + await expect(rankCohorts(variables, controller.signal)).resolves.toEqual( + mockRankings, + ); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}/study-picker/rank`, + expect.objectContaining({ + method: "POST", + body: JSON.stringify(["Age", "Motor score"]), + signal: controller.signal, + }), + ); +}); + +it.each([{ variables: [] }, { variables: ["", " ", "\t", "\n"] }])( + "rejects empty selections: $variables", + ({ variables }) => { + const fetch = vi.spyOn(globalThis, "fetch"); + + expect(() => rankCohorts(variables)).toThrow( + "Select at least one variable to rank cohorts.", + ); + + expect(fetch).not.toHaveBeenCalled(); + }, +); From 06202eb313a5c543fed149ca0108d488b0afb5ed Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 18:09:52 +0100 Subject: [PATCH 030/102] test(frontend): add study picker hook tests --- .../study-picker/hooks/useStudyPicker.test.ts | 194 ++++++++++++++++++ 1 file changed, 194 insertions(+) create mode 100644 frontend/src/features/study-picker/hooks/useStudyPicker.test.ts diff --git a/frontend/src/features/study-picker/hooks/useStudyPicker.test.ts b/frontend/src/features/study-picker/hooks/useStudyPicker.test.ts new file mode 100644 index 0000000..82980f1 --- /dev/null +++ b/frontend/src/features/study-picker/hooks/useStudyPicker.test.ts @@ -0,0 +1,194 @@ +// @vitest-environment jsdom + +import { act, renderHook, waitFor } from "@testing-library/react"; +import { http, HttpResponse } from "msw"; +import { expect, it, vi } from "vitest"; + +import { + mockMetadata, + mockRankings, + mockVariables, + TEST_API_URL, +} from "@/test/mocks/handlers"; +import { server } from "@/test/mocks/server"; +import { createTestWrapper } from "@/test/render"; + +import { useStudyPicker } from "./useStudyPicker"; + +const RANK_URL = `${TEST_API_URL}/study-picker/rank`; + +function setup() { + const { wrapper } = createTestWrapper({ route: null }); + + return renderHook(useStudyPicker, { wrapper }); +} + +it("loads variables and metadata without requesting rankings", async () => { + const { result } = setup(); + + await waitFor(() => { + expect(result.current.availableVariables).toEqual(mockVariables); + expect(result.current.metadata).toEqual(mockMetadata); + }); + + act(() => result.current.submitRanking()); + + expect(result.current.selectedVariables).toEqual([]); + expect(result.current.submittedVariables).toEqual([]); + expect(result.current.rankings).toEqual([]); + expect(result.current.canRank).toBe(false); + expect(result.current.hasSubmitted).toBe(false); + expect(result.current.rankingQuery.fetchStatus).toBe("idle"); +}); + +it("normalizes selections and manages the ranking lifecycle", async () => { + let release!: () => void; + + const pending = new Promise((resolve) => { + release = resolve; + }); + + const rank = vi.fn<() => Promise>(async () => { + await pending; + return HttpResponse.json(mockRankings); + }); + + server.use(http.post(RANK_URL, rank)); + + const { result } = setup(); + + try { + await waitFor(() => { + expect(result.current.variablesQuery.isSuccess).toBe(true); + }); + + act(() => { + result.current.updateSelectedVariables([ + " Age ", + "Motor score", + "Age", + "", + ]); + }); + + expect(result.current.selectedVariables).toEqual(mockVariables); + expect(result.current.canRank).toBe(true); + expect(result.current.hasSubmitted).toBe(false); + expect(rank).not.toHaveBeenCalled(); + + act(() => result.current.submitRanking()); + + await waitFor(() => { + expect(result.current.isRanking).toBe(true); + expect(rank).toHaveBeenCalledTimes(1); + }); + + expect(result.current.submittedVariables).toEqual(mockVariables); + expect(result.current.hasSubmitted).toBe(true); + expect(result.current.canRank).toBe(false); + } finally { + release(); + } + + await waitFor(() => { + expect(result.current.rankings).toEqual(mockRankings); + expect(result.current.isRanking).toBe(false); + }); + + expect(result.current.canRank).toBe(true); + + // An equivalent selection should preserve the existing results. + act(() => { + result.current.updateSelectedVariables(["Age", " Motor score ", "Age"]); + }); + + expect(result.current.submittedVariables).toEqual(mockVariables); + expect(result.current.rankings).toEqual(mockRankings); + + // Submitting the same selection should explicitly refetch. + act(() => result.current.submitRanking()); + + await waitFor(() => { + expect(rank).toHaveBeenCalledTimes(2); + expect(result.current.isRanking).toBe(false); + }); + + // Changing the selection should clear the previous submission. + act(() => { + result.current.updateSelectedVariables(["Motor score", "Age"]); + }); + + expect(result.current.selectedVariables).toEqual(["Motor score", "Age"]); + expect(result.current.submittedVariables).toEqual([]); + expect(result.current.rankings).toEqual([]); + expect(result.current.hasSubmitted).toBe(false); + expect(result.current.canRank).toBe(true); +}); + +it("distinguishes empty ranking results from an unsubmitted selection", async () => { + server.use(http.post(RANK_URL, () => HttpResponse.json([]))); + + const { result } = setup(); + + act(() => result.current.updateSelectedVariables(["Age"])); + act(() => result.current.submitRanking()); + + await waitFor(() => { + expect(result.current.rankingQuery.isSuccess).toBe(true); + }); + + expect(result.current.hasSubmitted).toBe(true); + expect(result.current.rankings).toEqual([]); +}); + +it("exposes ranking errors and supports retrying", async () => { + server.use( + http.post(RANK_URL, () => + HttpResponse.json({ detail: "Ranking unavailable" }, { status: 503 }), + ), + ); + + const { result } = setup(); + + act(() => result.current.updateSelectedVariables(mockVariables)); + act(() => result.current.submitRanking()); + + await waitFor(() => { + expect(result.current.rankingQuery.isError).toBe(true); + }); + + expect(result.current.rankingQuery.error?.message).toBe( + "Ranking unavailable", + ); + expect(result.current.rankings).toEqual([]); + expect(result.current.canRank).toBe(true); + + server.use(http.post(RANK_URL, () => HttpResponse.json(mockRankings))); + + act(() => result.current.submitRanking()); + + await waitFor(() => { + expect(result.current.rankings).toEqual(mockRankings); + expect(result.current.rankingQuery.isSuccess).toBe(true); + }); +}); + +it("provides fallback data when initial queries fail", async () => { + server.use( + http.get(`${TEST_API_URL}/study-picker/variables`, () => + HttpResponse.error(), + ), + http.get(`${TEST_API_URL}/cohorts/metadata`, () => HttpResponse.error()), + ); + + const { result } = setup(); + + await waitFor(() => { + expect(result.current.variablesQuery.isError).toBe(true); + expect(result.current.metadataQuery.isError).toBe(true); + }); + + expect(result.current.availableVariables).toEqual([]); + expect(result.current.metadata).toEqual({}); + expect(result.current.canRank).toBe(false); +}); From 04a4f8fac2785cf92fe4cda6cdae7e4615221fd8 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 18:12:25 +0100 Subject: [PATCH 031/102] test(frontend): add biomarker hook tests --- .../biomarkers/hooks/useBiomarkers.test.ts | 233 ++++++++++++++++++ 1 file changed, 233 insertions(+) create mode 100644 frontend/src/features/biomarkers/hooks/useBiomarkers.test.ts diff --git a/frontend/src/features/biomarkers/hooks/useBiomarkers.test.ts b/frontend/src/features/biomarkers/hooks/useBiomarkers.test.ts new file mode 100644 index 0000000..93e1bea --- /dev/null +++ b/frontend/src/features/biomarkers/hooks/useBiomarkers.test.ts @@ -0,0 +1,233 @@ +// @vitest-environment jsdom + +import { act, renderHook, waitFor } from "@testing-library/react"; +import { http, HttpResponse } from "msw"; +import { expect, it, vi } from "vitest"; + +import { mockBiomarkers, TEST_API_URL } from "@/test/mocks/handlers"; +import { server } from "@/test/mocks/server"; +import { createTestWrapper } from "@/test/render"; + +import { useBiomarkers } from "./useBiomarkers"; + +const MEASUREMENTS_URL = `${TEST_API_URL}/biomarkers/cohorts/:cohort/diagnoses/:diagnosis`; + +const HC = "Study A (HC Group)"; +const PD = "Study A (PD Group)"; +const COMPLETE = "Study A (Complete)"; +const STUDY_B_PD = "Study B (PD Group)"; + +function setup() { + const { wrapper } = createTestWrapper({ route: null }); + + return renderHook(useBiomarkers, { wrapper }); +} + +it("loads biomarkers and manages dependent selections", async () => { + const { result } = setup(); + + await waitFor(() => { + expect(result.current.availableBiomarkers).toEqual(mockBiomarkers); + expect(result.current.cohortColors).toEqual({ + "Study A": "#2563eb", + "Study B": "#059669", + }); + }); + + expect(result.current.selectedBiomarker).toBe(""); + expect(result.current.cohortsQuery.fetchStatus).toBe("idle"); + expect(result.current.diagnosesQuery.fetchStatus).toBe("idle"); + expect(result.current.measurementQueries).toEqual([]); + + act(() => result.current.selectBiomarker(" Age ")); + + expect(result.current.selectedBiomarker).toBe("Age"); + expect(result.current.isLoadingDiagnosisOptions).toBe(true); + + await waitFor(() => { + expect(result.current.availableDiagnosisLabels).toEqual([ + HC, + PD, + COMPLETE, + STUDY_B_PD, + ]); + }); + + act(() => { + result.current.updateSelectedDiagnosisLabels([ + PD, + COMPLETE, + PD, + "Invalid group", + ]); + }); + + expect(result.current.selectedDiagnosisLabels).toEqual([PD, COMPLETE]); + expect(result.current.isLoadingMeasurements).toBe(true); + + await waitFor(() => { + expect(result.current.distributions).toEqual([ + { + label: PD, + cohort: "Study A", + diagnosis: "PD", + values: [65, 70, 75], + }, + { + label: COMPLETE, + cohort: "Study A", + diagnosis: "Complete", + values: [50, 55, 60, 65, 70, 75], + }, + ]); + expect(result.current.isFetchingMeasurements).toBe(false); + }); + + // Equivalent selections must preserve the current results. + act(() => result.current.selectBiomarker("Age")); + act(() => result.current.updateSelectedDiagnosisLabels([PD, COMPLETE])); + + expect(result.current.selectedDiagnosisLabels).toEqual([PD, COMPLETE]); + expect(result.current.distributions).toHaveLength(2); + + // Changing the biomarker resets the previous diagnosis selection. + act(() => result.current.selectBiomarker("Motor score")); + + expect(result.current.selectedDiagnosisLabels).toEqual([]); + expect(result.current.distributions).toEqual([]); + + await waitFor(() => { + expect(result.current.availableDiagnosisLabels).toEqual([PD]); + }); + + act(() => result.current.updateSelectedDiagnosisLabels([PD])); + + await waitFor(() => { + expect(result.current.distributions).toEqual([ + { + label: PD, + cohort: "Study A", + diagnosis: "PD", + values: [10, 20, 30], + }, + ]); + }); + + act(() => result.current.selectBiomarker(" ")); + + expect(result.current.selectedBiomarker).toBe(""); + expect(result.current.selectedDiagnosisLabels).toEqual([]); + expect(result.current.distributions).toEqual([]); + expect(result.current.measurementQueries).toEqual([]); +}); + +it("preserves successful groups and retries only failed measurements", async () => { + server.use( + http.get(MEASUREMENTS_URL, ({ params }) => { + if (params.diagnosis === "HC") { + return HttpResponse.json([50, 55, 60]); + } + + if (params.cohort === "Study B") { + return HttpResponse.json([]); + } + + return HttpResponse.json( + { detail: "Measurements unavailable" }, + { status: 503 }, + ); + }), + ); + + const { result } = setup(); + + act(() => result.current.selectBiomarker("Age")); + + await waitFor(() => { + expect(result.current.availableDiagnosisLabels).toContain(STUDY_B_PD); + }); + + act(() => { + result.current.updateSelectedDiagnosisLabels([HC, PD, STUDY_B_PD]); + }); + + await waitFor(() => { + expect(result.current.distributions).toEqual([ + { + label: HC, + cohort: "Study A", + diagnosis: "HC", + values: [50, 55, 60], + }, + ]); + + expect(result.current.failedGroups).toEqual([ + { label: PD, message: "Measurements unavailable" }, + ]); + + expect(result.current.unavailableGroups).toEqual([STUDY_B_PD]); + expect(result.current.isFetchingMeasurements).toBe(false); + }); + + server.use(http.get(MEASUREMENTS_URL, () => HttpResponse.json([65, 70, 75]))); + + const fetch = vi.spyOn(globalThis, "fetch"); + + act(() => result.current.retryFailedMeasurements()); + + await waitFor(() => { + expect(result.current.failedGroups).toEqual([]); + expect(result.current.distributions).toHaveLength(2); + expect(result.current.isFetchingMeasurements).toBe(false); + }); + + expect(result.current.unavailableGroups).toEqual([STUDY_B_PD]); + + expect(result.current.distributions[1]).toMatchObject({ + label: PD, + values: [65, 70, 75], + }); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}/biomarkers/cohorts/Study%20A/diagnoses/PD?biomarker=Age`, + expect.objectContaining({ method: "GET" }), + ); +}); + +it("provides fallback data when initial queries fail", async () => { + server.use( + http.get(`${TEST_API_URL}/biomarkers/`, () => HttpResponse.error()), + http.get(`${TEST_API_URL}/cohorts/metadata`, () => HttpResponse.error()), + ); + + const { result } = setup(); + + await waitFor(() => { + expect(result.current.biomarkersQuery.isError).toBe(true); + expect(result.current.metadataQuery.isError).toBe(true); + }); + + expect(result.current.availableBiomarkers).toEqual([]); + expect(result.current.cohortColors).toEqual({}); +}); + +it("does not request measurements when diagnosis options fail", async () => { + server.use( + http.get(`${TEST_API_URL}/biomarkers/diagnoses`, () => + HttpResponse.error(), + ), + ); + + const { result } = setup(); + + act(() => result.current.selectBiomarker("Age")); + + await waitFor(() => { + expect(result.current.cohortsQuery.isSuccess).toBe(true); + expect(result.current.diagnosesQuery.isError).toBe(true); + }); + + expect(result.current.availableDiagnosisLabels).toEqual([]); + expect(result.current.isLoadingDiagnosisOptions).toBe(false); + expect(result.current.measurementQueries).toEqual([]); +}); From f984e38edfb77bcb92073c86379ccd3b91a4f9c5 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 22:27:30 +0100 Subject: [PATCH 032/102] test(frontend): add longitudinal hook tests --- .../hooks/useLongitudinal.test.ts | 157 ++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 frontend/src/features/longitudinal/hooks/useLongitudinal.test.ts diff --git a/frontend/src/features/longitudinal/hooks/useLongitudinal.test.ts b/frontend/src/features/longitudinal/hooks/useLongitudinal.test.ts new file mode 100644 index 0000000..802b63b --- /dev/null +++ b/frontend/src/features/longitudinal/hooks/useLongitudinal.test.ts @@ -0,0 +1,157 @@ +// @vitest-environment jsdom + +import { act, renderHook, waitFor } from "@testing-library/react"; +import { http, HttpResponse } from "msw"; +import { expect, it } from "vitest"; + +import { mockLongitudinalVariables, TEST_API_URL } from "@/test/mocks/handlers"; +import { server } from "@/test/mocks/server"; +import { createTestWrapper } from "@/test/render"; + +import { useLongitudinal } from "./useLongitudinal"; + +function setup() { + const { wrapper } = createTestWrapper({ route: null }); + + return renderHook(useLongitudinal, { wrapper }); +} + +it("selects Study Visit by default and prepares retention series", async () => { + const { result } = setup(); + + await waitFor(() => { + expect(result.current.variables).toEqual(mockLongitudinalVariables); + expect(result.current.selectedVariable).toBe("Study Visit"); + expect(result.current.measurementsQuery.isSuccess).toBe(true); + expect(result.current.colors).toEqual({ + "Study A": "#2563eb", + "Study B": "#059669", + }); + }); + + expect(result.current.measurementsQuery.data).toMatchObject([ + { + name: "Study A", + points: [ + { months: 0, retentionPercent: 80 }, + { months: 12, retentionPercent: 60 }, + ], + }, + { + name: "Study B", + points: [ + { months: 0, retentionPercent: 80 }, + { months: 6, retentionPercent: 60 }, + ], + }, + ]); + + server.use( + http.get(`${TEST_API_URL}/longitudinal/Age`, () => + HttpResponse.json([ + { + cohort: "Study A", + months: 6, + patientCount: 25, + totalPatientCount: 50, + }, + ]), + ), + ); + + act(() => result.current.setUserSelection("Age")); + + await waitFor(() => { + expect(result.current.selectedVariable).toBe("Age"); + expect(result.current.measurementsQuery.data).toMatchObject([ + { + name: "Study A", + points: [{ months: 6, retentionPercent: 50 }], + }, + ]); + }); + + act(() => result.current.setUserSelection("")); + + expect(result.current.selectedVariable).toBe(""); + expect(result.current.measurementsQuery.fetchStatus).toBe("idle"); + expect(result.current.measurementsQuery.data).toBeUndefined(); + + act(() => result.current.setUserSelection(null)); + + expect(result.current.selectedVariable).toBe("Study Visit"); +}); + +it("requires manual selection when Study Visit is unavailable", async () => { + server.use( + http.get(`${TEST_API_URL}/longitudinal/`, () => HttpResponse.json(["Age"])), + ); + + const { result } = setup(); + + await waitFor(() => { + expect(result.current.variables).toEqual(["Age"]); + }); + + expect(result.current.selectedVariable).toBe(""); + expect(result.current.measurementsQuery.fetchStatus).toBe("idle"); + + act(() => result.current.setUserSelection("Age")); + + await waitFor(() => { + expect(result.current.measurementsQuery.isSuccess).toBe(true); + }); + + expect(result.current.selectedVariable).toBe("Age"); +}); + +it("preserves cached measurements when refreshing fails", async () => { + const { result } = setup(); + + await waitFor(() => { + expect(result.current.measurementsQuery.isSuccess).toBe(true); + }); + + const previous = result.current.measurementsQuery.data; + + server.use( + http.get(`${TEST_API_URL}/longitudinal/:variable`, () => + HttpResponse.json( + { detail: "Measurements unavailable" }, + { status: 503 }, + ), + ), + ); + + await act(async () => { + await result.current.measurementsQuery.refetch(); + }); + + await waitFor(() => { + expect(result.current.measurementsQuery.isError).toBe(true); + }); + + expect(result.current.measurementsQuery.error?.message).toBe( + "Measurements unavailable", + ); + expect(result.current.measurementsQuery.data).toEqual(previous); +}); + +it("provides fallback data when initial queries fail", async () => { + server.use( + http.get(`${TEST_API_URL}/longitudinal/`, () => HttpResponse.error()), + http.get(`${TEST_API_URL}/cohorts/metadata`, () => HttpResponse.error()), + ); + + const { result } = setup(); + + await waitFor(() => { + expect(result.current.variablesQuery.isError).toBe(true); + expect(result.current.metadataQuery.isError).toBe(true); + }); + + expect(result.current.variables).toEqual([]); + expect(result.current.colors).toEqual({}); + expect(result.current.selectedVariable).toBe(""); + expect(result.current.measurementsQuery.fetchStatus).toBe("idle"); +}); From e4a44d6e8393e994378d980718f07e7a8f5d581f Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 22:30:39 +0100 Subject: [PATCH 033/102] test(frontend): add cohort longitudinal hook tests --- .../hooks/useCohortLongitudinal.test.ts | 173 ++++++++++++++++++ 1 file changed, 173 insertions(+) create mode 100644 frontend/src/features/longitudinal/hooks/useCohortLongitudinal.test.ts diff --git a/frontend/src/features/longitudinal/hooks/useCohortLongitudinal.test.ts b/frontend/src/features/longitudinal/hooks/useCohortLongitudinal.test.ts new file mode 100644 index 0000000..a3cae00 --- /dev/null +++ b/frontend/src/features/longitudinal/hooks/useCohortLongitudinal.test.ts @@ -0,0 +1,173 @@ +// @vitest-environment jsdom + +import { act, renderHook, waitFor } from "@testing-library/react"; +import { http, HttpResponse } from "msw"; +import { expect, it, vi } from "vitest"; + +import { mockLongitudinalData, TEST_API_URL } from "@/test/mocks/handlers"; +import { server } from "@/test/mocks/server"; +import { createTestWrapper } from "@/test/render"; + +import { useCohortLongitudinal } from "./useCohortLongitudinal"; + +const MEASUREMENTS_URL = `${TEST_API_URL}/longitudinal/:variable/:cohort`; + +function setup(initialCohort: string, initialVariables: readonly string[]) { + const { wrapper } = createTestWrapper({ route: null }); + + return renderHook( + ({ cohort, variables }) => useCohortLongitudinal(cohort, variables), + { + wrapper, + initialProps: { + cohort: initialCohort, + variables: initialVariables, + }, + }, + ); +} + +it.each([ + { cohort: "", variables: ["Age"] }, + { cohort: "Study A", variables: [] }, +])("does not fetch without a cohort and variables", ({ cohort, variables }) => { + const fetch = vi.spyOn(globalThis, "fetch"); + const { result } = setup(cohort, variables); + + expect(result.current).toMatchObject({ + series: [], + failedVariables: [], + unavailableVariables: [], + isPending: false, + }); + + expect(fetch).not.toHaveBeenCalled(); +}); + +it("loads multiple variables and updates results when the cohort changes", async () => { + const variables = ["Age", "Study Visit"]; + const { result, rerender } = setup("Study A", variables); + + expect(result.current.isPending).toBe(true); + + await waitFor(() => { + expect(result.current.isPending).toBe(false); + expect(result.current.series).toMatchObject( + variables.map((name) => ({ + name, + points: [ + { months: 0, retentionPercent: 80 }, + { months: 12, retentionPercent: 60 }, + ], + })), + ); + }); + + rerender({ cohort: "Study B", variables }); + + await waitFor(() => { + expect(result.current.isPending).toBe(false); + expect(result.current.series).toMatchObject( + variables.map((name) => ({ + name, + points: [ + { months: 0, retentionPercent: 80 }, + { months: 6, retentionPercent: 60 }, + ], + })), + ); + }); +}); + +it("preserves successful series and retries only failed variables", async () => { + server.use( + http.get(MEASUREMENTS_URL, ({ params }) => { + switch (params.variable) { + case "Age": + return HttpResponse.json( + mockLongitudinalData.filter((row) => row.cohort === "Study A"), + ); + + case "Motor score": + return HttpResponse.json( + { detail: "Measurements unavailable" }, + { status: 503 }, + ); + + case "Invalid counts": + return HttpResponse.json([ + { + cohort: "Study A", + months: 0, + patientCount: 120, + totalPatientCount: 100, + }, + ]); + + default: + return HttpResponse.json([]); + } + }), + ); + + const { result } = setup("Study A", [ + "Age", + "Motor score", + "Unknown variable", + "Invalid counts", + ]); + + await waitFor(() => { + expect(result.current.isPending).toBe(false); + expect(result.current.series.map((item) => item.name)).toEqual(["Age"]); + + expect(result.current.failedVariables).toEqual([ + { variable: "Motor score", message: "Measurements unavailable" }, + ]); + + expect(result.current.unavailableVariables).toEqual([ + "Unknown variable", + "Invalid counts", + ]); + }); + + server.use( + http.get(MEASUREMENTS_URL, () => + HttpResponse.json([ + { + cohort: "Study A", + months: 0, + patientCount: 50, + totalPatientCount: 100, + }, + ]), + ), + ); + + const fetch = vi.spyOn(globalThis, "fetch"); + + act(() => result.current.retryFailed()); + + await waitFor(() => { + expect(result.current.failedVariables).toEqual([]); + expect(result.current.series.map((item) => item.name)).toEqual([ + "Age", + "Motor score", + ]); + expect(result.current.isPending).toBe(false); + }); + + expect(result.current.series[1].points).toMatchObject([ + { months: 0, retentionPercent: 50 }, + ]); + + expect(result.current.unavailableVariables).toEqual([ + "Unknown variable", + "Invalid counts", + ]); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + `${TEST_API_URL}/longitudinal/Motor%20score/Study%20A`, + expect.objectContaining({ method: "GET" }), + ); +}); From c49955406e3f108d193c6df9339f8a359214332e Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 22:36:14 +0100 Subject: [PATCH 034/102] test(frontend): add mappings hook tests --- .../mappings/hooks/useMappings.test.ts | 213 ++++++++++++++++++ 1 file changed, 213 insertions(+) create mode 100644 frontend/src/features/mappings/hooks/useMappings.test.ts diff --git a/frontend/src/features/mappings/hooks/useMappings.test.ts b/frontend/src/features/mappings/hooks/useMappings.test.ts new file mode 100644 index 0000000..f6ce71b --- /dev/null +++ b/frontend/src/features/mappings/hooks/useMappings.test.ts @@ -0,0 +1,213 @@ +// @vitest-environment jsdom + +import { act, renderHook, waitFor } from "@testing-library/react"; +import { http, HttpResponse } from "msw"; +import { expect, it } from "vitest"; + +import { + mockChordData, + mockModalities, + TEST_API_URL, +} from "@/test/mocks/handlers"; +import { server } from "@/test/mocks/server"; +import { createTestWrapper } from "@/test/render"; + +import type { ChordDiagramData } from "../types"; +import { useMappings } from "./useMappings"; + +const CHORD_URL = `${TEST_API_URL}/visualization/chords/`; + +function setup() { + const { wrapper } = createTestWrapper({ route: null }); + + return renderHook(useMappings, { wrapper }); +} + +function createMultiPageGraph(): ChordDiagramData { + const links = Array.from({ length: 41 }, (_, index) => ({ + source: `Source ${index}`, + target: `Target ${index}`, + })); + + return { + nodes: [ + ...links.flatMap(({ source, target }) => [ + { name: source, group: "Study A" }, + { name: target, group: "Study B" }, + ]), + ...Array.from({ length: 40 }, (_, index) => ({ + name: `Isolated ${index}`, + group: "Study C", + })), + ], + links, + }; +} + +it("loads modalities and retrieves mappings only after selection", async () => { + const { result } = setup(); + + await waitFor(() => { + expect(result.current.modalities).toEqual(mockModalities); + expect(result.current.cohortColors).toEqual({ + "Study A": "#2563eb", + "Study B": "#059669", + }); + }); + + expect(result.current.selectedModality).toBe(""); + expect(result.current.chordQuery.fetchStatus).toBe("idle"); + expect(result.current.hasMappings).toBe(false); + expect(result.current.currentChunk).toBeNull(); + + act(() => result.current.selectModality(" Demographics ")); + + expect(result.current.selectedModality).toBe("Demographics"); + expect(result.current.isLoadingMappings).toBe(true); + + await waitFor(() => { + expect(result.current.hasMappings).toBe(true); + expect(result.current.isFetchingMappings).toBe(false); + }); + + expect(result.current.currentChunk?.nodes).toMatchObject(mockChordData.nodes); + expect(result.current.currentChunk?.links).toHaveLength(1); + expect(result.current.currentPage).toBe(1); + expect(result.current.totalPages).toBe(1); + + act(() => result.current.selectModality("Clinical")); + + await waitFor(() => { + expect(result.current.chordQuery.isSuccess).toBe(true); + }); + + expect(result.current.hasMappings).toBe(false); + expect(result.current.totalPages).toBe(0); + expect(result.current.currentPage).toBe(0); + expect(result.current.currentChunk).toBeNull(); +}); + +it("filters isolated nodes and manages pagination", async () => { + const graph = createMultiPageGraph(); + + server.use(http.get(CHORD_URL, () => HttpResponse.json(graph))); + + const { result } = setup(); + + act(() => result.current.selectModality("Demographics")); + + await waitFor(() => { + expect(result.current.totalPages).toBe(3); + }); + + expect(result.current.chunks.map((chunk) => chunk.nodes.length)).toEqual([ + 40, 40, 2, + ]); + + expect(result.current.chunks.map((chunk) => chunk.links.length)).toEqual([ + 20, 20, 1, + ]); + + expect(result.current.canGoPrevious).toBe(false); + expect(result.current.canGoNext).toBe(true); + + act(() => result.current.goToPreviousPage()); + expect(result.current.currentPage).toBe(1); + + for (const index of [-1, 0.5, 3]) { + act(() => result.current.goToPage(index)); + expect(result.current.currentPage).toBe(1); + } + + act(() => result.current.goToNextPage()); + expect(result.current.currentPage).toBe(2); + + act(() => result.current.goToPreviousPage()); + expect(result.current.currentPage).toBe(1); + + act(() => result.current.goToPage(2)); + + expect(result.current.currentPage).toBe(3); + expect(result.current.currentChunk).toBe(result.current.chunks[2]); + expect(result.current.canGoPrevious).toBe(true); + expect(result.current.canGoNext).toBe(false); + + act(() => result.current.goToNextPage()); + expect(result.current.currentPage).toBe(3); + + act(() => result.current.selectModality(" Demographics ")); + expect(result.current.currentPage).toBe(3); + + // Changing the modality resets pagination. + act(() => result.current.selectModality("Clinical")); + + await waitFor(() => { + expect(result.current.totalPages).toBe(3); + expect(result.current.currentPage).toBe(1); + }); + + act(() => result.current.goToPage(2)); + + // A refresh may return fewer diagram pages. + server.use(http.get(CHORD_URL, () => HttpResponse.json(mockChordData))); + + await act(async () => { + await result.current.chordQuery.refetch(); + }); + + await waitFor(() => { + expect(result.current.totalPages).toBe(1); + expect(result.current.currentPage).toBe(1); + }); + + expect(result.current.canGoNext).toBe(false); + expect(result.current.canGoPrevious).toBe(false); +}); + +it("provides fallback data when initial queries fail", async () => { + server.use( + http.get(`${TEST_API_URL}/cdm/modalities`, () => HttpResponse.error()), + http.get(`${TEST_API_URL}/cohorts/metadata`, () => HttpResponse.error()), + ); + + const { result } = setup(); + + await waitFor(() => { + expect(result.current.modalitiesQuery.isError).toBe(true); + expect(result.current.metadataQuery.isError).toBe(true); + }); + + expect(result.current.modalities).toEqual([]); + expect(result.current.cohortColors).toEqual({}); + expect(result.current.isLoadingModalities).toBe(false); +}); + +it("recovers from a failed mapping request", async () => { + server.use( + http.get(CHORD_URL, () => + HttpResponse.json({ detail: "Mappings unavailable" }, { status: 503 }), + ), + ); + + const { result } = setup(); + + act(() => result.current.selectModality("Demographics")); + + await waitFor(() => { + expect(result.current.chordQuery.isError).toBe(true); + }); + + expect(result.current.chordQuery.error?.message).toBe("Mappings unavailable"); + expect(result.current.hasMappings).toBe(false); + + server.use(http.get(CHORD_URL, () => HttpResponse.json(mockChordData))); + + await act(async () => { + await result.current.chordQuery.refetch(); + }); + + await waitFor(() => { + expect(result.current.chordQuery.isSuccess).toBe(true); + expect(result.current.hasMappings).toBe(true); + }); +}); From efe534eb9c5817df7f69021570b4e683195bc613 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 22:38:01 +0100 Subject: [PATCH 035/102] test(frontend): add race distribution hook tests --- .../races/hooks/useRaceDistribution.test.ts | 155 ++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 frontend/src/features/races/hooks/useRaceDistribution.test.ts diff --git a/frontend/src/features/races/hooks/useRaceDistribution.test.ts b/frontend/src/features/races/hooks/useRaceDistribution.test.ts new file mode 100644 index 0000000..2312484 --- /dev/null +++ b/frontend/src/features/races/hooks/useRaceDistribution.test.ts @@ -0,0 +1,155 @@ +// @vitest-environment jsdom + +import { act, renderHook, waitFor } from "@testing-library/react"; +import { http, HttpResponse } from "msw"; +import { expect, it, vi } from "vitest"; + +import { + mockCohorts, + mockRaceDistribution, + TEST_API_URL, +} from "@/test/mocks/handlers"; +import { server } from "@/test/mocks/server"; +import { createTestWrapper } from "@/test/render"; + +import { useRaceDistribution } from "./useRaceDistribution"; + +const COHORTS_URL = `${TEST_API_URL}/races/cohorts`; +const DISTRIBUTION_URL = `${TEST_API_URL}/races/distribution`; + +function setup() { + const { wrapper } = createTestWrapper({ route: null }); + + return renderHook(useRaceDistribution, { wrapper }); +} + +it("loads all cohorts by default and supports cohort filtering", async () => { + const { result } = setup(); + + expect(result.current.distributionQuery.fetchStatus).toBe("idle"); + + await waitFor(() => { + expect(result.current.availableCohorts).toEqual(mockCohorts); + expect(result.current.distributionQuery.data).toEqual(mockRaceDistribution); + }); + + expect(result.current.selectedCohort).toBe(""); + + act(() => result.current.selectCohort(" Study A ")); + + expect(result.current.selectedCohort).toBe("Study A"); + + await waitFor(() => { + expect(result.current.distributionQuery.data).toMatchObject([ + { name: "White", value: 60 }, + { name: "Asian", value: 20 }, + ]); + }); + + act(() => result.current.selectCohort("")); + + expect(result.current.selectedCohort).toBe(""); + + await waitFor(() => { + expect(result.current.distributionQuery.data).toEqual(mockRaceDistribution); + }); + + act(() => result.current.selectCohort("Unknown cohort")); + + expect(result.current.selectedCohort).toBe(""); + expect(result.current.distributionQuery.data).toEqual(mockRaceDistribution); +}); + +it("falls back to available cohorts when the selected cohort disappears", async () => { + const { result } = setup(); + + await waitFor(() => { + expect(result.current.distributionQuery.isSuccess).toBe(true); + }); + + act(() => result.current.selectCohort("Study A")); + + await waitFor(() => { + expect(result.current.distributionQuery.isSuccess).toBe(true); + }); + + server.use(http.get(COHORTS_URL, () => HttpResponse.json(["Study B"]))); + + await act(async () => { + await result.current.cohortsQuery.refetch(); + }); + + await waitFor(() => { + expect(result.current.availableCohorts).toEqual(["Study B"]); + expect(result.current.selectedCohort).toBe(""); + expect(result.current.distributionQuery.data).toMatchObject([ + { name: "White", value: 35 }, + { name: "Asian", value: 10 }, + ]); + }); +}); + +it.each([ + { fail: false, status: "success" }, + { fail: true, status: "error" }, +])( + "disables distribution queries without cohorts ($status)", + async ({ fail, status }) => { + server.use( + http.get(COHORTS_URL, () => + fail ? HttpResponse.error() : HttpResponse.json([]), + ), + ); + + const fetch = vi.spyOn(globalThis, "fetch"); + const { result } = setup(); + + await waitFor(() => { + expect(result.current.cohortsQuery.status).toBe(status); + }); + + expect(result.current.availableCohorts).toEqual([]); + expect(result.current.selectedCohort).toBe(""); + expect(result.current.distributionQuery.fetchStatus).toBe("idle"); + expect(result.current.distributionQuery.data).toBeUndefined(); + + expect(fetch).toHaveBeenCalledExactlyOnceWith( + COHORTS_URL, + expect.objectContaining({ method: "GET" }), + ); + }, +); + +it("exposes distribution errors and supports retrying", async () => { + server.use( + http.get(DISTRIBUTION_URL, () => + HttpResponse.json( + { detail: "Race distribution unavailable" }, + { status: 503 }, + ), + ), + ); + + const { result } = setup(); + + await waitFor(() => { + expect(result.current.distributionQuery.isError).toBe(true); + }); + + expect(result.current.distributionQuery.error?.message).toBe( + "Race distribution unavailable", + ); + + server.use( + http.get(DISTRIBUTION_URL, () => HttpResponse.json(mockRaceDistribution)), + ); + + await act(async () => { + await result.current.distributionQuery.refetch(); + }); + + await waitFor(() => { + expect(result.current.distributionQuery.isSuccess).toBe(true); + expect(result.current.distributionQuery.data).toEqual(mockRaceDistribution); + }); +}); From a5fa2b1674bd0037a7dde01b4c6c121221a22478 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 22:40:07 +0100 Subject: [PATCH 036/102] test(frontend): add home statistics hook tests --- .../home/hooks/useHomeStatistics.test.ts | 123 ++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 frontend/src/features/home/hooks/useHomeStatistics.test.ts diff --git a/frontend/src/features/home/hooks/useHomeStatistics.test.ts b/frontend/src/features/home/hooks/useHomeStatistics.test.ts new file mode 100644 index 0000000..5dc51ac --- /dev/null +++ b/frontend/src/features/home/hooks/useHomeStatistics.test.ts @@ -0,0 +1,123 @@ +// @vitest-environment jsdom + +import { renderHook, waitFor } from "@testing-library/react"; +import { http, HttpResponse } from "msw"; +import { expect, it } from "vitest"; + +import { mockMetadata, TEST_API_URL } from "@/test/mocks/handlers"; +import { server } from "@/test/mocks/server"; +import { createTestWrapper } from "@/test/render"; + +import { useHomeStatistics } from "./useHomeStatistics"; + +const expectedStatistics = [ + { label: "Cohorts", value: 2 }, + { label: "Participants", value: 150 }, + { label: "Variables Mapped", value: 2 }, + { label: "Compared Modalities", value: 2 }, +]; + +function setup() { + const { wrapper } = createTestWrapper({ route: null }); + + return renderHook(useHomeStatistics, { wrapper }); +} + +it("loads and aggregates homepage statistics", async () => { + const { result } = setup(); + + expect(result.current.isLoading).toBe(true); + expect(result.current.statistics.every(({ value }) => value === null)).toBe( + true, + ); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + expect(result.current.statistics).toEqual(expectedStatistics); + expect(result.current.error).toBeNull(); +}); + +it("excludes unreported participant counts from the total", async () => { + server.use( + http.get(`${TEST_API_URL}/cohorts/metadata`, () => + HttpResponse.json({ + ...mockMetadata, + "Study B": { + ...mockMetadata["Study B"], + participants: null, + }, + }), + ), + ); + + const { result } = setup(); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + expect(result.current.statistics).toContainEqual({ + label: "Participants", + value: 100, + }); +}); + +it("returns zero for successfully loaded empty datasets", async () => { + server.use( + http.get(`${TEST_API_URL}/cohorts/`, () => HttpResponse.json([])), + http.get(`${TEST_API_URL}/cohorts/metadata`, () => HttpResponse.json({})), + http.get(`${TEST_API_URL}/cdm/variables`, () => HttpResponse.json([])), + http.get(`${TEST_API_URL}/cdm/modalities`, () => HttpResponse.json([])), + ); + + const { result } = setup(); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + expect(result.current.statistics).toEqual( + expectedStatistics.map((statistic) => ({ + ...statistic, + value: 0, + })), + ); + + expect(result.current.error).toBeNull(); +}); + +it.each([ + { path: "/cohorts/", label: "Cohorts" }, + { path: "/cohorts/metadata", label: "Participants" }, + { path: "/cdm/variables", label: "Variables Mapped" }, + { path: "/cdm/modalities", label: "Compared Modalities" }, +])( + "preserves successful statistics when $label fails", + async ({ path, label }) => { + server.use( + http.get(`${TEST_API_URL}${path}`, () => + HttpResponse.json( + { detail: "Statistics unavailable" }, + { status: 503 }, + ), + ), + ); + + const { result } = setup(); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + expect(result.current.error?.message).toBe("Statistics unavailable"); + + expect(result.current.statistics).toEqual( + expectedStatistics.map((statistic) => ({ + ...statistic, + value: statistic.label === label ? null : statistic.value, + })), + ); + }, +); From 9bc40dd775eee46fdc5d8158436ad4304fd46d44 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 22:41:23 +0100 Subject: [PATCH 037/102] test(frontend): add cohort table hook tests --- .../cohorts/hooks/useCohortsTable.test.ts | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 frontend/src/features/cohorts/hooks/useCohortsTable.test.ts diff --git a/frontend/src/features/cohorts/hooks/useCohortsTable.test.ts b/frontend/src/features/cohorts/hooks/useCohortsTable.test.ts new file mode 100644 index 0000000..22ee853 --- /dev/null +++ b/frontend/src/features/cohorts/hooks/useCohortsTable.test.ts @@ -0,0 +1,77 @@ +// @vitest-environment jsdom + +import { act, renderHook } from "@testing-library/react"; +import { expect, it } from "vitest"; + +import type { CohortData } from "@/lib/api/cohorts"; +import { mockMetadata } from "@/test/mocks/handlers"; + +import { useCohortsTable } from "./useCohortsTable"; + +const cohorts: CohortData[] = [ + { + ...mockMetadata["Study A"], + cohort: "Study 10", + participants: 20, + }, + { + ...mockMetadata["Study A"], + cohort: "Study 2", + participants: 100, + }, + { + ...mockMetadata["Study B"], + cohort: "Study 1", + participants: null, + }, + { + ...mockMetadata["Study B"], + cohort: "Study 3", + participants: 0, + }, +]; + +it("sorts cohorts alphanumerically and uses stable row identifiers", () => { + const { result } = renderHook(() => useCohortsTable(cohorts)); + + expect(result.current.state.sorting).toEqual([{ id: "cohort", desc: false }]); + + expect(result.current.getRowModel().rows.map((row) => row.id)).toEqual([ + "Study 1", + "Study 2", + "Study 3", + "Study 10", + ]); +}); + +it.each([ + { desc: false, expected: [0, 20, 100, null] }, + { desc: true, expected: [100, 20, 0, null] }, +])("sorts participant counts with desc=$desc", ({ desc, expected }) => { + const { result } = renderHook(() => useCohortsTable(cohorts)); + + act(() => { + result.current.setSorting([{ id: "participants", desc }]); + }); + + expect( + result.current.getRowModel().rows.map((row) => row.original.participants), + ).toEqual(expected); +}); + +it("disables sorting for non-sortable columns", () => { + const { result } = renderHook(() => useCohortsTable(cohorts)); + + const unsortable = result.current + .getAllLeafColumns() + .filter((column) => !column.getCanSort()) + .map((column) => column.id); + + expect(unsortable).toEqual(["followUpInterval", "doi", "link"]); +}); + +it("handles empty cohort data", () => { + const { result } = renderHook(() => useCohortsTable([])); + + expect(result.current.getRowModel().rows).toEqual([]); +}); From c6d9c32dd96a252374ab030f7a024d7bc265ee69 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 22:42:47 +0100 Subject: [PATCH 038/102] test(frontend): add ranking table hook tests --- .../hooks/useRankingTable.test.ts | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 frontend/src/features/study-picker/hooks/useRankingTable.test.ts diff --git a/frontend/src/features/study-picker/hooks/useRankingTable.test.ts b/frontend/src/features/study-picker/hooks/useRankingTable.test.ts new file mode 100644 index 0000000..219b592 --- /dev/null +++ b/frontend/src/features/study-picker/hooks/useRankingTable.test.ts @@ -0,0 +1,97 @@ +// @vitest-environment jsdom + +import { renderHook } from "@testing-library/react"; +import { expect, it } from "vitest"; + +import type { Metadata } from "@/lib/api/cohorts"; +import { + mockMetadata, + mockRankings, + mockVariables, +} from "@/test/mocks/handlers"; + +import type { RankedCohort } from "../types"; +import { useRankingTable } from "./useRankingTable"; + +interface RankingProps { + rankings: readonly RankedCohort[]; + metadata: Metadata; + submittedVariables: readonly string[]; +} + +function setup( + initialProps: RankingProps = { + rankings: mockRankings, + metadata: mockMetadata, + submittedVariables: mockVariables, + }, +) { + return renderHook( + ({ rankings, metadata, submittedVariables }) => + useRankingTable(rankings, metadata, submittedVariables), + { initialProps }, + ); +} + +it("preserves ranking order and uses cohort names as row identifiers", () => { + const { result } = setup({ + rankings: mockRankings.toReversed(), + metadata: mockMetadata, + submittedVariables: mockVariables, + }); + + expect(result.current.getRowModel().rows).toMatchObject([ + { + id: "Study B", + original: { + rank: 1, + cohort: "Study B", + availableVariables: ["Age"], + color: "#059669", + }, + }, + { + id: "Study A", + original: { + rank: 2, + cohort: "Study A", + availableVariables: ["Age", "Motor score"], + color: "#2563eb", + }, + }, + ]); +}); + +it("updates table rows when ranking inputs change", () => { + const { result, rerender } = setup(); + + rerender({ + rankings: [mockRankings[0]], + metadata: {}, + submittedVariables: ["Age"], + }); + + expect(result.current.getRowModel().rows).toMatchObject([ + { + id: "Study A", + original: { + rank: 1, + cohort: "Study A", + availableVariables: ["Age"], + color: null, + accessLink: null, + longitudinalDataAvailable: null, + }, + }, + ]); +}); + +it("handles empty ranking results", () => { + const { result } = setup({ + rankings: [], + metadata: mockMetadata, + submittedVariables: mockVariables, + }); + + expect(result.current.getRowModel().rows).toEqual([]); +}); From 1a82cbcaa62526d4cad4c1632c46d1e79338fa47 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 22:46:39 +0100 Subject: [PATCH 039/102] test(frontend): add ECharts lifecycle hook tests --- frontend/src/hooks/useECharts.test.tsx | 180 +++++++++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 frontend/src/hooks/useECharts.test.tsx diff --git a/frontend/src/hooks/useECharts.test.tsx b/frontend/src/hooks/useECharts.test.tsx new file mode 100644 index 0000000..14bf5f8 --- /dev/null +++ b/frontend/src/hooks/useECharts.test.tsx @@ -0,0 +1,180 @@ +// @vitest-environment jsdom + +import { render, renderHook, screen } from "@testing-library/react"; +import type { EChartsCoreOption, EChartsType } from "echarts/core"; +import { expect, it, vi } from "vitest"; + +import { useECharts } from "./useECharts"; + +type ChartDouble = ReturnType; + +const initChart = vi.hoisted(() => vi.fn<() => ChartDouble>()); + +vi.mock("echarts/core", () => ({ + init: initChart, +})); + +const INITIAL_OPTIONS: EChartsCoreOption = { series: [] }; +const UPDATED_OPTIONS: EChartsCoreOption = { + title: { text: "Updated chart" }, +}; + +function createChart() { + return { + setOption: vi.fn(), + resize: vi.fn(), + isDisposed: vi.fn(() => false), + dispose: vi.fn(), + }; +} + +function setup() { + const chart = createChart(); + + initChart.mockReset().mockReturnValue(chart); + + const observe = vi.fn(); + const disconnect = vi.fn(); + + let notify: (() => void) | undefined; + + class MockResizeObserver implements ResizeObserver { + constructor(callback: ResizeObserverCallback) { + notify = () => callback([], this); + } + + observe = observe; + disconnect = disconnect; + unobserve = vi.fn(); + } + + vi.stubGlobal("ResizeObserver", MockResizeObserver); + + return { + chart, + observe, + disconnect, + notifyResize: () => { + if (!notify) { + throw new Error("ResizeObserver has not been initialized"); + } + + notify(); + }, + }; +} + +interface ChartProbeProps { + options: EChartsCoreOption; + enabled?: boolean; +} + +function ChartProbe({ options, enabled }: ChartProbeProps) { + const { containerRef } = useECharts(options, { enabled }); + + return
; +} + +it("does not initialize without a container", () => { + setup(); + + const { result } = renderHook(() => useECharts(INITIAL_OPTIONS)); + + expect(result.current.chartRef.current).toBeNull(); + expect(initChart).not.toHaveBeenCalled(); +}); + +it("initializes, updates, disables and recreates the chart", () => { + const { chart, observe, disconnect } = setup(); + + const { rerender, unmount } = render( + , + ); + + expect(initChart).not.toHaveBeenCalled(); + + rerender(); + + const container = screen.getByTestId("chart"); + + expect(initChart).toHaveBeenCalledExactlyOnceWith(container, undefined, { + renderer: "svg", + }); + + expect(observe).toHaveBeenCalledExactlyOnceWith(container); + + expect(chart.setOption).toHaveBeenCalledExactlyOnceWith(INITIAL_OPTIONS, { + notMerge: true, + }); + + rerender(); + + expect(initChart).toHaveBeenCalledTimes(1); + expect(chart.setOption).toHaveBeenCalledTimes(2); + expect(chart.setOption).toHaveBeenLastCalledWith(UPDATED_OPTIONS, { + notMerge: true, + }); + + rerender(); + + expect(chart.dispose).toHaveBeenCalledTimes(1); + expect(disconnect).toHaveBeenCalledTimes(1); + + const replacement = createChart(); + initChart.mockReturnValue(replacement); + + rerender(); + + expect(initChart).toHaveBeenCalledTimes(2); + expect(replacement.setOption).toHaveBeenCalledExactlyOnceWith( + UPDATED_OPTIONS, + { notMerge: true }, + ); + + unmount(); + + expect(replacement.dispose).toHaveBeenCalledTimes(1); + expect(chart.dispose).toHaveBeenCalledTimes(1); + expect(disconnect).toHaveBeenCalledTimes(2); +}); + +it("batches resize events and cancels pending work on unmount", () => { + vi.useFakeTimers(); + + const cancel = vi.spyOn(globalThis, "cancelAnimationFrame"); + const { chart, disconnect, notifyResize } = setup(); + + const { unmount } = render(); + + notifyResize(); + notifyResize(); + + expect(cancel).toHaveBeenCalledTimes(1); + expect(chart.resize).not.toHaveBeenCalled(); + + vi.advanceTimersToNextFrame(); + + expect(chart.resize).toHaveBeenCalledTimes(1); + + // Disposed charts must not be resized. + chart.isDisposed.mockReturnValue(true); + + notifyResize(); + vi.advanceTimersToNextFrame(); + + expect(chart.resize).toHaveBeenCalledTimes(1); + + // Pending resize work must be cancelled during cleanup. + chart.isDisposed.mockReturnValue(false); + + notifyResize(); + unmount(); + + expect(cancel).toHaveBeenCalledTimes(2); + expect(disconnect).toHaveBeenCalledTimes(1); + expect(chart.dispose).toHaveBeenCalledTimes(1); + + vi.advanceTimersByTime(32); + + expect(chart.resize).toHaveBeenCalledTimes(1); +}); From 8a98e7dd443e81134e55dd3c80012a6b7ca5b3e0 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 22:48:46 +0100 Subject: [PATCH 040/102] test(frontend): add mobile detection hook tests --- frontend/src/hooks/useIsMobile.test.ts | 78 ++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 frontend/src/hooks/useIsMobile.test.ts diff --git a/frontend/src/hooks/useIsMobile.test.ts b/frontend/src/hooks/useIsMobile.test.ts new file mode 100644 index 0000000..b9c3507 --- /dev/null +++ b/frontend/src/hooks/useIsMobile.test.ts @@ -0,0 +1,78 @@ +// @vitest-environment jsdom + +import { act, renderHook } from "@testing-library/react"; +import { createElement } from "react"; +import { renderToString } from "react-dom/server"; +import { expect, it, vi } from "vitest"; + +import { useIsMobile } from "./useIsMobile"; + +const MOBILE_QUERY = "(max-width: 639px)"; + +function setup(initialMatches = false) { + const media = Object.assign(new EventTarget(), { + matches: initialMatches, + media: MOBILE_QUERY, + }); + + const addListener = vi.spyOn(media, "addEventListener"); + const removeListener = vi.spyOn(media, "removeEventListener"); + + const matchMedia = vi.fn<(query: string) => typeof media>(() => media); + + vi.stubGlobal("matchMedia", matchMedia); + + return { + matchMedia, + addListener, + removeListener, + setMatches: (matches: boolean) => { + media.matches = matches; + media.dispatchEvent(new Event("change")); + }, + }; +} + +function MobileProbe() { + return useIsMobile() ? "mobile" : "desktop"; +} + +it.each([false, true])( + "returns the initial media query state: %s", + (matches) => { + const { matchMedia } = setup(matches); + const { result } = renderHook(useIsMobile); + + expect(result.current).toBe(matches); + expect(matchMedia).toHaveBeenCalledWith(MOBILE_QUERY); + }, +); + +it("responds to media query changes and removes its subscription", () => { + const { addListener, removeListener, setMatches } = setup(); + const { result, unmount } = renderHook(useIsMobile); + + expect(addListener).toHaveBeenCalledExactlyOnceWith( + "change", + expect.any(Function), + ); + + const listener = addListener.mock.calls[0][1]; + + act(() => setMatches(true)); + expect(result.current).toBe(true); + + act(() => setMatches(false)); + expect(result.current).toBe(false); + + unmount(); + + expect(removeListener).toHaveBeenCalledExactlyOnceWith("change", listener); +}); + +it("uses the desktop fallback during server-side rendering", () => { + const { matchMedia } = setup(true); + + expect(renderToString(createElement(MobileProbe))).toContain("desktop"); + expect(matchMedia).not.toHaveBeenCalled(); +}); From 8f58ec71677161a6d0e90faf47b25b8fe811265c Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 22:51:26 +0100 Subject: [PATCH 041/102] test(frontend): add color indicator component tests --- .../data-display/ColorIndicator.test.tsx | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 frontend/src/components/data-display/ColorIndicator.test.tsx diff --git a/frontend/src/components/data-display/ColorIndicator.test.tsx b/frontend/src/components/data-display/ColorIndicator.test.tsx new file mode 100644 index 0000000..3e80734 --- /dev/null +++ b/frontend/src/components/data-display/ColorIndicator.test.tsx @@ -0,0 +1,38 @@ +// @vitest-environment jsdom + +import { render } from "@testing-library/react"; +import { expect, it } from "vitest"; + +import { ColorIndicator } from "./ColorIndicator"; + +it("renders a decorative circular color indicator by default", () => { + const { container } = render( + , + ); + + const indicator = container.firstElementChild; + + expect(indicator).toHaveAttribute("aria-hidden", "true"); + expect(indicator).toHaveClass("rounded-full", "custom-class"); + expect(indicator).toHaveStyle({ + backgroundColor: "rgb(37, 99, 235)", + }); +}); + +it("supports square indicators", () => { + const { container } = render( + , + ); + + expect(container.firstElementChild).toHaveClass("rounded-sm"); + expect(container.firstElementChild).not.toHaveClass("rounded-full"); +}); + +it.each([undefined, null, ""])( + "renders nothing when the color is %s", + (color) => { + const { container } = render(); + + expect(container).toBeEmptyDOMElement(); + }, +); From b67ef8f5d59367fa7613c3809d1103a62920e91d Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 22:54:18 +0100 Subject: [PATCH 042/102] test(frontend): add empty state component tests --- .../components/feedback/EmptyState.test.tsx | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 frontend/src/components/feedback/EmptyState.test.tsx diff --git a/frontend/src/components/feedback/EmptyState.test.tsx b/frontend/src/components/feedback/EmptyState.test.tsx new file mode 100644 index 0000000..e17a74f --- /dev/null +++ b/frontend/src/components/feedback/EmptyState.test.tsx @@ -0,0 +1,51 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { expect, it, vi } from "vitest"; + +import { EmptyState } from "./EmptyState"; + +it("renders the message without optional content", () => { + render(); + + expect(screen.getByText("No data available")).toBeInTheDocument(); + expect(screen.queryByRole("button")).not.toBeInTheDocument(); +}); + +it("renders a rich description and custom class", () => { + const { container } = render( + + Try selecting another variable. + + } + className="custom-class" + />, + ); + + expect(screen.getByText("another variable")).toBeInTheDocument(); + expect(container.firstElementChild).toHaveClass("custom-class"); +}); + +it("renders an interactive action", async () => { + const user = userEvent.setup(); + const onAction = vi.fn<() => void>(); + + render( + + Change selection + + } + />, + ); + + await user.click(screen.getByRole("button", { name: "Change selection" })); + + expect(onAction).toHaveBeenCalledTimes(1); +}); From eed27d81ea416ef22fe805931f64a5f5093730c4 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 22:55:20 +0100 Subject: [PATCH 043/102] test(frontend): add error state component tests --- .../components/feedback/ErrorState.test.tsx | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 frontend/src/components/feedback/ErrorState.test.tsx diff --git a/frontend/src/components/feedback/ErrorState.test.tsx b/frontend/src/components/feedback/ErrorState.test.tsx new file mode 100644 index 0000000..4db7b14 --- /dev/null +++ b/frontend/src/components/feedback/ErrorState.test.tsx @@ -0,0 +1,65 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { expect, it, vi } from "vitest"; + +import { ErrorState } from "./ErrorState"; + +it("renders an accessible error without a retry action", () => { + render(); + + expect(screen.getByRole("alert")).toHaveTextContent("Could not load data"); + expect(screen.queryByRole("button")).not.toBeInTheDocument(); +}); + +it("renders additional error details and supports retrying", async () => { + const user = userEvent.setup(); + const onRetry = vi.fn<() => void>(); + + render( + +

Server unavailable

+
, + ); + + expect(screen.getByRole("alert")).toHaveTextContent("Request failed"); + expect(screen.getByText("Server unavailable")).toBeInTheDocument(); + + await user.click(screen.getByRole("button", { name: "Retry" })); + + expect(onRetry).toHaveBeenCalledTimes(1); +}); + +it("supports polite announcements, inverse styling and custom retry labels", async () => { + const user = userEvent.setup(); + const onRetry = vi.fn<() => void>(); + + const { container } = render( + +

Previously loaded data remains available.

+
, + ); + + const error = container.firstElementChild; + + expect(error).toHaveAttribute("aria-live", "polite"); + expect(error).toHaveClass("border-white/30", "custom-class"); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + + expect(screen.getByText("Statistics unavailable")).toBeInTheDocument(); + expect( + screen.getByText("Previously loaded data remains available."), + ).toBeInTheDocument(); + + await user.click(screen.getByRole("button", { name: "Retry refresh" })); + + expect(onRetry).toHaveBeenCalledTimes(1); +}); From 1e3c995ff93650cc4c5387a9c0b3d6a52c818ccb Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 22:56:34 +0100 Subject: [PATCH 044/102] test(frontend): add loading state component tests --- .../components/feedback/LoadingState.test.tsx | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 frontend/src/components/feedback/LoadingState.test.tsx diff --git a/frontend/src/components/feedback/LoadingState.test.tsx b/frontend/src/components/feedback/LoadingState.test.tsx new file mode 100644 index 0000000..da52653 --- /dev/null +++ b/frontend/src/components/feedback/LoadingState.test.tsx @@ -0,0 +1,29 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import { expect, it } from "vitest"; + +import { LoadingState } from "./LoadingState"; + +it("renders an accessible loading message with a decorative spinner", () => { + render(); + + const status = screen.getByRole("status"); + + expect(status).toHaveTextContent("Loading measurements..."); + expect(status.querySelector("svg")).toHaveAttribute("aria-hidden", "true"); +}); + +it("supports custom classes and updates the loading message", () => { + const { rerender } = render( + , + ); + + expect(screen.getByRole("status")).toHaveClass("custom-class"); + + rerender( + , + ); + + expect(screen.getByRole("status")).toHaveTextContent("Loading cohorts..."); +}); From 7e6c56dfb3318dcb39b4a2892325acce04f876c6 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 23:06:32 +0100 Subject: [PATCH 045/102] fix(frontend): preserve inherited combobox disabled state --- frontend/src/components/ui/combobox.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frontend/src/components/ui/combobox.tsx b/frontend/src/components/ui/combobox.tsx index 5a78826..c907cb7 100644 --- a/frontend/src/components/ui/combobox.tsx +++ b/frontend/src/components/ui/combobox.tsx @@ -63,7 +63,8 @@ function ComboboxInput({ return ( } + render={} + disabled={disabled} {...props} /> From a206fc73b392cfd1be4768937a057ac460884d27 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 23:06:36 +0100 Subject: [PATCH 046/102] test(frontend): add single-select combobox tests --- .../forms/SingleSelectCombobox.test.tsx | 164 ++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 frontend/src/components/forms/SingleSelectCombobox.test.tsx diff --git a/frontend/src/components/forms/SingleSelectCombobox.test.tsx b/frontend/src/components/forms/SingleSelectCombobox.test.tsx new file mode 100644 index 0000000..b825d95 --- /dev/null +++ b/frontend/src/components/forms/SingleSelectCombobox.test.tsx @@ -0,0 +1,164 @@ +// @vitest-environment jsdom + +import { render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import type { ComponentProps } from "react"; +import { beforeEach, expect, it, vi } from "vitest"; + +import { SingleSelectCombobox } from "./SingleSelectCombobox"; + +beforeEach(() => { + vi.stubGlobal("BASE_UI_ANIMATIONS_DISABLED", true); +}); + +function setup( + overrides: Partial> = {}, +) { + const user = userEvent.setup(); + const onValueChange = vi.fn<(value: string) => void>(); + + const props = { + id: "variable", + label: "Variable", + items: ["Age", "Motor score", "Study Visit"], + value: "", + onValueChange, + ...overrides, + }; + + const view = render(); + + return { + ...view, + props, + user, + onValueChange, + input: screen.getByRole("combobox", { name: "Variable" }), + }; +} + +it("searches and selects an option using a pointer", async () => { + const { user, input, onValueChange, rerender, props } = setup(); + + await user.type(input, "motor"); + + const option = await screen.findByRole("option", { + name: "Motor score", + }); + + expect(screen.queryByRole("option", { name: "Age" })).not.toBeInTheDocument(); + + await user.click(option); + + expect(onValueChange).toHaveBeenLastCalledWith("Motor score"); + + rerender(); + + expect(input).toHaveValue("Motor score"); +}); + +it("searches and selects an option using the keyboard", async () => { + const { user, input, onValueChange } = setup(); + + await user.type(input, "motor"); + + const option = await screen.findByRole("option", { + name: "Motor score", + }); + + await waitFor(() => { + expect(input).toHaveAttribute("aria-activedescendant", option.id); + }); + + await user.keyboard("{Enter}"); + + expect(onValueChange).toHaveBeenLastCalledWith("Motor score"); +}); + +it.each([ + { + isLoading: true, + placeholder: "Loading options...", + announcements: ["Loading available options."], + }, + { + isLoading: false, + placeholder: "No options available", + announcements: [], + }, +])( + "disables empty comboboxes with isLoading=$isLoading", + ({ isLoading, placeholder, announcements }) => { + const { input } = setup({ items: [], isLoading }); + + expect(input).toBeDisabled(); + expect(input).toHaveAttribute("placeholder", placeholder); + + expect( + screen.queryAllByRole("status").map((status) => status.textContent), + ).toEqual(announcements); + }, +); + +it("supports helper text, custom placeholders and empty search results", async () => { + const { user, input } = setup({ + placeholder: "Search variables", + description: "Select a variable to compare.", + emptyMessage: "No variables match.", + }); + + expect(input).toHaveAttribute("placeholder", "Search variables"); + expect(input).toHaveAccessibleDescription("Select a variable to compare."); + + await user.type(input, "nonexistent"); + + expect(await screen.findByText("No variables match.")).toBeInTheDocument(); + + expect(screen.queryByRole("option")).not.toBeInTheDocument(); +}); + +it.each([ + { hideLabel: false, buttonName: "Clear selection" }, + { hideLabel: true, buttonName: "Clear variable selection" }, +])( + "clears the selection with hideLabel=$hideLabel", + async ({ hideLabel, buttonName }) => { + const { user, input, onValueChange, rerender, props } = setup({ + value: "Age", + hideLabel, + }); + + expect(input).toHaveValue("Age"); + + await user.click(screen.getByRole("button", { name: buttonName })); + + expect(onValueChange).toHaveBeenLastCalledWith(""); + + rerender(); + + expect(input).toHaveValue(""); + expect( + screen.queryByRole("button", { name: buttonName }), + ).not.toBeInTheDocument(); + }, +); + +it("disables selection and clearing when explicitly disabled", () => { + const { input } = setup({ + value: "Age", + disabled: true, + }); + + expect(input).toBeDisabled(); + expect( + screen.getByRole("button", { name: "Clear selection" }), + ).toBeDisabled(); +}); + +it("keeps existing options available during loading", () => { + const { input } = setup({ isLoading: true }); + + expect(input).toBeEnabled(); + expect(input).toHaveAttribute("placeholder", "Search..."); + expect(screen.queryByRole("status")).not.toBeInTheDocument(); +}); From 11ba1561d1328f34e384a192436c638bc85db760 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 23:10:41 +0100 Subject: [PATCH 047/102] test(frontend): add multi-select combobox tests --- .../forms/MultiSelectCombobox.test.tsx | 182 ++++++++++++++++++ 1 file changed, 182 insertions(+) create mode 100644 frontend/src/components/forms/MultiSelectCombobox.test.tsx diff --git a/frontend/src/components/forms/MultiSelectCombobox.test.tsx b/frontend/src/components/forms/MultiSelectCombobox.test.tsx new file mode 100644 index 0000000..f05087e --- /dev/null +++ b/frontend/src/components/forms/MultiSelectCombobox.test.tsx @@ -0,0 +1,182 @@ +// @vitest-environment jsdom + +import { render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { useState, type ComponentProps } from "react"; +import { beforeEach, expect, it, vi } from "vitest"; + +import { MultiSelectCombobox } from "./MultiSelectCombobox"; + +type Props = ComponentProps; + +beforeEach(() => { + vi.stubGlobal("BASE_UI_ANIMATIONS_DISABLED", true); +}); + +function ControlledCombobox({ + value: initialValue, + onValueChange, + ...props +}: Props) { + const [value, setValue] = useState(initialValue); + + return ( + { + setValue(next); + onValueChange(next); + }} + /> + ); +} + +function setup(overrides: Partial = {}) { + const user = userEvent.setup(); + const onValueChange = vi.fn<(value: string[]) => void>(); + + const props: Props = { + id: "variables", + label: "Variables", + items: ["Age", "Motor score", "Study Visit"], + value: [], + onValueChange, + ...overrides, + }; + + render(); + + return { + user, + onValueChange, + input: screen.getByRole("combobox", { name: "Variables" }), + }; +} + +it("selects multiple options and keeps the dropdown open", async () => { + const { user, input, onValueChange } = setup(); + + await user.type(input, "age"); + + await user.click(await screen.findByRole("option", { name: "Age" })); + + expect(onValueChange).toHaveBeenLastCalledWith(["Age"]); + expect(input).toHaveAttribute("aria-expanded", "true"); + expect(screen.getByText("1 selected")).toBeInTheDocument(); + + await user.clear(input); + await user.type(input, "motor"); + + const option = await screen.findByRole("option", { + name: "Motor score", + }); + + await waitFor(() => { + expect(input).toHaveAttribute("aria-activedescendant", option.id); + }); + + await user.keyboard("{Enter}"); + + expect(onValueChange).toHaveBeenLastCalledWith(["Age", "Motor score"]); + + expect(screen.getByText("2 selected")).toBeInTheDocument(); + expect(input).toHaveAttribute("placeholder", "Add another..."); +}); + +it.each([false, true])( + "removes individual selections and clears all with hideLabel=%s", + async (hideLabel) => { + const { user, input, onValueChange } = setup({ + value: ["Age", "Motor score"], + hideLabel, + }); + + expect(screen.getByText("2 selected")).toBeInTheDocument(); + expect(input).toHaveAttribute("placeholder", "Add another..."); + + await user.click(screen.getByRole("button", { name: "Remove Age" })); + + expect(onValueChange).toHaveBeenLastCalledWith(["Motor score"]); + expect(screen.getByText("1 selected")).toBeInTheDocument(); + + expect( + screen.queryByRole("button", { name: "Remove Age" }), + ).not.toBeInTheDocument(); + + await user.click(screen.getByRole("button", { name: "Clear all" })); + + expect(onValueChange).toHaveBeenLastCalledWith([]); + + expect(screen.queryByText("1 selected")).not.toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "Clear all" }), + ).not.toBeInTheDocument(); + + expect(input).toHaveAttribute("placeholder", "Search..."); + }, +); + +it("supports helper text, custom placeholders and empty search results", async () => { + const { user, input } = setup({ + placeholder: "Search variables", + description: "Select variables to compare.", + emptyMessage: "No variables match.", + }); + + expect(input).toHaveAttribute("placeholder", "Search variables"); + expect(input).toHaveAccessibleDescription("Select variables to compare."); + + await user.type(input, "nonexistent"); + + expect(await screen.findByText("No variables match.")).toBeInTheDocument(); + + expect(screen.queryByRole("option")).not.toBeInTheDocument(); +}); + +it.each([ + { + isLoading: true, + placeholder: "Loading options...", + announcements: ["Loading available options."], + }, + { + isLoading: false, + placeholder: "No options available", + announcements: [], + }, +])( + "disables empty comboboxes with isLoading=$isLoading", + ({ isLoading, placeholder, announcements }) => { + const { input } = setup({ items: [], isLoading }); + + expect(input).toBeDisabled(); + expect(input).toHaveAttribute("placeholder", placeholder); + + expect( + screen.queryAllByRole("status").map((status) => status.textContent), + ).toEqual(announcements); + }, +); + +it("disables selection, removal and clearing when explicitly disabled", () => { + const { input } = setup({ + value: ["Age", "Motor score"], + disabled: true, + }); + + expect(input).toBeDisabled(); + expect(screen.getByRole("button", { name: "Remove Age" })).toBeDisabled(); + expect( + screen.getByRole("button", { name: "Remove Motor score" }), + ).toBeDisabled(); + expect(screen.getByRole("button", { name: "Clear all" })).toBeDisabled(); +}); + +it("keeps existing options available during loading", () => { + const { input } = setup({ isLoading: true }); + + expect(input).toBeEnabled(); + expect(input).toHaveAttribute("placeholder", "Search..."); + expect(screen.queryByRole("status")).not.toBeInTheDocument(); +}); From 578c422feb7554bf9b0427987448c485fcdef3aa Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 23:12:12 +0100 Subject: [PATCH 048/102] test(frontend): add page layout component tests --- frontend/src/components/layout/page.test.tsx | 79 ++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 frontend/src/components/layout/page.test.tsx diff --git a/frontend/src/components/layout/page.test.tsx b/frontend/src/components/layout/page.test.tsx new file mode 100644 index 0000000..a7beaaa --- /dev/null +++ b/frontend/src/components/layout/page.test.tsx @@ -0,0 +1,79 @@ +// @vitest-environment jsdom + +import { render, screen, within } from "@testing-library/react"; +import { expect, it } from "vitest"; + +import { PageHeader, PageLayout, PageSection } from "./page"; + +it("renders an accessible page structure", () => { + render( + + + Compare biomarker measurements across cohorts. + + + + + + , + ); + + const main = screen.getByRole("main"); + + expect(main).toHaveClass("custom-layout"); + + expect( + within(main).getByRole("heading", { + level: 1, + name: "Biomarkers", + }), + ).toBeInTheDocument(); + + expect(main).toHaveTextContent( + "Compare biomarker measurements across cohorts.", + ); + + const section = within(main).getByRole("region", { + name: "Select a biomarker", + }); + + expect(within(section).getByRole("heading", { level: 2 })).toHaveAttribute( + "id", + "selection", + ); + + expect( + within(section).getByRole("button", { name: "Select" }), + ).toBeInTheDocument(); + + expect(section).toHaveClass("max-w-2xl"); +}); + +it.each([ + { width: "form", expected: "max-w-2xl" }, + { width: "full", expected: "max-w-7xl" }, +] as const)("supports the $width section width", ({ width, expected }) => { + render( + + Compare selected cohorts. + + } + className="custom-section" + > + Measurement results + , + ); + + const section = screen.getByRole("region", { + name: "Results", + }); + + expect(section).toHaveClass(expected, "custom-section"); + expect(section).toHaveTextContent("Compare selected cohorts."); + expect(section).toHaveTextContent("Measurement results"); +}); From 4db9c1cf8daaa32b7a60517b75ba186ad298e918 Mon Sep 17 00:00:00 2001 From: Mehmet Can Ay Date: Mon, 30 Nov 2026 23:13:28 +0100 Subject: [PATCH 049/102] test(frontend): add footer component tests --- .../src/components/layout/Footer.test.tsx | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 frontend/src/components/layout/Footer.test.tsx diff --git a/frontend/src/components/layout/Footer.test.tsx b/frontend/src/components/layout/Footer.test.tsx new file mode 100644 index 0000000..bf4b005 --- /dev/null +++ b/frontend/src/components/layout/Footer.test.tsx @@ -0,0 +1,96 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { MemoryRouter, useLocation } from "react-router"; +import { expect, it, vi } from "vitest"; + +import { AnalyticsConsentContext } from "@/components/privacy/analytics-consent-context"; + +import { Footer } from "./Footer"; + +function LocationProbe() { + const { pathname } = useLocation(); + + return {pathname}; +} + +function setup(analyticsAvailable = true) { + const user = userEvent.setup(); + const openPreferences = vi.fn<() => void>(); + + render( + + +