Open-source personal finance manager. Self-hosted, privacy-first.
test(frontend): add React Testing Library and cover the critical paths (#793)
Tássio Noronha0a0acf44c97b
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 8b5c52fa..02ce5824 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -55,7 +55,7 @@ The same applies to issues. An issue produced by pointing a model at the reposit1. Create a branch from `main`: `git checkout -b feature/your-feature`2. Make your changes3. Run backend tests: `cd backend && uv sync --all-extras && uv run pytest` (Python 3.11+)-4. Run frontend lint: `cd frontend && npm run lint`+4. Run frontend checks: `cd frontend && npm run lint && npm test`5. Commit with a clear message (see below)6. Push your branch and open a Pull Request@@ -74,6 +74,14 @@ local and CI stay in sync.[prek](https://github.com/j178/prek) is a drop-in replacement for pre-commit:same `.pre-commit-config.yaml`, but a single binary with no Python bootstrap.+### Frontend tests++Vitest and Testing Library. Render through `renderWithProviders` from+`@/test/utils`, which wires up TanStack Query, the router and i18n, and import+with the `@/` alias rather than a relative path. Assert on what the user sees:+the rendered text, the disabled button, the error that appears on a failed+request.+### Adding a frontend dependency`frontend/.npmrc` never runs a package's install scripts, and asks npm to skipdiff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex adbeea8f..51eff562 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -39,6 +39,10 @@"devDependencies": {"@eslint/js": "^9.39.1","@tailwindcss/vite": "4.3.3",+ "@testing-library/dom": "10.4.1",+ "@testing-library/jest-dom": "7.0.1",+ "@testing-library/react": "16.3.3",+ "@testing-library/user-event": "14.6.6","@types/d3-sankey": "^0.12.5","@types/node": "^24.10.13","@types/react": "^19.2.7",@@ -50,6 +54,7 @@"eslint-plugin-react-hooks": "^7.0.1","eslint-plugin-react-refresh": "^0.4.24","globals": "^17.0.0",+ "jsdom": "30.0.1","shadcn": "^4.0.0","tailwindcss": "4.3.3","tw-animate-css": "^1.4.0",@@ -59,6 +64,66 @@"vitest": "^4.1.8"}},+ "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/@asamuzakjp/css-color": {+ "version": "6.0.7",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-6.0.7.tgz",+ "integrity": "sha512-vC/bk1Lz7Tn/EfU9/apOTBk80/8dyGyWMowPoV1tJ52muDGsDqt2HPT2klrFUiY60MQmQv9q8yIht15JnBgDGw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@csstools/css-calc": "^3.3.0",+ "@csstools/css-color-parser": "^4.1.10",+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0",+ "lru-cache": "^11.5.2"+ },+ "engines": {+ "node": "^22.13.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": {+ "version": "11.5.2",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz",+ "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==",+ "dev": true,+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": "20 || >=22"+ }+ },+ "node_modules/@asamuzakjp/dom-selector": {+ "version": "8.3.2",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-8.3.2.tgz",+ "integrity": "sha512-93Z1N+BQNXysodoicpOIyNh2drHfz/CTf9nnT0FEx72GJcIiwgydD7tGAr78j41LsYn3hlRn+LdGPuBLn1Bl8Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "bidi-js": "^1.0.3",+ "css-tree": "^3.2.1",+ "is-potential-custom-element-name": "^1.0.1",+ "lru-cache": "^11.5.2"+ },+ "engines": {+ "node": "^22.13.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/dom-selector/node_modules/lru-cache": {+ "version": "11.5.2",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz",+ "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==",+ "dev": true,+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": "20 || >=22"+ }+ },"node_modules/@babel/code-frame": {"version": "7.29.0","resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",@@ -501,6 +566,159 @@"node": ">=6.9.0"}},+ "node_modules/@bramus/specificity": {+ "version": "2.4.2",+ "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz",+ "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "css-tree": "^3.0.0"+ },+ "bin": {+ "specificity": "bin/cli.js"+ }+ },+ "node_modules/@csstools/color-helpers": {+ "version": "6.1.1",+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.1.tgz",+ "integrity": "sha512-gLNsunvwf3mCi5u5o46/Z/JcJMnhbHSaZ69rkgPzNM3J4s8hWwpPUQB6/tt0EDFyCiWzxANlx+2LJwpYj4zS1w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "engines": {+ "node": ">=20.19.0"+ }+ },+ "node_modules/@csstools/css-calc": {+ "version": "3.3.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.3.0.tgz",+ "integrity": "sha512-c5ihYsPkdG6JCkU2zTMm4+k6r7RXuGxtWYhu5DHMIiF1FHzrfmHL5so11AoFpUv/tu61xfcmT4AmKoFfMPoqdQ==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-color-parser": {+ "version": "4.2.2",+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.2.tgz",+ "integrity": "sha512-3QKjR/vxyjcSXBLgb6lP0S3MGdvwbmqSsvLPbYdVORqPDc8FX1HAJ0Spk38bxaRXgvENTA47tlhhbb5Z2e8hEg==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@csstools/color-helpers": "^6.1.1",+ "@csstools/css-calc": "^3.3.0"+ },+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-parser-algorithms": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz",+ "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-syntax-patches-for-csstree": {+ "version": "1.1.10",+ "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.10.tgz",+ "integrity": "sha512-xBja6gaAaH2R2c7eNyl0TY4dhnnZ2uhj+KXpLdEQ6M/wuk9bYFZM8wY0ykw3VO4TgEJ56KGlerXS/9KBKVR/Cg==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "peerDependencies": {+ "css-tree": "^3.2.1"+ },+ "peerDependenciesMeta": {+ "css-tree": {+ "optional": true+ }+ }+ },+ "node_modules/@csstools/css-tokenizer": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz",+ "integrity": "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ }+ },"node_modules/@dotenvx/dotenvx": {"version": "1.52.0","resolved": "https://registry.npmjs.org/@dotenvx/dotenvx/-/dotenvx-1.52.0.tgz",@@ -839,6 +1057,24 @@"node": "^18.18.0 || ^20.9.0 || >=21.1.0"}},+ "node_modules/@exodus/bytes": {+ "version": "1.15.1",+ "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz",+ "integrity": "sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==",+ "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.7.4","resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.4.tgz",@@ -3053,9 +3289,6 @@"arm64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -3073,9 +3306,6 @@"arm64"],"dev": true,- "libc": [- "musl"- ],"license": "MIT","optional": true,"os": [@@ -3093,9 +3323,6 @@"ppc64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -3113,9 +3340,6 @@"s390x"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -3133,9 +3357,6 @@"x64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -3153,9 +3374,6 @@"x64"],"dev": true,- "libc": [- "musl"- ],"license": "MIT","optional": true,"os": [@@ -3388,9 +3606,6 @@"arm64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -3408,9 +3623,6 @@"arm64"],"dev": true,- "libc": [- "musl"- ],"license": "MIT","optional": true,"os": [@@ -3428,9 +3640,6 @@"x64"],"dev": true,- "libc": [- "glibc"- ],"license": "MIT","optional": true,"os": [@@ -3448,9 +3657,6 @@"x64"],"dev": true,- "libc": [- "musl"- ],"license": "MIT","optional": true,"os": [@@ -3565,6 +3771,114 @@"react": "^18 || ^19"}},+ "node_modules/@testing-library/dom": {+ "version": "10.4.1",+ "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz",+ "integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==",+ "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/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/@testing-library/jest-dom": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-7.0.1.tgz",+ "integrity": "sha512-oMDTC3oA+6CXSO2JZnvOI7CA6oVub6kij5ggk9ohwye5slmkwxYDXcPOVxgMw/RQlticjtO0C1RZkR97HgrWMw==",+ "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": ">= 0.32"+ },+ "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/user-event": {+ "version": "14.6.6",+ "resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.6.tgz",+ "integrity": "sha512-Jbs9FpkkIDw8FgSc6kOVsOv8JuuqGAL7J4X1oot77JxAoDlkNn2GRkd0aYRVuQ+pVQAiHWVkE4rX/dkF5fBiCw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12",+ "npm": ">=6"+ },+ "peerDependencies": {+ "@testing-library/dom": ">=7.21.4"+ }+ },"node_modules/@ts-morph/common": {"version": "0.27.0","resolved": "https://registry.npmjs.org/@ts-morph/common/-/common-0.27.0.tgz",@@ -3616,6 +3930,13 @@"url": "https://github.com/sponsors/isaacs"}},+ "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/chai": {"version": "5.2.3","resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",@@ -5062,6 +5383,16 @@"zalgo-promise": "^1"}},+ "node_modules/bidi-js": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz",+ "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "require-from-string": "^2.0.2"+ }+ },"node_modules/body-parser": {"version": "2.2.2","resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz",@@ -5590,6 +5921,27 @@"node": ">= 8"}},+ "node_modules/css-tree": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz",+ "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "mdn-data": "2.27.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"+ }+ },+ "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/cssesc": {"version": "3.0.0","resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",@@ -5777,6 +6129,35 @@"dev": true,"license": "BSD-2-Clause"},+ "node_modules/data-urls": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz",+ "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "whatwg-mimetype": "^5.0.0",+ "whatwg-url": "^16.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/data-urls/node_modules/whatwg-url": {+ "version": "16.0.1",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz",+ "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.11.0",+ "tr46": "^6.0.0",+ "webidl-conversions": "^8.0.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },"node_modules/data-view-buffer": {"version": "1.0.2","resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz",@@ -5858,6 +6239,13 @@}}},+ "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/decimal.js-light": {"version": "2.5.1","resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz",@@ -6055,6 +6443,13 @@"node": ">=0.3.1"}},+ "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/dotenv": {"version": "17.3.1","resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.3.1.tgz",@@ -6145,6 +6540,19 @@"node": ">=10.13.0"}},+ "node_modules/entities": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz",+ "integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=20.19.0"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },"node_modules/env-paths": {"version": "2.2.1","resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz",@@ -7513,6 +7921,19 @@"node": ">=16.9.0"}},+ "node_modules/html-encoding-sniffer": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz",+ "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.6.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },"node_modules/html-parse-stringify": {"version": "3.0.1","resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-3.0.1.tgz",@@ -7667,6 +8088,16 @@"node": ">=0.8.19"}},+ "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/inherits": {"version": "2.0.4","resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",@@ -8108,6 +8539,13 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "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/is-promise": {"version": "4.0.0","resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",@@ -8369,6 +8807,67 @@"js-yaml": "bin/js-yaml.js"}},+ "node_modules/jsdom": {+ "version": "30.0.1",+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.0.1.tgz",+ "integrity": "sha512-52v7mUVUfNQVYYqE1lcdaymWL0njO7lTLUog6ZvW2U5KsbiLk/GnZlVJ+qx0xfNJZ6Gn+KSpPNE52vurbxZwrA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/css-color": "^6.0.5",+ "@asamuzakjp/dom-selector": "^8.3.0",+ "@bramus/specificity": "^2.4.2",+ "@csstools/css-syntax-patches-for-csstree": "^1.1.7",+ "@exodus/bytes": "^1.15.1",+ "css-tree": "^3.2.1",+ "data-urls": "^7.0.0",+ "decimal.js": "^10.6.0",+ "html-encoding-sniffer": "^6.0.0",+ "is-potential-custom-element-name": "^1.0.1",+ "lru-cache": "^11.5.2",+ "parse5": "^8.0.1",+ "saxes": "^6.0.0",+ "symbol-tree": "^3.2.4",+ "tough-cookie": "^6.0.2",+ "undici": "^8.9.0",+ "w3c-xmlserializer": "^5.0.0",+ "webidl-conversions": "^8.0.1",+ "whatwg-mimetype": "^5.0.0",+ "whatwg-url": "^17.1.0",+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": "^22.22.2 || ^24.15.0 || >=26.0.0"+ },+ "peerDependencies": {+ "canvas": "^3.2.3"+ },+ "peerDependenciesMeta": {+ "canvas": {+ "optional": true+ }+ }+ },+ "node_modules/jsdom/node_modules/lru-cache": {+ "version": "11.5.2",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz",+ "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==",+ "dev": true,+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": "20 || >=22"+ }+ },+ "node_modules/jsdom/node_modules/undici": {+ "version": "8.10.1",+ "resolved": "https://registry.npmjs.org/undici/-/undici-8.10.1.tgz",+ "integrity": "sha512-YQ3WlbqjYMmNpdvDH64jAgLjxuAR9+649calDWhbshYaeQGO2bR4nI94ORJmwI3J9YhoKQnpyGOK+0zlWS5N5Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=22.19.0"+ }+ },"node_modules/jsesc": {"version": "3.1.0","resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",@@ -8656,9 +9155,6 @@"arm64"],"dev": true,- "libc": [- "glibc"- ],"license": "MPL-2.0","optional": true,"os": [@@ -8680,9 +9176,6 @@"arm64"],"dev": true,- "libc": [- "musl"- ],"license": "MPL-2.0","optional": true,"os": [@@ -8704,9 +9197,6 @@"x64"],"dev": true,- "libc": [- "glibc"- ],"license": "MPL-2.0","optional": true,"os": [@@ -8728,9 +9218,6 @@"x64"],"dev": true,- "libc": [- "musl"- ],"license": "MPL-2.0","optional": true,"os": [@@ -8888,6 +9375,16 @@"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"}},+ "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": "0.30.21","resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",@@ -9199,6 +9696,13 @@"url": "https://opencollective.com/unified"}},+ "node_modules/mdn-data": {+ "version": "2.27.1",+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",+ "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",+ "dev": true,+ "license": "CC0-1.0"+ },"node_modules/media-typer": {"version": "1.1.0","resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",@@ -9873,6 +10377,16 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "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/minimatch": {"version": "3.1.4","resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.4.tgz",@@ -10343,6 +10857,19 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/parse5": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",+ "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "entities": "^8.0.0"+ },+ "funding": {+ "url": "https://github.com/inikulin/parse5?sponsor=1"+ }+ },"node_modules/parseurl": {"version": "1.3.3","resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",@@ -10535,6 +11062,51 @@"node": ">= 0.8.0"}},+ "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/pretty-format/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/pretty-format/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/pretty-format/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/pretty-ms": {"version": "9.3.0","resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-9.3.0.tgz",@@ -11058,6 +11630,20 @@"react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"}},+ "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/redux": {"version": "5.0.1","resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",@@ -11398,6 +11984,19 @@"dev": true,"license": "MIT"},+ "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.27.0","resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",@@ -11988,6 +12587,19 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "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/strip-json-comments": {"version": "3.1.1","resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",@@ -12032,6 +12644,13 @@"node": ">=8"}},+ "node_modules/symbol-tree": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",+ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/tailwind-merge": {"version": "3.5.0","resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.5.0.tgz",@@ -12113,6 +12732,26 @@"node": ">=14.0.0"}},+ "node_modules/tldts": {+ "version": "7.4.11",+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.11.tgz",+ "integrity": "sha512-aBiNayCfTQxuIJBm06M+xR14cYaYlDlSXZbgsnKzKNxDKUVq7KFwTjwBSsb7m9Y5xO8WfPnBc63WaYFMTGlvqw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tldts-core": "^7.4.11"+ },+ "bin": {+ "tldts": "bin/cli.js"+ }+ },+ "node_modules/tldts-core": {+ "version": "7.4.11",+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.11.tgz",+ "integrity": "sha512-CW3WN2rIIE/Of21mulhgnGOwoDyEFNygyIBOONSdyAuSATgMMUCpLeUlB+E8sAwA5xRV9hYPl+kyZ9citHCaKg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/to-regex-range": {"version": "5.0.1","resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",@@ -12136,6 +12775,32 @@"node": ">=0.6"}},+ "node_modules/tough-cookie": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz",+ "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "tldts": "^7.0.5"+ },+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/tr46": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz",+ "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "punycode": "^2.3.1"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/trim-lines": {"version": "3.0.1","resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",@@ -12934,9 +13599,6 @@"arm64"],"dev": true,- "libc": [- "glibc"- ],"license": "MPL-2.0","optional": true,"os": [@@ -12958,9 +13620,6 @@"arm64"],"dev": true,- "libc": [- "musl"- ],"license": "MPL-2.0","optional": true,"os": [@@ -12982,9 +13641,6 @@"x64"],"dev": true,- "libc": [- "glibc"- ],"license": "MPL-2.0","optional": true,"os": [@@ -13006,9 +13662,6 @@"x64"],"dev": true,- "libc": [- "musl"- ],"license": "MPL-2.0","optional": true,"os": [@@ -13163,6 +13816,54 @@"node": ">=0.10.0"}},+ "node_modules/w3c-xmlserializer": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",+ "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "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.1.0",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.1.0.tgz",+ "integrity": "sha512-3GeworPmc2ZfEEHP7lEbUfBX/L75wdEsi0rLNhXcXxnoN5jyq0SL5gCy06SGW2cyTIZdTvWIDQNQoza++vKeaw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.15.1",+ "tr46": "^6.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",@@ -13319,6 +14020,23 @@"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/yallist": {"version": "3.1.1","resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex a25fa03d..d5c8a9b1 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -44,6 +44,10 @@"devDependencies": {"@eslint/js": "^9.39.1","@tailwindcss/vite": "4.3.3",+ "@testing-library/dom": "10.4.1",+ "@testing-library/jest-dom": "7.0.1",+ "@testing-library/react": "16.3.3",+ "@testing-library/user-event": "14.6.6","@types/d3-sankey": "^0.12.5","@types/node": "^24.10.13","@types/react": "^19.2.7",@@ -55,6 +59,7 @@"eslint-plugin-react-hooks": "^7.0.1","eslint-plugin-react-refresh": "^0.4.24","globals": "^17.0.0",+ "jsdom": "30.0.1","shadcn": "^4.0.0","tailwindcss": "4.3.3","tw-animate-css": "^1.4.0",diff --git a/frontend/src/components/admin-route.test.tsx b/frontend/src/components/admin-route.test.tsxnew file mode 100644index 00000000..2cdbf4ea--- /dev/null+++ b/frontend/src/components/admin-route.test.tsx@@ -0,0 +1,84 @@+import { describe, expect, it, vi } from 'vitest'+import { screen } from '@testing-library/react'+import { Route, Routes } from 'react-router-dom'++import { AdminRoute } from '@/components/admin-route'+import { renderWithProviders } from '@/test/utils'++const useAuth = vi.hoisted(() => vi.fn())+vi.mock('@/contexts/auth-context', () => ({ useAuth }))++function renderGuard() {+ return renderWithProviders(+ <Routes>+ <Route path="/" element={<div>home</div>} />+ <Route+ path="/admin"+ element={+ <AdminRoute>+ <div>admin settings</div>+ </AdminRoute>+ }+ />+ </Routes>,+ { route: '/admin' },+ )+}++describe('AdminRoute', () => {+ it('renders for a superuser', () => {+ useAuth.mockReturnValue({+ token: 'jwt',+ user: { is_superuser: true },+ isLoading: false,+ })++ renderGuard()++ expect(screen.getByText('admin settings')).toBeInTheDocument()+ })++ it('sends a signed-in non-admin home', () => {+ // Hiding the nav link is not enough: the URL is still typeable.+ useAuth.mockReturnValue({+ token: 'jwt',+ user: { is_superuser: false },+ isLoading: false,+ })++ renderGuard()++ expect(screen.getByText('home')).toBeInTheDocument()+ expect(screen.queryByText('admin settings')).not.toBeInTheDocument()+ })++ it('sends an anonymous visitor home', () => {+ useAuth.mockReturnValue({ token: null, user: null, isLoading: false })++ renderGuard()++ expect(screen.getByText('home')).toBeInTheDocument()+ })++ it('treats a missing user object as not an admin', () => {+ useAuth.mockReturnValue({ token: 'jwt', user: null, isLoading: false })++ renderGuard()++ // Assert the redirect landed, not just that the page is absent: a guard+ // that rendered nothing at all would satisfy the weaker check while the+ // user stared at a blank /admin.+ expect(screen.getByText('home')).toBeInTheDocument()+ expect(screen.queryByText('admin settings')).not.toBeInTheDocument()+ })++ it('shows a loading indicator while the session resolves', () => {+ useAuth.mockReturnValue({ token: 'jwt', user: null, isLoading: true })++ const { container } = renderGuard()++ expect(container.querySelector('.animate-spin')).toBeInTheDocument()+ expect(screen.queryByText('admin settings')).not.toBeInTheDocument()+ expect(screen.queryByText('home')).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/components/agents-route.test.tsx b/frontend/src/components/agents-route.test.tsxnew file mode 100644index 00000000..e866f23a--- /dev/null+++ b/frontend/src/components/agents-route.test.tsx@@ -0,0 +1,59 @@+import { describe, expect, it, vi } from 'vitest'+import { screen } from '@testing-library/react'+import { Route, Routes } from 'react-router-dom'++import { AgentsRoute } from '@/components/agents-route'+import { renderWithProviders } from '@/test/utils'++const useFeatureFlags = vi.hoisted(() => vi.fn())+vi.mock('@/hooks/use-feature-flags', () => ({ useFeatureFlags }))++function renderGuard() {+ return renderWithProviders(+ <Routes>+ <Route path="/" element={<div>home</div>} />+ <Route+ path="/agents"+ element={+ <AgentsRoute>+ <div>agents page</div>+ </AgentsRoute>+ }+ />+ </Routes>,+ { route: '/agents' },+ )+}++describe('AgentsRoute', () => {+ it('renders the page when the server has agents enabled', () => {+ useFeatureFlags.mockReturnValue({ agentsEnabled: true, isLoading: false })++ renderGuard()++ expect(screen.getByText('agents page')).toBeInTheDocument()+ })++ it('sends the user home when AGENTS_ENABLED is off', () => {+ // Agents is opt-in. A deployment that never enabled it must not render a+ // management page whose every API call would 404.+ useFeatureFlags.mockReturnValue({ agentsEnabled: false, isLoading: false })++ renderGuard()++ expect(screen.getByText('home')).toBeInTheDocument()+ expect(screen.queryByText('agents page')).not.toBeInTheDocument()+ })++ it('shows a loading indicator rather than assuming the flag is off', () => {+ useFeatureFlags.mockReturnValue({ agentsEnabled: false, isLoading: true })++ const { container } = renderGuard()++ // Without the spinner assertion this passes on a guard that renders+ // nothing, which is a blank screen rather than a wait.+ expect(container.querySelector('.animate-spin')).toBeInTheDocument()+ expect(screen.queryByText('home')).not.toBeInTheDocument()+ expect(screen.queryByText('agents page')).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/components/category-icon.test.tsx b/frontend/src/components/category-icon.test.tsxnew file mode 100644index 00000000..1d963355--- /dev/null+++ b/frontend/src/components/category-icon.test.tsx@@ -0,0 +1,80 @@+import { describe, expect, it } from 'vitest'+import { screen } from '@testing-library/react'++import { CategoryIcon } from '@/components/category-icon'+import { renderWithProviders } from '@/test/utils'++describe('CategoryIcon', () => {+ it('renders the icon it was asked for', () => {+ // Asserting only that an svg exists would also pass on the fallback,+ // which is the failure this test is here to catch. Lucide stamps the+ // icon name into the class list, so pin that.+ const { container } = renderWithProviders(+ <CategoryIcon icon="shopping-cart" color="#22c55e" />,+ )++ expect(container.querySelector('svg')).toHaveClass('lucide-shopping-cart')+ })++ it('renders an emoji icon as text, for categories saved before the icon set', () => {+ renderWithProviders(<CategoryIcon icon="🍔" color="#f97316" />)++ expect(screen.getByText('🍔')).toBeInTheDocument()+ })++ it('falls back to a placeholder icon for an unknown name', () => {+ // A renamed icon in a future lucide release must not blank the row.+ const { container } = renderWithProviders(+ <CategoryIcon icon="not-a-real-icon" color="#22c55e" />,+ )++ // CircleHelp renders as circle-question-mark: lucide renamed the icon and+ // kept the old export as an alias.+ expect(container.querySelector('svg')).toHaveClass(+ 'lucide-circle-question-mark',+ )+ })++ it('survives a category with no icon or colour at all', () => {+ const { container } = renderWithProviders(+ <CategoryIcon icon={null} color={null} />,+ )++ expect(container.querySelector('svg')).toBeInTheDocument()+ expect(container.firstElementChild).toHaveStyle({+ backgroundColor: 'rgb(107, 114, 128)',+ })+ })++ it('paints the category colour as the background', () => {+ const { container } = renderWithProviders(+ <CategoryIcon icon="shopping-cart" color="#22c55e" />,+ )++ expect(container.firstElementChild).toHaveStyle({+ backgroundColor: 'rgb(34, 197, 94)',+ })+ })++ it('grows with the requested size', () => {+ const { container: small } = renderWithProviders(+ <CategoryIcon icon="shopping-cart" color="#22c55e" size="xs" />,+ )+ expect(small.firstElementChild).toHaveClass('w-4', 'h-4')++ const { container: large } = renderWithProviders(+ <CategoryIcon icon="shopping-cart" color="#22c55e" size="xl" />,+ )+ expect(large.firstElementChild).toHaveClass('w-11', 'h-11')+ })++ it('never shrinks inside a flex row', () => {+ // Category icons sit next to variable-length names in the transaction+ // list; without shrink-0 a long payee squashes the icon.+ const { container } = renderWithProviders(+ <CategoryIcon icon="shopping-cart" color="#22c55e" />,+ )++ expect(container.firstElementChild).toHaveClass('shrink-0')+ })+})diff --git a/frontend/src/components/components.contract.test.ts b/frontend/src/components/components.contract.test.tsnew file mode 100644index 00000000..e8a229b5--- /dev/null+++ b/frontend/src/components/components.contract.test.ts@@ -0,0 +1,50 @@+/**+ * Evaluates every component module in the tree.+ *+ * Most of these are pulled in by a lazily-loaded page, so a module that+ * throws on import does not fail the build and does not fail any test that+ * happens not to touch it. The blast radius is whoever opens the screen.+ * Importing all of them costs little and catches the whole class: a circular+ * import that resolves to undefined, a top-level call into a browser API, a+ * barrel that lost an export in a rename.+ *+ * The assertion is deliberately weak. This file is a smoke detector, not a+ * behaviour suite: the moment it starts asserting on rendering, it becomes+ * something contributors have to maintain rather than something that quietly+ * protects them.+ */+import { describe, expect, it } from 'vitest'++const modules = import.meta.glob('@/components/**/*.tsx', {+ eager: false,+}) as Record<string, () => Promise<Record<string, unknown>>>++const paths = Object.keys(modules)+ .filter((path) => !path.includes('.test.'))+ .sort()++describe('component modules', () => {+ it('finds the component tree', () => {+ // If a refactor moves components elsewhere, this suite would silently+ // pass over an empty list.+ expect(paths.length).toBeGreaterThan(50)+ })++ for (const path of paths) {+ const name = path.replace(/^.*\/components\//, '')++ it(`${name} evaluates and exports a component`, async () => {+ const module = await modules[path]()++ // A plain component is a function; one wrapped in memo, forwardRef or+ // lazy is an object carrying $$typeof. Both are renderable, and this+ // has to accept either or it fails on the wrapped ones for no reason.+ const components = Object.values(module).filter(+ (value) =>+ typeof value === 'function' ||+ (typeof value === 'object' && value !== null && '$$typeof' in value),+ )+ expect(components.length).toBeGreaterThan(0)+ })+ }+})diff --git a/frontend/src/components/currency-select.test.tsx b/frontend/src/components/currency-select.test.tsxnew file mode 100644index 00000000..bcdbfb86--- /dev/null+++ b/frontend/src/components/currency-select.test.tsx@@ -0,0 +1,101 @@+import { useState } from 'react'+import { describe, expect, it, vi } from 'vitest'+import { screen } from '@testing-library/react'++import { CURRENCIES, CurrencySelect } from '@/components/currency-select'+import { renderWithProviders } from '@/test/utils'++describe('CURRENCIES', () => {+ it('has no duplicate codes', () => {+ const codes = CURRENCIES.map((c) => c.code)+ expect(new Set(codes).size).toBe(codes.length)+ })++ it('gives every entry a flag and a symbol', () => {+ // A blank cell in the dropdown is how a half-added currency shows up.+ for (const { code, flag, symbol } of CURRENCIES) {+ expect(code, `${code} code`).toMatch(/^[A-Z]{3}$/)+ expect(flag, `${code} flag`).not.toBe('')+ expect(symbol, `${code} symbol`).not.toBe('')+ }+ })++ it('includes the two currencies the product treats as first class', () => {+ const codes = CURRENCIES.map((c) => c.code)+ expect(codes).toContain('USD')+ expect(codes).toContain('BRL')+ })++ it('formats every listed currency without throwing', () => {+ // Intl rejects a code it does not know, and this list feeds the setup+ // screen where a throw would block the whole first-run flow.+ for (const { code } of CURRENCIES) {+ expect(() =>+ new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: code,+ }).format(1),+ ).not.toThrow()+ }+ })+})++describe('CurrencySelect', () => {+ it('shows the current selection', () => {+ renderWithProviders(<CurrencySelect value="BRL" onChange={vi.fn()} />)++ expect(screen.getByRole('combobox')).toHaveTextContent('BRL')+ })++ it('lists every supported currency when opened', async () => {+ const { user } = renderWithProviders(+ <CurrencySelect value="USD" onChange={vi.fn()} />,+ )++ await user.click(screen.getByRole('combobox'))++ const options = await screen.findAllByRole('option')+ expect(options).toHaveLength(CURRENCIES.length)+ })++ it('reports the chosen code', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <CurrencySelect value="USD" onChange={onChange} />,+ )++ await user.click(screen.getByRole('combobox'))+ await user.click(await screen.findByRole('option', { name: /BRL/ }))++ expect(onChange).toHaveBeenCalledWith('BRL')+ })++ it('shows the new currency once the parent commits it', async () => {+ // The callback firing is only half of it. A select that reports BRL and+ // keeps displaying USD looks broken to the user, and asserting on the+ // mock alone would not notice.+ function Controlled() {+ const [value, setValue] = useState('USD')+ return <CurrencySelect value={value} onChange={setValue} />+ }++ const { user } = renderWithProviders(<Controlled />)+ expect(screen.getByRole('combobox')).toHaveTextContent('USD')++ await user.click(screen.getByRole('combobox'))+ await user.click(await screen.findByRole('option', { name: /BRL/ }))++ expect(screen.getByRole('combobox')).toHaveTextContent('BRL')+ })++ it('takes an id so a label can point at it', () => {+ renderWithProviders(+ <>+ <label htmlFor="currency">Currency</label>+ <CurrencySelect id="currency" value="USD" onChange={vi.fn()} />+ </>,+ )++ expect(screen.getByLabelText('Currency')).toBeInTheDocument()+ })+})diff --git a/frontend/src/components/delete-confirmation-dialog.test.tsx b/frontend/src/components/delete-confirmation-dialog.test.tsxnew file mode 100644index 00000000..cbdc550a--- /dev/null+++ b/frontend/src/components/delete-confirmation-dialog.test.tsx@@ -0,0 +1,155 @@+import { describe, expect, it, vi } from 'vitest'+import { screen, waitFor } from '@testing-library/react'++import { DeleteConfirmationDialog } from '@/components/delete-confirmation-dialog'+import { renderWithProviders, t } from '@/test/utils'++const baseProps = {+ open: true,+ title: 'Delete category',+ description: 'Groceries will be removed from 12 transactions.',+ isPending: false,+ onClose: vi.fn(),+ onConfirm: vi.fn(),+}++describe('DeleteConfirmationDialog', () => {+ it('renders nothing while closed', () => {+ renderWithProviders(+ <DeleteConfirmationDialog {...baseProps} open={false} />,+ )++ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ })++ it('shows the caller-supplied title and description', () => {+ renderWithProviders(<DeleteConfirmationDialog {...baseProps} />)++ expect(screen.getByRole('dialog')).toBeInTheDocument()+ expect(screen.getByText('Delete category')).toBeInTheDocument()+ expect(+ screen.getByText('Groceries will be removed from 12 transactions.'),+ ).toBeInTheDocument()+ })++ it('labels its actions with the shipped copy', () => {+ // Deliberately the literal English, not t('common.cancel'). Looking the+ // label up through the same key the component uses makes the assertion+ // circular: it would still pass if the key resolved to the raw key+ // string, which is exactly how a missing translation renders.+ renderWithProviders(<DeleteConfirmationDialog {...baseProps} />)++ expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /Delete/ })).toBeInTheDocument()++ // And the keys really are the ones the component reads.+ expect(t('common.cancel')).toBe('Cancel')+ expect(t('common.delete')).toBe('Delete')+ })++ it('confirms through onConfirm', async () => {+ const onConfirm = vi.fn()+ const { user } = renderWithProviders(+ <DeleteConfirmationDialog {...baseProps} onConfirm={onConfirm} />,+ )++ await user.click(+ screen.getByRole('button', { name: new RegExp(t('common.delete')) }),+ )++ expect(onConfirm).toHaveBeenCalledTimes(1)+ })++ it('cancels through onClose when no explicit onCancel is given', async () => {+ const onClose = vi.fn()+ const { user } = renderWithProviders(+ <DeleteConfirmationDialog {...baseProps} onClose={onClose} />,+ )++ await user.click(screen.getByRole('button', { name: t('common.cancel') }))++ expect(onClose).toHaveBeenCalledTimes(1)+ })++ it('prefers an explicit onCancel over onClose', async () => {+ // #643: cancelling a nested confirmation has to return to the parent+ // dialog, which is a different action from dismissing the whole stack.+ const onClose = vi.fn()+ const onCancel = vi.fn()+ const { user } = renderWithProviders(+ <DeleteConfirmationDialog+ {...baseProps}+ onClose={onClose}+ onCancel={onCancel}+ />,+ )++ await user.click(screen.getByRole('button', { name: t('common.cancel') }))++ expect(onCancel).toHaveBeenCalledTimes(1)+ expect(onClose).not.toHaveBeenCalled()+ })++ it('closes on Escape while idle', async () => {+ const onClose = vi.fn()+ const { user } = renderWithProviders(+ <DeleteConfirmationDialog {...baseProps} onClose={onClose} />,+ )++ await user.keyboard('{Escape}')++ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1))+ })++ it('disables both actions while the delete is in flight', () => {+ // Without this a double click fires two DELETEs, and the second one+ // 404s on a row the first already removed.+ renderWithProviders(<DeleteConfirmationDialog {...baseProps} isPending />)++ expect(screen.getByRole('button', { name: t('common.cancel') })).toBeDisabled()+ expect(+ screen.getByRole('button', { name: new RegExp(t('common.delete')) }),+ ).toBeDisabled()+ })++ it('refuses to close on Escape while the delete is in flight', async () => {+ // The dialog is the only progress indicator the user has; dismissing it+ // mid-request leaves them unsure whether the row was deleted.+ const onClose = vi.fn()+ const { user } = renderWithProviders(+ <DeleteConfirmationDialog {...baseProps} isPending onClose={onClose} />,+ )++ await user.keyboard('{Escape}')++ expect(onClose).not.toHaveBeenCalled()+ expect(screen.getByRole('dialog')).toBeInTheDocument()+ })++ it('hides the corner close affordance while pending', () => {+ renderWithProviders(<DeleteConfirmationDialog {...baseProps} isPending />)++ expect(screen.queryByRole('button', { name: 'Close' })).not.toBeInTheDocument()+ })++ it('stays open after confirming, so the caller controls dismissal on error', async () => {+ // #643 again: on a failed delete the dialog must remain so the user can+ // read the toast and back out deliberately.+ const onConfirm = vi.fn()+ const onClose = vi.fn()+ const { user } = renderWithProviders(+ <DeleteConfirmationDialog+ {...baseProps}+ onConfirm={onConfirm}+ onClose={onClose}+ />,+ )++ await user.click(+ screen.getByRole('button', { name: new RegExp(t('common.delete')) }),+ )++ expect(screen.getByRole('dialog')).toBeInTheDocument()+ expect(onClose).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/components/module-route.test.tsx b/frontend/src/components/module-route.test.tsxnew file mode 100644index 00000000..63a9fefa--- /dev/null+++ b/frontend/src/components/module-route.test.tsx@@ -0,0 +1,85 @@+import { describe, expect, it, vi } from 'vitest'+import { screen } from '@testing-library/react'+import { Route, Routes } from 'react-router-dom'++import { ModuleRoute } from '@/components/module-route'+import { renderWithProviders } from '@/test/utils'++const useWorkspace = vi.hoisted(() => vi.fn())+vi.mock('@/contexts/workspace-context', () => ({ useWorkspace }))++function renderGuard() {+ return renderWithProviders(+ <Routes>+ <Route path="/" element={<div>home</div>} />+ <Route+ path="/budgets"+ element={+ <ModuleRoute module="budgets">+ <div>budgets page</div>+ </ModuleRoute>+ }+ />+ </Routes>,+ { route: '/budgets' },+ )+}++describe('ModuleRoute', () => {+ it('renders the page when the workspace has the module', () => {+ useWorkspace.mockReturnValue({ hasModule: () => true, isLoading: false })++ renderGuard()++ expect(screen.getByText('budgets page')).toBeInTheDocument()+ })++ it('sends the user home when the workspace does not have it', () => {+ // Hiding the nav entry leaves the URL reachable; this is the guard that+ // actually closes it.+ useWorkspace.mockReturnValue({ hasModule: () => false, isLoading: false })++ renderGuard()++ expect(screen.getByText('home')).toBeInTheDocument()+ expect(screen.queryByText('budgets page')).not.toBeInTheDocument()+ })++ it('asks about the module it was given, not a hard-coded one', () => {+ // Deliberately mismatched: the route is /budgets but the guard is told+ // "invoices". Asking about "budgets" here would pass if the component+ // derived the module from the path or hard-coded it.+ const hasModule = vi.fn().mockReturnValue(true)+ useWorkspace.mockReturnValue({ hasModule, isLoading: false })++ renderWithProviders(+ <Routes>+ <Route path="/" element={<div>home</div>} />+ <Route+ path="/budgets"+ element={+ <ModuleRoute module="invoices">+ <div>budgets page</div>+ </ModuleRoute>+ }+ />+ </Routes>,+ { route: '/budgets' },+ )++ expect(hasModule).toHaveBeenCalledWith('invoices')+ expect(hasModule).not.toHaveBeenCalledWith('budgets')+ })++ it('shows a loading indicator instead of bouncing to home', () => {+ // Redirecting first would make a deep link unusable on a cold load, since+ // enabled_modules has not arrived yet.+ useWorkspace.mockReturnValue({ hasModule: () => false, isLoading: true })++ const { container } = renderGuard()++ expect(container.querySelector('.animate-spin')).toBeInTheDocument()+ expect(screen.queryByText('home')).not.toBeInTheDocument()+ expect(screen.queryByText('budgets page')).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/components/month-stepper.test.tsx b/frontend/src/components/month-stepper.test.tsxnew file mode 100644index 00000000..92e8e439--- /dev/null+++ b/frontend/src/components/month-stepper.test.tsx@@ -0,0 +1,104 @@+import { describe, expect, it, vi } from 'vitest'+import { screen } from '@testing-library/react'++import { MonthStepper } from '@/components/month-stepper'+import { renderWithProviders } from '@/test/utils'++describe('MonthStepper', () => {+ it('shows the selected month', () => {+ renderWithProviders(+ <MonthStepper value="2026-06" onChange={vi.fn()} locale="en-US" />,+ )++ expect(screen.getByTitle(/June 2026/)).toBeInTheDocument()+ })++ it('steps back a month', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <MonthStepper+ value="2026-06"+ onChange={onChange}+ locale="en-US"+ prevLabel="Previous month"+ nextLabel="Next month"+ />,+ )++ await user.click(screen.getByRole('button', { name: 'Previous month' }))++ expect(onChange).toHaveBeenCalledWith('2026-05')+ })++ it('steps forward a month', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <MonthStepper+ value="2026-06"+ onChange={onChange}+ locale="en-US"+ prevLabel="Previous month"+ nextLabel="Next month"+ />,+ )++ await user.click(screen.getByRole('button', { name: 'Next month' }))++ expect(onChange).toHaveBeenCalledWith('2026-07')+ })++ it('crosses the year boundary going back from January', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <MonthStepper+ value="2026-01"+ onChange={onChange}+ locale="en-US"+ prevLabel="Previous month"+ nextLabel="Next month"+ />,+ )++ await user.click(screen.getByRole('button', { name: 'Previous month' }))++ expect(onChange).toHaveBeenCalledWith('2025-12')+ })++ it('crosses the year boundary going forward from December', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <MonthStepper+ value="2026-12"+ onChange={onChange}+ locale="en-US"+ prevLabel="Previous month"+ nextLabel="Next month"+ />,+ )++ await user.click(screen.getByRole('button', { name: 'Next month' }))++ expect(onChange).toHaveBeenCalledWith('2027-01')+ })++ it('renders the label in the given locale', () => {+ renderWithProviders(+ <MonthStepper value="2026-05" onChange={vi.fn()} locale="pt-BR" />,+ )++ expect(screen.getByTitle(/maio de 2026/i)).toBeInTheDocument()+ })++ it('holds no state of its own, so the parent stays the source of truth', () => {+ const onChange = vi.fn()+ const { rerender } = renderWithProviders(+ <MonthStepper value="2026-06" onChange={onChange} locale="en-US" />,+ )++ rerender(+ <MonthStepper value="2026-09" onChange={onChange} locale="en-US" />,+ )++ expect(screen.getByTitle(/September 2026/)).toBeInTheDocument()+ })+})diff --git a/frontend/src/components/page-header.test.tsx b/frontend/src/components/page-header.test.tsxnew file mode 100644index 00000000..b467f95c--- /dev/null+++ b/frontend/src/components/page-header.test.tsx@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest'+import { screen } from '@testing-library/react'++import { PageHeader } from '@/components/page-header'+import { renderWithProviders } from '@/test/utils'++describe('PageHeader', () => {+ it('renders the section and the title', () => {+ renderWithProviders(<PageHeader section="Money" title="Transactions" />)++ expect(screen.getByText('Money')).toBeInTheDocument()+ expect(screen.getByText('Transactions')).toBeInTheDocument()+ })++ it('renders the title as the page heading', () => {+ // One h1 per screen is what lets a screen-reader user jump to the+ // content; the section line above it is not a heading.+ renderWithProviders(<PageHeader section="Money" title="Transactions" />)++ expect(+ screen.getByRole('heading', { level: 1, name: 'Transactions' }),+ ).toBeInTheDocument()+ expect(screen.getAllByRole('heading')).toHaveLength(1)+ })++ it('renders the optional action', () => {+ renderWithProviders(+ <PageHeader+ section="Money"+ title="Transactions"+ action={<button type="button">New transaction</button>}+ />,+ )++ expect(+ screen.getByRole('button', { name: 'New transaction' }),+ ).toBeInTheDocument()+ })++ it('renders without an action', () => {+ renderWithProviders(<PageHeader section="Money" title="Transactions" />)++ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/components/projected-transaction-badge.test.tsx b/frontend/src/components/projected-transaction-badge.test.tsxnew file mode 100644index 00000000..09807bb4--- /dev/null+++ b/frontend/src/components/projected-transaction-badge.test.tsx@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest'+import { screen } from '@testing-library/react'++import { ProjectedTransactionBadge } from '@/components/projected-transaction-badge'+import { i18n, renderWithProviders, t } from '@/test/utils'++describe('ProjectedTransactionBadge', () => {+ it('labels a projected transaction from the bundle', () => {+ renderWithProviders(<ProjectedTransactionBadge />)++ expect(screen.getByText(t('transactions.projected'))).toBeInTheDocument()+ })++ it('renders translated copy, not the raw key', () => {+ // A missing key renders as "transactions.projected" in the UI, which is+ // the shape the Dutch locale regression took (#653).+ renderWithProviders(<ProjectedTransactionBadge />)++ expect(screen.queryByText('transactions.projected')).not.toBeInTheDocument()+ })++ it('follows the active language', async () => {+ await i18n.changeLanguage('pt-BR')+ try {+ renderWithProviders(<ProjectedTransactionBadge />)++ expect(screen.getByText(t('transactions.projected'))).toBeInTheDocument()+ } finally {+ await i18n.changeLanguage('en')+ }+ })+})diff --git a/frontend/src/components/protected-route.test.tsx b/frontend/src/components/protected-route.test.tsxnew file mode 100644index 00000000..bb1d6786--- /dev/null+++ b/frontend/src/components/protected-route.test.tsx@@ -0,0 +1,65 @@+import { describe, expect, it, vi } from 'vitest'+import { screen } from '@testing-library/react'+import { Route, Routes } from 'react-router-dom'++import { ProtectedRoute } from '@/components/protected-route'+import { renderWithProviders } from '@/test/utils'++const useAuth = vi.hoisted(() => vi.fn())+vi.mock('@/contexts/auth-context', () => ({ useAuth }))++function renderGuard() {+ return renderWithProviders(+ <Routes>+ <Route path="/login" element={<div>login screen</div>} />+ <Route+ path="/private"+ element={+ <ProtectedRoute>+ <div>private page</div>+ </ProtectedRoute>+ }+ />+ </Routes>,+ { route: '/private' },+ )+}++describe('ProtectedRoute', () => {+ it('renders the page for an authenticated user', () => {+ useAuth.mockReturnValue({ token: 'jwt', user: null, isLoading: false })++ renderGuard()++ expect(screen.getByText('private page')).toBeInTheDocument()+ })++ it('sends an anonymous visitor to the login screen', () => {+ useAuth.mockReturnValue({ token: null, user: null, isLoading: false })++ renderGuard()++ expect(screen.getByText('login screen')).toBeInTheDocument()+ expect(screen.queryByText('private page')).not.toBeInTheDocument()+ })++ it('shows a loading indicator instead of redirecting while the session resolves', () => {+ // Redirecting during the initial `auth.me()` call would bounce every+ // returning user to /login on a hard refresh.+ useAuth.mockReturnValue({ token: 'jwt', user: null, isLoading: true })++ const { container } = renderGuard()++ expect(container.querySelector('.animate-spin')).toBeInTheDocument()+ expect(screen.queryByText('private page')).not.toBeInTheDocument()+ expect(screen.queryByText('login screen')).not.toBeInTheDocument()+ })++ it('does not leak the page for a moment while loading without a token', () => {+ useAuth.mockReturnValue({ token: null, user: null, isLoading: true })++ renderGuard()++ expect(screen.queryByText('private page')).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/components/shell-logo.test.tsx b/frontend/src/components/shell-logo.test.tsxnew file mode 100644index 00000000..3a186194--- /dev/null+++ b/frontend/src/components/shell-logo.test.tsx@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest'++import { ShellLogo } from '@/components/shell-logo'+import { renderWithProviders } from '@/test/utils'++describe('ShellLogo', () => {+ it('renders an svg at the default size', () => {+ const { container } = renderWithProviders(<ShellLogo />)++ const svg = container.querySelector('svg')!+ expect(svg).toBeInTheDocument()+ expect(svg).toHaveAttribute('width', '24')+ expect(svg).toHaveAttribute('height', '24')+ })++ it('honours an explicit size on both axes', () => {+ const { container } = renderWithProviders(<ShellLogo size={64} />)++ const svg = container.querySelector('svg')!+ expect(svg).toHaveAttribute('width', '64')+ expect(svg).toHaveAttribute('height', '64')+ })++ it('keeps the viewBox fixed so the mark never distorts', () => {+ const { container } = renderWithProviders(<ShellLogo size={120} />)++ const svg = container.querySelector('svg')!+ expect(svg).toHaveAttribute('viewBox', '0 0 460 460')+ expect(svg).toHaveAttribute('preserveAspectRatio', 'xMidYMid meet')+ })++ it('fills from currentColor, so it follows the theme', () => {+ const { container } = renderWithProviders(<ShellLogo />)++ expect(container.querySelector('g')).toHaveAttribute('fill', 'currentColor')+ })++ it('accepts a className', () => {+ const { container } = renderWithProviders(+ <ShellLogo className="text-primary" />,+ )++ expect(container.querySelector('svg')).toHaveClass('text-primary')+ })+})diff --git a/frontend/src/components/ui/avatar.test.tsx b/frontend/src/components/ui/avatar.test.tsxnew file mode 100644index 00000000..8cb2e5fa--- /dev/null+++ b/frontend/src/components/ui/avatar.test.tsx@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest'+import { screen } from '@testing-library/react'++import {+ Avatar,+ AvatarFallback,+ AvatarGroup,+ AvatarGroupCount,+} from '@/components/ui/avatar'+import { renderWithProviders } from '@/test/utils'++describe('Avatar', () => {+ it('renders the fallback when no image resolves', () => {+ // jsdom never loads images, which is also what a member with no avatar+ // looks like in the app.+ renderWithProviders(+ <Avatar>+ <AvatarFallback>TN</AvatarFallback>+ </Avatar>,+ )++ expect(screen.getByText('TN')).toBeInTheDocument()+ })++ it('defaults to the default size', () => {+ const { container } = renderWithProviders(+ <Avatar>+ <AvatarFallback>TN</AvatarFallback>+ </Avatar>,+ )++ expect(container.querySelector('[data-slot="avatar"]')).toHaveAttribute(+ 'data-size',+ 'default',+ )+ })++ it('records the requested size, which the child styling keys off', () => {+ const { container } = renderWithProviders(+ <Avatar size="lg">+ <AvatarFallback>TN</AvatarFallback>+ </Avatar>,+ )++ expect(container.querySelector('[data-slot="avatar"]')).toHaveAttribute(+ 'data-size',+ 'lg',+ )+ })++ it('renders a group with an overflow count', () => {+ renderWithProviders(+ <AvatarGroup>+ <Avatar>+ <AvatarFallback>A</AvatarFallback>+ </Avatar>+ <Avatar>+ <AvatarFallback>B</AvatarFallback>+ </Avatar>+ <AvatarGroupCount>+3</AvatarGroupCount>+ </AvatarGroup>,+ )++ expect(screen.getByText('A')).toBeInTheDocument()+ expect(screen.getByText('B')).toBeInTheDocument()+ expect(screen.getByText('+3')).toBeInTheDocument()+ })+})diff --git a/frontend/src/components/ui/badge.test.tsx b/frontend/src/components/ui/badge.test.tsxnew file mode 100644index 00000000..4693d640--- /dev/null+++ b/frontend/src/components/ui/badge.test.tsx@@ -0,0 +1,49 @@+import { describe, expect, it } from 'vitest'+import { screen } from '@testing-library/react'++import { Badge } from '@/components/ui/badge'+import { renderWithProviders } from '@/test/utils'++describe('Badge', () => {+ it('renders its content', () => {+ renderWithProviders(<Badge>Pending</Badge>)++ expect(screen.getByText('Pending')).toBeInTheDocument()+ })++ it('defaults to the default variant', () => {+ renderWithProviders(<Badge>Cleared</Badge>)++ expect(screen.getByText('Cleared')).toHaveAttribute('data-variant', 'default')+ })++ it('records the requested variant', () => {+ renderWithProviders(<Badge variant="destructive">Overdue</Badge>)++ expect(screen.getByText('Overdue')).toHaveAttribute(+ 'data-variant',+ 'destructive',+ )+ })++ it('renders as a link when asChild is set', () => {+ renderWithProviders(+ <Badge asChild>+ <a href="/rules">3 rules</a>+ </Badge>,+ )++ expect(screen.getByRole('link', { name: '3 rules' })).toHaveAttribute(+ 'href',+ '/rules',+ )+ })++ it('keeps whitespace-nowrap so a long label cannot wrap mid-badge', () => {+ // #693 was a label wrapping inside its container. The class is the+ // contract that prevents it.+ renderWithProviders(<Badge>Starts with</Badge>)++ expect(screen.getByText('Starts with')).toHaveClass('whitespace-nowrap')+ })+})diff --git a/frontend/src/components/ui/button.test.tsx b/frontend/src/components/ui/button.test.tsxnew file mode 100644index 00000000..a06cae38--- /dev/null+++ b/frontend/src/components/ui/button.test.tsx@@ -0,0 +1,69 @@+import { describe, expect, it, vi } from 'vitest'+import { screen } from '@testing-library/react'++import { Button } from '@/components/ui/button'+import { renderWithProviders } from '@/test/utils'++describe('Button', () => {+ it('renders its label as a real button element', () => {+ renderWithProviders(<Button>Save changes</Button>)++ const button = screen.getByRole('button', { name: 'Save changes' })+ expect(button).toBeInTheDocument()+ expect(button.tagName).toBe('BUTTON')+ })++ it('calls onClick when pressed', async () => {+ const onClick = vi.fn()+ const { user } = renderWithProviders(<Button onClick={onClick}>Confirm</Button>)++ await user.click(screen.getByRole('button', { name: 'Confirm' }))++ expect(onClick).toHaveBeenCalledTimes(1)+ })++ it('does not fire onClick while disabled', async () => {+ const onClick = vi.fn()+ const { user } = renderWithProviders(+ <Button disabled onClick={onClick}>+ Delete+ </Button>,+ )++ const button = screen.getByRole('button', { name: 'Delete' })+ expect(button).toBeDisabled()++ await user.click(button)+ expect(onClick).not.toHaveBeenCalled()+ })++ it('exposes variant and size so styling regressions stay assertable', () => {+ renderWithProviders(+ <Button variant="destructive" size="sm">+ Remove+ </Button>,+ )++ const button = screen.getByRole('button', { name: 'Remove' })+ expect(button).toHaveAttribute('data-variant', 'destructive')+ expect(button).toHaveAttribute('data-size', 'sm')+ })++ it('renders as the child element when asChild is set', () => {+ renderWithProviders(+ <Button asChild>+ <a href="/accounts">Go to accounts</a>+ </Button>,+ )++ const link = screen.getByRole('link', { name: 'Go to accounts' })+ expect(link).toHaveAttribute('href', '/accounts')+ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ })++ it('keeps a caller className alongside the variant classes', () => {+ renderWithProviders(<Button className="w-full">Wide</Button>)++ expect(screen.getByRole('button', { name: 'Wide' })).toHaveClass('w-full')+ })+})diff --git a/frontend/src/components/ui/card.test.tsx b/frontend/src/components/ui/card.test.tsxnew file mode 100644index 00000000..54715c82--- /dev/null+++ b/frontend/src/components/ui/card.test.tsx@@ -0,0 +1,65 @@+import { describe, expect, it } from 'vitest'+import { screen } from '@testing-library/react'++import {+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+} from '@/components/ui/card'+import { renderWithProviders } from '@/test/utils'++describe('Card', () => {+ it('renders every slot it is given', () => {+ renderWithProviders(+ <Card>+ <CardHeader>+ <CardTitle>Net worth</CardTitle>+ <CardDescription>Across all accounts</CardDescription>+ <CardAction>+ <button type="button">Refresh</button>+ </CardAction>+ </CardHeader>+ <CardContent>R$ 12.480,00</CardContent>+ <CardFooter>Updated a minute ago</CardFooter>+ </Card>,+ )++ expect(screen.getByText('Net worth')).toBeInTheDocument()+ expect(screen.getByText('Across all accounts')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Refresh' })).toBeInTheDocument()+ expect(screen.getByText('R$ 12.480,00')).toBeInTheDocument()+ expect(screen.getByText('Updated a minute ago')).toBeInTheDocument()+ })++ it('tags each slot so layout rules stay addressable', () => {+ const { container } = renderWithProviders(+ <Card>+ <CardHeader>+ <CardTitle>Title</CardTitle>+ </CardHeader>+ <CardContent>Body</CardContent>+ </Card>,+ )++ expect(container.querySelector('[data-slot="card"]')).toBeInTheDocument()+ expect(+ container.querySelector('[data-slot="card-header"]'),+ ).toBeInTheDocument()+ expect(+ container.querySelector('[data-slot="card-title"]'),+ ).toBeInTheDocument()+ expect(+ container.querySelector('[data-slot="card-content"]'),+ ).toBeInTheDocument()+ })++ it('renders a card with no optional slots', () => {+ renderWithProviders(<Card>Bare</Card>)++ expect(screen.getByText('Bare')).toBeInTheDocument()+ })+})diff --git a/frontend/src/components/ui/dialog.test.tsx b/frontend/src/components/ui/dialog.test.tsxnew file mode 100644index 00000000..71423e35--- /dev/null+++ b/frontend/src/components/ui/dialog.test.tsx@@ -0,0 +1,103 @@+import { describe, expect, it, vi } from 'vitest'+import { screen, waitFor } from '@testing-library/react'++import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from '@/components/ui/dialog'+import { renderWithProviders } from '@/test/utils'++function Example({+ onOpenChange,+ showCloseButton,+}: {+ onOpenChange?: (open: boolean) => void+ showCloseButton?: boolean+} = {}) {+ return (+ <Dialog onOpenChange={onOpenChange}>+ <DialogTrigger>Open</DialogTrigger>+ <DialogContent showCloseButton={showCloseButton}>+ <DialogHeader>+ <DialogTitle>Delete account</DialogTitle>+ <DialogDescription>This cannot be undone.</DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <button type="button">Confirm</button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++describe('Dialog', () => {+ it('stays closed until the trigger is pressed', () => {+ renderWithProviders(<Example />)++ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ })++ it('opens on the trigger and shows its title and description', async () => {+ const { user } = renderWithProviders(<Example />)++ await user.click(screen.getByRole('button', { name: 'Open' }))++ const dialog = await screen.findByRole('dialog')+ expect(dialog).toBeInTheDocument()+ expect(screen.getByText('Delete account')).toBeInTheDocument()+ expect(screen.getByText('This cannot be undone.')).toBeInTheDocument()+ })++ it('closes on Escape', async () => {+ const { user } = renderWithProviders(<Example />)++ await user.click(screen.getByRole('button', { name: 'Open' }))+ await screen.findByRole('dialog')++ await user.keyboard('{Escape}')++ await waitFor(() => {+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ })+ })++ it('reports open and close through onOpenChange exactly once each', async () => {+ const onOpenChange = vi.fn()+ const { user } = renderWithProviders(<Example onOpenChange={onOpenChange} />)++ await user.click(screen.getByRole('button', { name: 'Open' }))+ await screen.findByRole('dialog')+ expect(onOpenChange).toHaveBeenCalledWith(true)++ await user.keyboard('{Escape}')+ await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false))++ // Count and order, not just "was called with". A dialog that fires open+ // twice would double-submit anything the consumer does on open, and+ // toHaveBeenCalledWith alone cannot tell.+ expect(onOpenChange.mock.calls).toEqual([[true], [false]])+ })++ it('renders a close affordance by default', async () => {+ const { user } = renderWithProviders(<Example />)++ await user.click(screen.getByRole('button', { name: 'Open' }))+ await screen.findByRole('dialog')++ expect(screen.getByRole('button', { name: 'Close' })).toBeInTheDocument()+ })++ it('omits the close affordance when the caller opts out', async () => {+ const { user } = renderWithProviders(<Example showCloseButton={false} />)++ await user.click(screen.getByRole('button', { name: 'Open' }))+ await screen.findByRole('dialog')++ expect(screen.queryByRole('button', { name: 'Close' })).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/components/ui/input.test.tsx b/frontend/src/components/ui/input.test.tsxnew file mode 100644index 00000000..b1416259--- /dev/null+++ b/frontend/src/components/ui/input.test.tsx@@ -0,0 +1,55 @@+import { describe, expect, it, vi } from 'vitest'+import { screen } from '@testing-library/react'++import { Input } from '@/components/ui/input'+import { renderWithProviders } from '@/test/utils'++describe('Input', () => {+ it('accepts typed text', async () => {+ const { user } = renderWithProviders(<Input aria-label="Description" />)++ const input = screen.getByLabelText('Description')+ await user.type(input, 'Coffee')++ expect(input).toHaveValue('Coffee')+ })++ it('reports every keystroke to onChange', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <Input aria-label="Amount" onChange={onChange} />,+ )++ await user.type(screen.getByLabelText('Amount'), '250')++ expect(onChange).toHaveBeenCalledTimes(3)+ })++ it('does not accept input while disabled', async () => {+ const { user } = renderWithProviders(<Input aria-label="Locked" disabled />)++ const input = screen.getByLabelText('Locked')+ expect(input).toBeDisabled()++ await user.type(input, 'nope')+ expect(input).toHaveValue('')+ })++ it('passes the type through', () => {+ renderWithProviders(<Input aria-label="Password" type="password" />)++ expect(screen.getByLabelText('Password')).toHaveAttribute('type', 'password')+ })++ it('exposes the invalid state that the styling hangs off', () => {+ renderWithProviders(<Input aria-label="Email" aria-invalid />)++ expect(screen.getByLabelText('Email')).toHaveAttribute('aria-invalid', 'true')+ })++ it('renders a placeholder', () => {+ renderWithProviders(<Input aria-label="Search" placeholder="Search payees" />)++ expect(screen.getByPlaceholderText('Search payees')).toBeInTheDocument()+ })+})diff --git a/frontend/src/components/ui/label.test.tsx b/frontend/src/components/ui/label.test.tsxnew file mode 100644index 00000000..c5d06b70--- /dev/null+++ b/frontend/src/components/ui/label.test.tsx@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest'+import { screen } from '@testing-library/react'++import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { renderWithProviders } from '@/test/utils'++describe('Label', () => {+ it('renders its text', () => {+ renderWithProviders(<Label>Category</Label>)++ expect(screen.getByText('Category')).toBeInTheDocument()+ })++ it('associates with the control it names, so the field is reachable by label', async () => {+ const { user } = renderWithProviders(+ <>+ <Label htmlFor="payee">Payee</Label>+ <Input id="payee" />+ </>,+ )++ const input = screen.getByLabelText('Payee')+ expect(input).toBeInTheDocument()++ // Clicking the label must focus the input, which is the whole point of+ // the association.+ await user.click(screen.getByText('Payee'))+ expect(input).toHaveFocus()+ })+})diff --git a/frontend/src/components/ui/select.test.tsx b/frontend/src/components/ui/select.test.tsxnew file mode 100644index 00000000..d1b12bdc--- /dev/null+++ b/frontend/src/components/ui/select.test.tsx@@ -0,0 +1,99 @@+import { describe, expect, it, vi } from 'vitest'+import { screen } from '@testing-library/react'++import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select'+import { renderWithProviders } from '@/test/utils'++function Example({+ onValueChange,+ defaultValue,+ disabled,+}: {+ onValueChange?: (value: string) => void+ defaultValue?: string+ disabled?: boolean+} = {}) {+ return (+ <Select+ defaultValue={defaultValue}+ onValueChange={onValueChange}+ disabled={disabled}+ >+ <SelectTrigger aria-label="Currency">+ <SelectValue placeholder="Pick a currency" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="BRL">Brazilian Real</SelectItem>+ <SelectItem value="USD">US Dollar</SelectItem>+ <SelectItem value="EUR">Euro</SelectItem>+ </SelectContent>+ </Select>+ )+}++describe('Select', () => {+ it('shows the placeholder until something is chosen', () => {+ renderWithProviders(<Example />)++ expect(screen.getByText('Pick a currency')).toBeInTheDocument()+ })++ it('shows the default value instead of the placeholder', () => {+ renderWithProviders(<Example defaultValue="USD" />)++ expect(screen.getByText('US Dollar')).toBeInTheDocument()+ expect(screen.queryByText('Pick a currency')).not.toBeInTheDocument()+ })++ it('keeps its options closed until opened', () => {+ renderWithProviders(<Example />)++ expect(screen.queryByRole('option', { name: 'Euro' })).not.toBeInTheDocument()+ })++ it('opens on click and lists every option', async () => {+ const { user } = renderWithProviders(<Example />)++ await user.click(screen.getByRole('combobox', { name: 'Currency' }))++ expect(+ await screen.findByRole('option', { name: 'Brazilian Real' }),+ ).toBeInTheDocument()+ expect(screen.getByRole('option', { name: 'US Dollar' })).toBeInTheDocument()+ expect(screen.getByRole('option', { name: 'Euro' })).toBeInTheDocument()+ })++ it('reports the chosen value', async () => {+ const onValueChange = vi.fn()+ const { user } = renderWithProviders(+ <Example onValueChange={onValueChange} />,+ )++ await user.click(screen.getByRole('combobox', { name: 'Currency' }))+ await user.click(await screen.findByRole('option', { name: 'Euro' }))++ expect(onValueChange).toHaveBeenCalledWith('EUR')+ // The trigger has to follow. Reporting the value while still showing the+ // placeholder is a real Radix misconfiguration and the mock cannot see it.+ expect(screen.getByRole('combobox', { name: 'Currency' })).toHaveTextContent(+ 'Euro',+ )+ expect(screen.queryByText('Pick a currency')).not.toBeInTheDocument()+ })++ it('does not open while disabled', async () => {+ const { user } = renderWithProviders(<Example disabled />)++ const trigger = screen.getByRole('combobox', { name: 'Currency' })+ expect(trigger).toBeDisabled()++ await user.click(trigger)+ expect(screen.queryByRole('option', { name: 'Euro' })).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/components/ui/separator.test.tsx b/frontend/src/components/ui/separator.test.tsxnew file mode 100644index 00000000..ec09f073--- /dev/null+++ b/frontend/src/components/ui/separator.test.tsx@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest'++import { Separator } from '@/components/ui/separator'+import { renderWithProviders } from '@/test/utils'++describe('Separator', () => {+ it('defaults to a horizontal decorative rule', () => {+ const { container } = renderWithProviders(<Separator />)++ const separator = container.querySelector('[data-slot="separator"]')!+ expect(separator).toHaveAttribute('data-orientation', 'horizontal')+ // Decorative separators are hidden from the accessibility tree, which is+ // what we want for pure visual dividers.+ expect(separator).toHaveAttribute('role', 'none')+ })++ it('supports a vertical orientation', () => {+ const { container } = renderWithProviders(<Separator orientation="vertical" />)++ expect(container.querySelector('[data-slot="separator"]')).toHaveAttribute(+ 'data-orientation',+ 'vertical',+ )+ })++ it('becomes a real separator for assistive tech when not decorative', () => {+ const { container } = renderWithProviders(<Separator decorative={false} />)++ expect(container.querySelector('[data-slot="separator"]')).toHaveAttribute(+ 'role',+ 'separator',+ )+ })+})diff --git a/frontend/src/components/ui/skeleton.test.tsx b/frontend/src/components/ui/skeleton.test.tsxnew file mode 100644index 00000000..0fdcb84a--- /dev/null+++ b/frontend/src/components/ui/skeleton.test.tsx@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest'++import { Skeleton } from '@/components/ui/skeleton'+import { renderWithProviders } from '@/test/utils'++describe('Skeleton', () => {+ it('renders a pulsing placeholder', () => {+ const { container } = renderWithProviders(<Skeleton />)++ const skeleton = container.querySelector('[data-slot="skeleton"]')!+ expect(skeleton).toBeInTheDocument()+ expect(skeleton).toHaveClass('animate-pulse')+ })++ it('keeps the caller sizing classes', () => {+ const { container } = renderWithProviders(<Skeleton className="h-8 w-32" />)++ expect(container.querySelector('[data-slot="skeleton"]')).toHaveClass(+ 'h-8',+ 'w-32',+ )+ })++ it('carries no text, so a loading card announces nothing misleading', () => {+ const { container } = renderWithProviders(<Skeleton className="h-4" />)++ expect(container.textContent).toBe('')+ })+})diff --git a/frontend/src/components/ui/switch.test.tsx b/frontend/src/components/ui/switch.test.tsxnew file mode 100644index 00000000..c7e5607d--- /dev/null+++ b/frontend/src/components/ui/switch.test.tsx@@ -0,0 +1,58 @@+import { describe, expect, it, vi } from 'vitest'+import { screen } from '@testing-library/react'++import { Switch } from '@/components/ui/switch'+import { renderWithProviders } from '@/test/utils'++describe('Switch', () => {+ it('exposes its state to assistive tech', () => {+ renderWithProviders(+ <Switch checked onCheckedChange={vi.fn()} aria-labelledby="lbl" />,+ )++ expect(screen.getByRole('switch')).toBeChecked()+ })++ it('reports the flipped value, not the current one', async () => {+ const onCheckedChange = vi.fn()+ const { user } = renderWithProviders(+ <Switch checked={false} onCheckedChange={onCheckedChange} />,+ )++ await user.click(screen.getByRole('switch'))++ expect(onCheckedChange).toHaveBeenCalledWith(true)+ })++ it('flips back off from on', async () => {+ const onCheckedChange = vi.fn()+ const { user } = renderWithProviders(+ <Switch checked onCheckedChange={onCheckedChange} />,+ )++ await user.click(screen.getByRole('switch'))++ expect(onCheckedChange).toHaveBeenCalledWith(false)+ })++ it('stays silent while disabled', async () => {+ const onCheckedChange = vi.fn()+ const { user } = renderWithProviders(+ <Switch checked={false} onCheckedChange={onCheckedChange} disabled />,+ )++ const toggle = screen.getByRole('switch')+ expect(toggle).toBeDisabled()++ await user.click(toggle)+ expect(onCheckedChange).not.toHaveBeenCalled()+ })++ it('is type=button so it cannot submit the form around it', () => {+ // A settings switch inside a form that submits on click would save+ // half-filled state.+ renderWithProviders(<Switch checked={false} onCheckedChange={vi.fn()} />)++ expect(screen.getByRole('switch')).toHaveAttribute('type', 'button')+ })+})diff --git a/frontend/src/components/ui/table.test.tsx b/frontend/src/components/ui/table.test.tsxnew file mode 100644index 00000000..cf2afbb7--- /dev/null+++ b/frontend/src/components/ui/table.test.tsx@@ -0,0 +1,98 @@+import { describe, expect, it } from 'vitest'+import { screen, within } from '@testing-library/react'++import {+ Table,+ TableBody,+ TableCaption,+ TableCell,+ TableFooter,+ TableHead,+ TableHeader,+ TableRow,+} from '@/components/ui/table'+import { renderWithProviders } from '@/test/utils'++function Example() {+ return (+ <Table>+ <TableCaption>June transactions</TableCaption>+ <TableHeader>+ <TableRow>+ <TableHead>Date</TableHead>+ <TableHead>Payee</TableHead>+ <TableHead>Amount</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ <TableRow>+ <TableCell>04/06</TableCell>+ <TableCell>Padaria</TableCell>+ <TableCell>R$ 18,00</TableCell>+ </TableRow>+ <TableRow>+ <TableCell>05/06</TableCell>+ <TableCell>Uber</TableCell>+ <TableCell>R$ 32,40</TableCell>+ </TableRow>+ </TableBody>+ <TableFooter>+ <TableRow>+ <TableCell>Total</TableCell>+ <TableCell />+ <TableCell>R$ 50,40</TableCell>+ </TableRow>+ </TableFooter>+ </Table>+ )+}++describe('Table', () => {+ it('renders a semantic table so screen readers can navigate it', () => {+ renderWithProviders(<Example />)++ expect(screen.getByRole('table')).toBeInTheDocument()+ })++ it('exposes its column headers', () => {+ renderWithProviders(<Example />)++ const headers = screen.getAllByRole('columnheader')+ expect(headers.map((h) => h.textContent)).toEqual([+ 'Date',+ 'Payee',+ 'Amount',+ ])+ })++ it('renders one row per record plus the header and footer rows', () => {+ renderWithProviders(<Example />)++ expect(screen.getAllByRole('row')).toHaveLength(4)+ })++ it('keeps cells in their row', () => {+ renderWithProviders(<Example />)++ const row = screen.getByText('Padaria').closest('tr')!+ expect(within(row).getByText('R$ 18,00')).toBeInTheDocument()+ expect(within(row).queryByText('R$ 32,40')).not.toBeInTheDocument()+ })++ it('renders the caption', () => {+ renderWithProviders(<Example />)++ expect(screen.getByText('June transactions')).toBeInTheDocument()+ })++ it('renders an empty body without crashing', () => {+ renderWithProviders(+ <Table>+ <TableBody />+ </Table>,+ )++ expect(screen.getByRole('table')).toBeInTheDocument()+ expect(screen.queryAllByRole('row')).toHaveLength(0)+ })+})diff --git a/frontend/src/components/ui/tabs.test.tsx b/frontend/src/components/ui/tabs.test.tsxnew file mode 100644index 00000000..578f51be--- /dev/null+++ b/frontend/src/components/ui/tabs.test.tsx@@ -0,0 +1,94 @@+import { describe, expect, it, vi } from 'vitest'+import { screen } from '@testing-library/react'++import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'+import { renderWithProviders } from '@/test/utils'++function Example({+ onValueChange,+}: { onValueChange?: (value: string) => void } = {}) {+ return (+ <Tabs defaultValue="expenses" onValueChange={onValueChange}>+ <TabsList>+ <TabsTrigger value="expenses">Expenses</TabsTrigger>+ <TabsTrigger value="income">Income</TabsTrigger>+ <TabsTrigger value="transfers" disabled>+ Transfers+ </TabsTrigger>+ </TabsList>+ <TabsContent value="expenses">expenses panel</TabsContent>+ <TabsContent value="income">income panel</TabsContent>+ <TabsContent value="transfers">transfers panel</TabsContent>+ </Tabs>+ )+}++describe('Tabs', () => {+ it('shows the default panel and hides the others', () => {+ renderWithProviders(<Example />)++ expect(screen.getByText('expenses panel')).toBeInTheDocument()+ expect(screen.queryByText('income panel')).not.toBeInTheDocument()+ })++ it('marks the active trigger as selected', () => {+ renderWithProviders(<Example />)++ expect(screen.getByRole('tab', { name: 'Expenses' })).toHaveAttribute(+ 'aria-selected',+ 'true',+ )+ expect(screen.getByRole('tab', { name: 'Income' })).toHaveAttribute(+ 'aria-selected',+ 'false',+ )+ })++ it('switches panels on click', async () => {+ const { user } = renderWithProviders(<Example />)++ await user.click(screen.getByRole('tab', { name: 'Income' }))++ expect(await screen.findByText('income panel')).toBeInTheDocument()+ expect(screen.queryByText('expenses panel')).not.toBeInTheDocument()+ })++ it('reports the newly selected value', async () => {+ const onValueChange = vi.fn()+ const { user } = renderWithProviders(+ <Example onValueChange={onValueChange} />,+ )++ await user.click(screen.getByRole('tab', { name: 'Income' }))++ expect(onValueChange).toHaveBeenCalledWith('income')+ })++ it('ignores a disabled tab', async () => {+ const onValueChange = vi.fn()+ const { user } = renderWithProviders(+ <Example onValueChange={onValueChange} />,+ )++ await user.click(screen.getByRole('tab', { name: 'Transfers' }))++ expect(onValueChange).not.toHaveBeenCalled()+ expect(screen.getByText('expenses panel')).toBeInTheDocument()+ })++ it('exposes the list variant so line styling stays assertable', () => {+ const { container } = renderWithProviders(+ <Tabs defaultValue="a">+ <TabsList variant="line">+ <TabsTrigger value="a">A</TabsTrigger>+ </TabsList>+ <TabsContent value="a">panel</TabsContent>+ </Tabs>,+ )++ expect(container.querySelector('[data-slot="tabs-list"]')).toHaveAttribute(+ 'data-variant',+ 'line',+ )+ })+})diff --git a/frontend/src/contexts/auth-context.test.tsx b/frontend/src/contexts/auth-context.test.tsxnew file mode 100644index 00000000..f472215a--- /dev/null+++ b/frontend/src/contexts/auth-context.test.tsx@@ -0,0 +1,315 @@+import type { ReactNode } from 'react'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { act, renderHook, waitFor } from '@testing-library/react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'++import { AuthProvider, useAuth } from '@/contexts/auth-context'+import type { User } from '@/types'+import { createTestQueryClient } from '@/test/utils'++const auth = vi.hoisted(() => ({+ me: vi.fn(),+ login: vi.fn(),+ verify2fa: vi.fn(),+ register: vi.fn(),+}))+vi.mock('@/lib/api', () => ({ auth }))++const USER: User = {+ id: '1',+ email: '[email protected]',+ is_active: true,+ is_superuser: false,+ is_verified: true,+ is_2fa_enabled: false,+ preferences: {},+}++function wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={createTestQueryClient()}>+ <AuthProvider>{children}</AuthProvider>+ </QueryClientProvider>+ )+}++/** Render the hook and wait for the initial session probe to settle. */+async function renderAuth() {+ const result = renderHook(() => useAuth(), { wrapper })+ await waitFor(() => expect(result.result.current.isLoading).toBe(false))+ return result+}++beforeEach(() => {+ vi.clearAllMocks()+ localStorage.clear()+})++describe('AuthProvider session restore', () => {+ it('settles as signed out when there is no stored token', async () => {+ const { result } = await renderAuth()++ expect(result.current.token).toBeNull()+ expect(result.current.user).toBeNull()+ expect(auth.me).not.toHaveBeenCalled()+ })++ it('restores the user from a stored token', async () => {+ localStorage.setItem('token', 'stored-jwt')+ auth.me.mockResolvedValue(USER)++ const { result } = await renderAuth()++ expect(auth.me).toHaveBeenCalled()+ expect(result.current.user).toEqual(USER)+ expect(result.current.token).toBe('stored-jwt')+ })++ it('discards a token the server rejects', async () => {+ // An expired or revoked token must not leave the app in a half-signed-in+ // state where every request 401s.+ localStorage.setItem('token', 'expired-jwt')+ auth.me.mockRejectedValue(new Error('401'))++ const { result } = await renderAuth()++ expect(result.current.token).toBeNull()+ expect(result.current.user).toBeNull()+ expect(localStorage.getItem('token')).toBeNull()+ })+})++describe('login', () => {+ it('stores the token and loads the user', async () => {+ auth.login.mockResolvedValue({ access_token: 'new-jwt' })+ auth.me.mockResolvedValue(USER)++ const { result } = await renderAuth()++ await act(async () => {+ const outcome = await result.current.login('[email protected]', 'pw')+ expect(outcome).toEqual({ requires_2fa: false })+ })++ expect(localStorage.getItem('token')).toBe('new-jwt')+ await waitFor(() => expect(result.current.user).toEqual(USER))+ })++ it('does not store a session when a second factor is still required', async () => {+ // The temp token is not a session. Persisting it here would sign the user+ // in on a refresh without them ever passing 2FA.+ auth.login.mockResolvedValue({+ requires_2fa: true,+ temp_token: 'temp',+ available_methods: ['totp'],+ })++ const { result } = await renderAuth()++ let outcome!: Awaited<ReturnType<typeof result.current.login>>+ await act(async () => {+ outcome = await result.current.login('[email protected]', 'pw')+ })++ expect(outcome).toEqual({+ requires_2fa: true,+ temp_token: 'temp',+ available_methods: ['totp'],+ })+ expect(localStorage.getItem('token')).toBeNull()+ expect(result.current.token).toBeNull()+ expect(result.current.user).toBeNull()+ })++ it('propagates a rejected login instead of swallowing it', async () => {+ auth.login.mockRejectedValue(new Error('invalid credentials'))++ const { result } = await renderAuth()++ await expect(+ act(async () => {+ await result.current.login('[email protected]', 'wrong')+ }),+ ).rejects.toThrow('invalid credentials')++ expect(localStorage.getItem('token')).toBeNull()+ })+})++describe('verify2fa', () => {+ it('exchanges the temp token for a real session', async () => {+ auth.verify2fa.mockResolvedValue({ access_token: 'jwt-after-2fa' })+ auth.me.mockResolvedValue(USER)++ const { result } = await renderAuth()++ await act(async () => {+ await result.current.verify2fa('temp', '123456')+ })++ expect(auth.verify2fa).toHaveBeenCalledWith('temp', '123456')+ expect(localStorage.getItem('token')).toBe('jwt-after-2fa')+ await waitFor(() => expect(result.current.user).toEqual(USER))+ })+})++describe('loginWithToken', () => {+ it('adopts a token minted elsewhere, such as the OIDC callback', async () => {+ auth.me.mockResolvedValue(USER)++ const { result } = await renderAuth()++ act(() => {+ result.current.loginWithToken('oidc-jwt')+ })++ expect(localStorage.getItem('token')).toBe('oidc-jwt')+ await waitFor(() => expect(result.current.user).toEqual(USER))+ })+})++describe('register', () => {+ it('signs the new account straight in', async () => {+ auth.register.mockResolvedValue(undefined)+ auth.login.mockResolvedValue({ access_token: 'jwt' })+ auth.me.mockResolvedValue(USER)++ const { result } = await renderAuth()++ await act(async () => {+ await result.current.register('[email protected]', 'pw', { language: 'pt-BR' })+ })++ expect(auth.register).toHaveBeenCalledWith('[email protected]', 'pw', {+ language: 'pt-BR',+ })+ expect(auth.login).toHaveBeenCalledWith('[email protected]', 'pw')+ expect(localStorage.getItem('token')).toBe('jwt')+ })++ it('does not attempt a login when registration fails', async () => {+ auth.register.mockRejectedValue(new Error('email taken'))++ const { result } = await renderAuth()++ await expect(+ act(async () => {+ await result.current.register('[email protected]', 'pw')+ }),+ ).rejects.toThrow('email taken')++ expect(auth.login).not.toHaveBeenCalled()+ })+})++describe('logout', () => {+ it('clears the token and the user', async () => {+ localStorage.setItem('token', 'jwt')+ auth.me.mockResolvedValue(USER)++ const { result } = await renderAuth()+ await waitFor(() => expect(result.current.user).toEqual(USER))++ act(() => {+ result.current.logout()+ })++ expect(localStorage.getItem('token')).toBeNull()+ expect(result.current.token).toBeNull()+ expect(result.current.user).toBeNull()+ })++ it('empties the query cache, so the next account sees no stale balances', async () => {+ // This is the privacy-relevant half of logout. Signing out on a shared+ // machine has to drop the cached financial data, not just the token.+ localStorage.setItem('token', 'jwt')+ auth.me.mockResolvedValue(USER)++ // Not createTestQueryClient: its gcTime of 0 collects data that has no+ // active observer, so the fixture would vanish before logout ran and the+ // test would pass for the wrong reason.+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ queryClient.setQueryData(['accounts'], [{ id: 'a1', balance: 4200 }])++ function localWrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={queryClient}>+ <AuthProvider>{children}</AuthProvider>+ </QueryClientProvider>+ )+ }++ const { result } = renderHook(() => useAuth(), { wrapper: localWrapper })+ await waitFor(() => expect(result.current.user).toEqual(USER))+ expect(queryClient.getQueryData(['accounts'])).toBeDefined()++ act(() => {+ result.current.logout()+ })++ expect(queryClient.getQueryData(['accounts'])).toBeUndefined()+ })+})++describe('updateUser', () => {+ it('replaces the cached user without another round trip', async () => {+ localStorage.setItem('token', 'jwt')+ auth.me.mockResolvedValue(USER)++ const { result } = await renderAuth()+ await waitFor(() => expect(result.current.user).toEqual(USER))++ const renamed = { ...USER, email: '[email protected]' }+ act(() => {+ result.current.updateUser(renamed)+ })++ expect(result.current.user).toEqual(renamed)+ expect(auth.me).toHaveBeenCalledTimes(1)+ })+})++describe('cross-tab sync', () => {+ it('signs out when another tab clears the token', async () => {+ localStorage.setItem('token', 'jwt')+ auth.me.mockResolvedValue(USER)++ const { result } = await renderAuth()+ await waitFor(() => expect(result.current.user).toEqual(USER))++ act(() => {+ window.dispatchEvent(+ new StorageEvent('storage', { key: 'token', newValue: null }),+ )+ })++ await waitFor(() => expect(result.current.token).toBeNull())+ expect(result.current.user).toBeNull()+ })++ it('ignores storage events for unrelated keys', async () => {+ localStorage.setItem('token', 'jwt')+ auth.me.mockResolvedValue(USER)++ const { result } = await renderAuth()+ await waitFor(() => expect(result.current.user).toEqual(USER))++ act(() => {+ window.dispatchEvent(+ new StorageEvent('storage', { key: 'theme', newValue: 'light' }),+ )+ })++ expect(result.current.token).toBe('jwt')+ })+})++describe('useAuth', () => {+ it('refuses to be used outside the provider', () => {+ expect(() => renderHook(() => useAuth())).toThrow(+ 'useAuth must be used within an AuthProvider',+ )+ })+})diff --git a/frontend/src/contexts/workspace-context.test.tsx b/frontend/src/contexts/workspace-context.test.tsxnew file mode 100644index 00000000..01cfa404--- /dev/null+++ b/frontend/src/contexts/workspace-context.test.tsx@@ -0,0 +1,278 @@+import type { ReactNode } from 'react'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { act, renderHook, waitFor } from '@testing-library/react'+import { QueryClientProvider } from '@tanstack/react-query'++import { WorkspaceProvider, useWorkspace } from '@/contexts/workspace-context'+import type { Workspace, WorkspaceRole } from '@/types'+import { createTestQueryClient } from '@/test/utils'++const workspacesApi = vi.hoisted(() => ({ list: vi.fn() }))+vi.mock('@/lib/api', () => ({+ workspaces: workspacesApi,+ WORKSPACE_STORAGE_KEY: 'workspace_id',+}))++const useAuth = vi.hoisted(() => vi.fn())+vi.mock('@/contexts/auth-context', () => ({ useAuth }))++function makeWorkspace(overrides: Partial<Workspace> = {}): Workspace {+ return {+ id: 'ws-1',+ name: 'Personal',+ kind: 'personal',+ role: 'owner',+ enabled_modules: ['transactions', 'accounts', 'budgets'],+ ...overrides,+ } as Workspace+}++function wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={createTestQueryClient()}>+ <WorkspaceProvider>{children}</WorkspaceProvider>+ </QueryClientProvider>+ )+}++async function renderWorkspace() {+ const rendered = renderHook(() => useWorkspace(), { wrapper })+ await waitFor(() => expect(rendered.result.current.isLoading).toBe(false))+ return rendered+}++function signedIn() {+ useAuth.mockReturnValue({+ user: { id: 'u1' },+ token: 'jwt',+ isLoading: false,+ })+}++beforeEach(() => {+ vi.clearAllMocks()+ localStorage.clear()+ signedIn()+})++describe('loading', () => {+ it('stays loading while auth is still resolving', async () => {+ // Reporting "done, no workspaces" for one render is long enough for+ // anything gated on hasModule to redirect away from a valid deep link.+ useAuth.mockReturnValue({ user: null, token: null, isLoading: true })++ const { result } = renderHook(() => useWorkspace(), { wrapper })++ expect(result.current.isLoading).toBe(true)+ expect(workspacesApi.list).not.toHaveBeenCalled()+ })++ it('reports empty once auth settles with no session', async () => {+ useAuth.mockReturnValue({ user: null, token: null, isLoading: false })++ const { result } = await renderWorkspace()++ expect(result.current.workspaces).toEqual([])+ expect(result.current.current).toBeNull()+ expect(workspacesApi.list).not.toHaveBeenCalled()+ })++ it('survives a failed fetch without getting stuck loading', async () => {+ workspacesApi.list.mockRejectedValue(new Error('network'))++ const { result } = await renderWorkspace()++ expect(result.current.workspaces).toEqual([])+ })+})++describe('selection', () => {+ it('selects the first workspace when nothing is stored', async () => {+ const first = makeWorkspace({ id: 'ws-a' })+ const second = makeWorkspace({ id: 'ws-b' })+ workspacesApi.list.mockResolvedValue([first, second])++ const { result } = await renderWorkspace()++ expect(result.current.current?.id).toBe('ws-a')+ expect(localStorage.getItem('workspace_id')).toBe('ws-a')+ })++ it('restores the stored workspace when it is still accessible', async () => {+ localStorage.setItem('workspace_id', 'ws-b')+ workspacesApi.list.mockResolvedValue([+ makeWorkspace({ id: 'ws-a' }),+ makeWorkspace({ id: 'ws-b', name: 'Family' }),+ ])++ const { result } = await renderWorkspace()++ expect(result.current.current?.name).toBe('Family')+ })++ it('falls back to the first when the stored workspace is gone', async () => {+ // Archived workspace, or the user was removed from it. Keeping the stale+ // id would send workspace_id headers the server rejects on every call.+ localStorage.setItem('workspace_id', 'ws-deleted')+ workspacesApi.list.mockResolvedValue([makeWorkspace({ id: 'ws-a' })])++ const { result } = await renderWorkspace()++ expect(result.current.current?.id).toBe('ws-a')+ expect(localStorage.getItem('workspace_id')).toBe('ws-a')+ })++ it('clears the stored id when the user has no workspaces at all', async () => {+ localStorage.setItem('workspace_id', 'ws-deleted')+ workspacesApi.list.mockResolvedValue([])++ const { result } = await renderWorkspace()++ expect(result.current.current).toBeNull()+ expect(localStorage.getItem('workspace_id')).toBeNull()+ })+})++describe('switchWorkspace', () => {+ /** Render against a client we hold, so cache effects are observable. */+ async function renderWithClient(queryClient = createTestQueryClient()) {+ function localWrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={queryClient}>+ <WorkspaceProvider>{children}</WorkspaceProvider>+ </QueryClientProvider>+ )+ }+ const rendered = renderHook(() => useWorkspace(), { wrapper: localWrapper })+ await waitFor(() => expect(rendered.result.current.isLoading).toBe(false))+ return { ...rendered, queryClient }+ }++ it('persists the new id before the refetches go out', async () => {+ // The axios interceptor reads workspace_id from localStorage, so writing+ // it after resetQueries would refetch the new workspace's screens with+ // the old workspace's header.+ workspacesApi.list.mockResolvedValue([+ makeWorkspace({ id: 'ws-a' }),+ makeWorkspace({ id: 'ws-b' }),+ ])++ const { result } = await renderWorkspace()++ await act(async () => {+ await result.current.switchWorkspace('ws-b')+ })++ expect(localStorage.getItem('workspace_id')).toBe('ws-b')+ expect(result.current.current?.id).toBe('ws-b')+ })++ it('drops the previous workspace data from the cache', async () => {+ // Every cached query was scoped to the workspace we just left. Leaving it+ // in place shows one workspace's figures under another's name.+ workspacesApi.list.mockResolvedValue([+ makeWorkspace({ id: 'ws-a' }),+ makeWorkspace({ id: 'ws-b' }),+ ])++ const { result, queryClient } = await renderWithClient()+ queryClient.setQueryData(['transactions'], [{ id: 't1', amount: 100 }])++ await act(async () => {+ await result.current.switchWorkspace('ws-b')+ })++ expect(queryClient.getQueryData(['transactions'])).toBeUndefined()+ })++ it('leaves the cache alone when switching to the workspace already active', async () => {+ // A no-op switch must not throw away data the user is looking at.+ workspacesApi.list.mockResolvedValue([makeWorkspace({ id: 'ws-a' })])++ const { result, queryClient } = await renderWithClient()+ queryClient.setQueryData(['transactions'], [{ id: 't1', amount: 100 }])++ await act(async () => {+ await result.current.switchWorkspace('ws-a')+ })++ expect(result.current.current?.id).toBe('ws-a')+ expect(queryClient.getQueryData(['transactions'])).toBeDefined()+ })+})++describe('roles', () => {+ const cases: Array<{+ role: WorkspaceRole+ canManage: boolean+ canWrite: boolean+ }> = [+ { role: 'owner', canManage: true, canWrite: true },+ { role: 'manager', canManage: true, canWrite: true },+ { role: 'editor', canManage: false, canWrite: true },+ { role: 'viewer', canManage: false, canWrite: false },+ ]++ for (const { role, canManage, canWrite } of cases) {+ it(`grants ${role} canManage=${canManage} canWrite=${canWrite}`, async () => {+ workspacesApi.list.mockResolvedValue([makeWorkspace({ role })])++ const { result } = await renderWorkspace()++ expect(result.current.role).toBe(role)+ expect(result.current.canManage).toBe(canManage)+ expect(result.current.canWrite).toBe(canWrite)+ })+ }++ it('grants nothing when there is no active workspace', async () => {+ workspacesApi.list.mockResolvedValue([])++ const { result } = await renderWorkspace()++ expect(result.current.role).toBeNull()+ expect(result.current.canManage).toBe(false)+ expect(result.current.canWrite).toBe(false)+ })+})++describe('hasModule', () => {+ it('is true only for modules the server enabled', async () => {+ workspacesApi.list.mockResolvedValue([+ makeWorkspace({ enabled_modules: ['transactions', 'budgets'] }),+ ])++ const { result } = await renderWorkspace()++ expect(result.current.hasModule('transactions')).toBe(true)+ expect(result.current.hasModule('budgets')).toBe(true)+ expect(result.current.hasModule('invoices')).toBe(false)+ })++ it('is false for everything when the workspace enables nothing', async () => {+ workspacesApi.list.mockResolvedValue([+ makeWorkspace({ enabled_modules: [] }),+ ])++ const { result } = await renderWorkspace()++ expect(result.current.enabledModules).toEqual([])+ expect(result.current.hasModule('transactions')).toBe(false)+ })++ it('is false when there is no active workspace', async () => {+ workspacesApi.list.mockResolvedValue([])++ const { result } = await renderWorkspace()++ expect(result.current.hasModule('transactions')).toBe(false)+ })+})++describe('useWorkspace', () => {+ it('refuses to be used outside the provider', () => {+ expect(() => renderHook(() => useWorkspace())).toThrow(+ 'useWorkspace must be used within a WorkspaceProvider',+ )+ })+})diff --git a/frontend/src/hooks/use-feature-flags.test.tsx b/frontend/src/hooks/use-feature-flags.test.tsxnew file mode 100644index 00000000..9c50f226--- /dev/null+++ b/frontend/src/hooks/use-feature-flags.test.tsx@@ -0,0 +1,72 @@+import type { ReactNode } from 'react'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { renderHook, waitFor } from '@testing-library/react'+import { QueryClientProvider } from '@tanstack/react-query'++import { useFeatureFlags } from '@/hooks/use-feature-flags'+import { createTestQueryClient } from '@/test/utils'++const info = vi.hoisted(() => ({ get: vi.fn() }))+vi.mock('@/lib/api', () => ({ info }))++function wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={createTestQueryClient()}>+ {children}+ </QueryClientProvider>+ )+}++beforeEach(() => {+ vi.clearAllMocks()+})++describe('useFeatureFlags', () => {+ it('reports agents on when the server says so', async () => {+ info.get.mockResolvedValue({ features: { agents: true } })++ const { result } = renderHook(() => useFeatureFlags(), { wrapper })++ await waitFor(() => expect(result.current.isLoading).toBe(false))+ expect(result.current.agentsEnabled).toBe(true)+ })++ it('reports agents off when the server says so', async () => {+ info.get.mockResolvedValue({ features: { agents: false } })++ const { result } = renderHook(() => useFeatureFlags(), { wrapper })++ await waitFor(() => expect(result.current.isLoading).toBe(false))+ expect(result.current.agentsEnabled).toBe(false)+ })++ it('defaults to off while still loading', () => {+ // AgentsRoute reads this. Defaulting to on would flash a management page+ // whose every call 404s on a deployment that never enabled agents.+ info.get.mockReturnValue(new Promise(() => {}))++ const { result } = renderHook(() => useFeatureFlags(), { wrapper })++ expect(result.current.isLoading).toBe(true)+ expect(result.current.agentsEnabled).toBe(false)+ })++ it('defaults to off when /api/info omits the features block', async () => {+ // An older backend behind a newer frontend.+ info.get.mockResolvedValue({})++ const { result } = renderHook(() => useFeatureFlags(), { wrapper })++ await waitFor(() => expect(result.current.isLoading).toBe(false))+ expect(result.current.agentsEnabled).toBe(false)+ })++ it('defaults to off when the request fails', async () => {+ info.get.mockRejectedValue(new Error('offline'))++ const { result } = renderHook(() => useFeatureFlags(), { wrapper })++ await waitFor(() => expect(result.current.isLoading).toBe(false))+ expect(result.current.agentsEnabled).toBe(false)+ })+})diff --git a/frontend/src/hooks/use-local-auth.test.tsx b/frontend/src/hooks/use-local-auth.test.tsxnew file mode 100644index 00000000..966425c8--- /dev/null+++ b/frontend/src/hooks/use-local-auth.test.tsx@@ -0,0 +1,60 @@+import type { ReactNode } from 'react'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { renderHook, waitFor } from '@testing-library/react'+import { QueryClientProvider } from '@tanstack/react-query'++import { useLocalAuthEnabled } from '@/hooks/use-local-auth'+import { createTestQueryClient } from '@/test/utils'++const authApi = vi.hoisted(() => ({ oidcConfig: vi.fn() }))+vi.mock('@/lib/api', () => ({ auth: authApi }))++function wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={createTestQueryClient()}>+ {children}+ </QueryClientProvider>+ )+}++beforeEach(() => {+ vi.clearAllMocks()+})++describe('useLocalAuthEnabled', () => {+ it('shows the local credential controls when the server allows them', async () => {+ authApi.oidcConfig.mockResolvedValue({+ enabled: true,+ provider_name: 'Keycloak',+ local_auth_enabled: true,+ })++ const { result } = renderHook(() => useLocalAuthEnabled(), { wrapper })++ await waitFor(() => expect(result.current).toBe(true))+ })++ it('hides them in an OIDC-only deployment', async () => {+ authApi.oidcConfig.mockResolvedValue({+ enabled: true,+ provider_name: 'Keycloak',+ local_auth_enabled: false,+ })++ const { result } = renderHook(() => useLocalAuthEnabled(), { wrapper })++ await waitFor(() => expect(result.current).toBe(false))+ })++ it('settles rather than hanging when the config call fails', async () => {+ // The hook pins retry:false and networkMode:'always' precisely so a+ // failure reaches the fallback instead of parking the query in pending,+ // which would hide the controls indefinitely.+ authApi.oidcConfig.mockRejectedValue(new Error('offline'))++ const { result } = renderHook(() => useLocalAuthEnabled(), { wrapper })++ await waitFor(() => expect(result.current).toBe(true))+ expect(authApi.oidcConfig).toHaveBeenCalledTimes(1)+ })+})diff --git a/frontend/src/hooks/use-privacy-mode.test.tsx b/frontend/src/hooks/use-privacy-mode.test.tsxnew file mode 100644index 00000000..a5320197--- /dev/null+++ b/frontend/src/hooks/use-privacy-mode.test.tsx@@ -0,0 +1,75 @@+import { beforeEach, describe, expect, it } from 'vitest'+import { act, renderHook } from '@testing-library/react'++import { usePrivacyMode } from '@/hooks/use-privacy-mode'++beforeEach(() => {+ localStorage.clear()+})++describe('usePrivacyMode', () => {+ it('is off by default', () => {+ const { result } = renderHook(() => usePrivacyMode())++ expect(result.current.privacyMode).toBe(false)+ })++ it('reads an already-persisted preference on mount', () => {+ localStorage.setItem('privacyMode', 'true')++ const { result } = renderHook(() => usePrivacyMode())++ expect(result.current.privacyMode).toBe(true)+ })++ it('treats any other stored value as off', () => {+ localStorage.setItem('privacyMode', 'yes')++ const { result } = renderHook(() => usePrivacyMode())++ expect(result.current.privacyMode).toBe(false)+ })++ it('toggles and persists', () => {+ const { result } = renderHook(() => usePrivacyMode())++ act(() => result.current.togglePrivacyMode())++ expect(result.current.privacyMode).toBe(true)+ expect(localStorage.getItem('privacyMode')).toBe('true')++ act(() => result.current.togglePrivacyMode())++ expect(result.current.privacyMode).toBe(false)+ expect(localStorage.getItem('privacyMode')).toBe('false')+ })++ it('passes values through untouched while off', () => {+ const { result } = renderHook(() => usePrivacyMode())++ expect(result.current.mask('R$ 12.480,00')).toBe('R$ 12.480,00')+ })++ it('replaces every value with the mask while on', () => {+ const { result } = renderHook(() => usePrivacyMode())++ act(() => result.current.togglePrivacyMode())++ expect(result.current.mask('R$ 12.480,00')).toBe(result.current.MASK)+ expect(result.current.mask('-R$ 3,20')).toBe(result.current.MASK)+ // The mask must not leak the length of what it hides.+ expect(result.current.mask('R$ 1,00')).toBe(result.current.mask('R$ 999.999,00'))+ })++ it('keeps every subscriber in step, so one toggle hides the whole screen', () => {+ // Balances are rendered by many components at once. If they did not share+ // the store, toggling would blank some and leave others showing figures.+ const first = renderHook(() => usePrivacyMode())+ const second = renderHook(() => usePrivacyMode())++ act(() => first.result.current.togglePrivacyMode())++ expect(first.result.current.privacyMode).toBe(true)+ expect(second.result.current.privacyMode).toBe(true)+ })+})diff --git a/frontend/src/lib/auth-errors.test.ts b/frontend/src/lib/auth-errors.test.tsnew file mode 100644index 00000000..10ae3182--- /dev/null+++ b/frontend/src/lib/auth-errors.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest'+import type { AxiosError } from 'axios'++import { isServerUnreachable } from '@/lib/auth-errors'++/** Minimal stand-in for the shape the auth screens actually branch on. */+function axiosError(status?: number): AxiosError {+ return (status === undefined+ ? { isAxiosError: true, response: undefined }+ : { isAxiosError: true, response: { status } }) as AxiosError+}++describe('isServerUnreachable', () => {+ it('treats a response-less failure as unreachable', () => {+ // Connection refused, DNS failure, timeout, CORS: axios gives no response.+ expect(isServerUnreachable(axiosError())).toBe(true)+ })++ it('treats 5xx as unreachable', () => {+ // A reverse proxy answering 502 while the backend container is down is+ // an outage, not a credentials problem (issue #318).+ expect(isServerUnreachable(axiosError(500))).toBe(true)+ expect(isServerUnreachable(axiosError(502))).toBe(true)+ expect(isServerUnreachable(axiosError(503))).toBe(true)+ expect(isServerUnreachable(axiosError(504))).toBe(true)+ })++ it('treats a real rejection as reachable, so the credentials message shows', () => {+ expect(isServerUnreachable(axiosError(400))).toBe(false)+ expect(isServerUnreachable(axiosError(401))).toBe(false)+ expect(isServerUnreachable(axiosError(403))).toBe(false)+ expect(isServerUnreachable(axiosError(404))).toBe(false)+ expect(isServerUnreachable(axiosError(422))).toBe(false)+ })++ it('treats 499 as reachable and 500 as not, at the boundary', () => {+ expect(isServerUnreachable(axiosError(499))).toBe(false)+ expect(isServerUnreachable(axiosError(500))).toBe(true)+ })++ it('treats a non-axios throw as unreachable rather than crashing', () => {+ expect(isServerUnreachable(new Error('boom'))).toBe(true)+ expect(isServerUnreachable(null)).toBe(true)+ expect(isServerUnreachable(undefined)).toBe(true)+ })+})diff --git a/frontend/src/lib/category-icons.test.ts b/frontend/src/lib/category-icons.test.tsnew file mode 100644index 00000000..f1d0ee1e--- /dev/null+++ b/frontend/src/lib/category-icons.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest'++import { CATEGORY_ICONS, ICON_MAP, isEmoji } from '@/lib/category-icons'++describe('CATEGORY_ICONS', () => {+ it('has no duplicate names', () => {+ // A duplicate would silently win in ICON_MAP and shadow the other entry.+ const names = CATEGORY_ICONS.map((entry) => entry.name)+ expect(new Set(names).size).toBe(names.length)+ })++ it('gives every entry a name, a label and a component', () => {+ for (const entry of CATEGORY_ICONS) {+ expect(entry.name, 'name').toMatch(/^[a-z0-9-]+$/)+ expect(entry.label, `${entry.name} label`).not.toBe('')+ expect(entry.icon, `${entry.name} icon`).toBeDefined()+ }+ })+})++describe('ICON_MAP', () => {+ it('exposes every catalogue entry for lookup', () => {+ expect(Object.keys(ICON_MAP)).toHaveLength(CATEGORY_ICONS.length)+ for (const entry of CATEGORY_ICONS) {+ expect(ICON_MAP[entry.name]).toBe(entry.icon)+ }+ })++ it('returns nothing for a name it does not know', () => {+ // CategoryIcon relies on this being undefined so it can fall back rather+ // than render a blank box.+ expect(ICON_MAP['not-a-real-icon']).toBeUndefined()+ })+})++describe('isEmoji', () => {+ it('recognises the emoji stored by older category rows', () => {+ expect(isEmoji('🍔')).toBe(true)+ expect(isEmoji('🏠')).toBe(true)+ expect(isEmoji('💰')).toBe(true)+ })++ it('rejects a lucide icon name', () => {+ expect(isEmoji('shopping-cart')).toBe(false)+ expect(isEmoji('house')).toBe(false)+ })++ it('rejects an empty string', () => {+ expect(isEmoji('')).toBe(false)+ })++ it('rejects a long string that merely contains an emoji', () => {+ expect(isEmoji('food 🍔')).toBe(false)+ })+})diff --git a/frontend/src/lib/format.test.ts b/frontend/src/lib/format.test.tsnew file mode 100644index 00000000..c3eac5d7--- /dev/null+++ b/frontend/src/lib/format.test.ts@@ -0,0 +1,160 @@+import { describe, expect, it } from 'vitest'++import {+ formatCurrency,+ resolveDateLocale,+ resolveDateOrder,+ resolveDisplayLocale,+} from '@/lib/format'++/**+ * Intl separates the symbol from the digits with a non-breaking or narrow+ * no-break space depending on locale and ICU version. Asserting on the raw+ * string makes these tests fail on a Node upgrade rather than on a real+ * regression, so collapse every kind of space to a plain one.+ */+function normalize(value: string): string {+ // JS \s already covers U+00A0 and the narrow U+202F that Intl emits.+ return value.replace(/\s/g, ' ')+}++describe('resolveDisplayLocale', () => {+ it('honours an explicit number format over the currency', () => {+ expect(resolveDisplayLocale('dot_comma', 'USD')).toBe('de-DE')+ expect(resolveDisplayLocale('comma_dot', 'BRL')).toBe('en-US')+ expect(resolveDisplayLocale('space_comma', 'BRL')).toBe('fr-FR')+ })++ it('derives the locale from the currency when the format is auto', () => {+ expect(resolveDisplayLocale('auto', 'BRL')).toBe('pt-BR')+ expect(resolveDisplayLocale('auto', 'EUR')).toBe('de-DE')+ expect(resolveDisplayLocale('auto', 'JPY')).toBe('ja-JP')+ })++ it('treats a missing number format like auto', () => {+ expect(resolveDisplayLocale(undefined, 'BRL')).toBe('pt-BR')+ })++ it('falls back when the currency is unknown or absent', () => {+ expect(resolveDisplayLocale('auto', 'XYZ')).toBe('en-US')+ expect(resolveDisplayLocale('auto', undefined)).toBe('en-US')+ expect(resolveDisplayLocale('auto', undefined, 'pt-BR')).toBe('pt-BR')+ })+})++describe('resolveDateOrder', () => {+ it('honours an explicit date format above everything else', () => {+ expect(resolveDateOrder('ymd', 'comma_dot', 'USD')).toBe('ymd')+ expect(resolveDateOrder('dmy', 'comma_dot', 'USD')).toBe('dmy')+ expect(resolveDateOrder('mdy', 'dot_comma', 'BRL')).toBe('mdy')+ })++ it('derives the order from the number format when the date format is auto', () => {+ expect(resolveDateOrder('auto', 'comma_dot', 'BRL')).toBe('mdy')+ expect(resolveDateOrder('auto', 'dot_comma', 'USD')).toBe('dmy')+ expect(resolveDateOrder('auto', 'space_comma', 'USD')).toBe('dmy')+ })++ it('falls back to the currency when both settings are auto', () => {+ expect(resolveDateOrder('auto', 'auto', 'USD')).toBe('mdy')+ expect(resolveDateOrder('auto', 'auto', 'BRL')).toBe('dmy')+ expect(resolveDateOrder('auto', 'auto', 'EUR')).toBe('dmy')+ })++ it('defaults to day-first when nothing is configured', () => {+ // Day-first covers the majority of the supported currency set, so it is+ // the safer default for a user who never opened the settings screen.+ expect(resolveDateOrder(undefined, undefined, undefined)).toBe('dmy')+ })+})++describe('resolveDateLocale', () => {+ it('picks the English regional variant that matches the order', () => {+ expect(resolveDateLocale('mdy', 'auto', 'USD', 'en')).toBe('en-US')+ expect(resolveDateLocale('dmy', 'auto', 'USD', 'en')).toBe('en-GB')+ expect(resolveDateLocale('ymd', 'auto', 'USD', 'en')).toBe('en-CA')+ })++ it('keeps a day-first language as itself, so month names stay translated', () => {+ // The whole point: a pt-BR user on the default order must not get+ // English month names.+ expect(resolveDateLocale('auto', 'auto', 'BRL', 'pt-BR')).toBe('pt-BR')+ expect(resolveDateLocale('dmy', 'auto', 'EUR', 'es')).toBe('es')+ })++ it('borrows an English proxy when a language is paired with a foreign order', () => {+ expect(resolveDateLocale('mdy', 'auto', 'BRL', 'pt-BR')).toBe('en-US')+ expect(resolveDateLocale('ymd', 'auto', 'BRL', 'pt-BR')).toBe('en-CA')+ })++ it('treats any en- variant as English', () => {+ expect(resolveDateLocale('dmy', 'auto', 'USD', 'en-GB')).toBe('en-GB')+ })+})++describe('formatCurrency', () => {+ it('renders an em dash for a missing value rather than "0"', () => {+ // A null balance means "unknown", and showing 0 would be a lie.+ expect(formatCurrency(null)).toBe('—')+ expect(formatCurrency(undefined)).toBe('—')+ })++ it('formats with the separators of the given locale', () => {+ expect(normalize(formatCurrency(1234.5, 'USD', 'en-US'))).toBe('$1,234.50')+ expect(normalize(formatCurrency(1234.5, 'BRL', 'pt-BR'))).toBe('R$ 1.234,50')+ expect(normalize(formatCurrency(1234.5, 'EUR', 'de-DE'))).toBe('1.234,50 €')+ })++ it('keeps each currency at its own precision', () => {+ // Pinning two decimals would render yen as "¥1,000.00".+ expect(normalize(formatCurrency(1000, 'JPY', 'ja-JP'))).toBe('¥1,000')+ expect(normalize(formatCurrency(1000, 'CLP', 'es-CL'))).toBe('$1.000')+ })++ it('renders negatives with a sign', () => {+ expect(normalize(formatCurrency(-42, 'USD', 'en-US'))).toBe('-$42.00')+ })++ it('never renders a negative zero', () => {+ // -0 reaches this from a summed balance that cancels out. "-R$ 0,00" on a+ // dashboard reads as a bug to the user.+ expect(normalize(formatCurrency(-0, 'BRL', 'pt-BR'))).toBe('R$ 0,00')+ expect(normalize(formatCurrency(-0, 'USD', 'en-US'))).toBe('$0.00')+ })++ it('swallows sub-cent residue left by FX conversion instead of signing it', () => {+ expect(normalize(formatCurrency(-0.001, 'USD', 'en-US'))).toBe('$0.00')+ expect(normalize(formatCurrency(-0.004, 'USD', 'en-US'))).toBe('$0.00')+ })++ it('still signs a value that rounds to a real cent', () => {+ expect(normalize(formatCurrency(-0.006, 'USD', 'en-US'))).toBe('-$0.01')+ })++ it('applies the zero rule at the currency precision, not always two decimals', () => {+ // JPY has no minor unit, so anything under half a yen is zero here.+ expect(normalize(formatCurrency(-0.4, 'JPY', 'ja-JP'))).toBe('¥0')+ })++ it('falls back to USD in en-US when the locale is malformed', () => {+ // i18next reads ?lng= from the querystring, so a hand-typed URL can put+ // junk in here. Throwing would blank the whole screen.+ expect(normalize(formatCurrency(10, 'USD', 'not a locale'))).toBe('$10.00')+ })++ it('falls back when the currency code is malformed', () => {+ expect(normalize(formatCurrency(10, 'not-a-currency', 'en-US'))).toBe('$10.00')+ })++ it('treats an empty currency as USD', () => {+ expect(normalize(formatCurrency(10, '', 'en-US'))).toBe('$10.00')+ })++ it('defaults to USD in en-US with no options', () => {+ expect(normalize(formatCurrency(5))).toBe('$5.00')+ })++ it('formats zero without a sign', () => {+ expect(normalize(formatCurrency(0, 'USD', 'en-US'))).toBe('$0.00')+ })+})diff --git a/frontend/src/lib/modules.test.ts b/frontend/src/lib/modules.test.tsnew file mode 100644index 00000000..95fd561a--- /dev/null+++ b/frontend/src/lib/modules.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from 'vitest'++import { MODULE_IDS, isModuleId } from '@/lib/modules'++describe('MODULE_IDS', () => {+ it('has no duplicates', () => {+ expect(new Set(MODULE_IDS).size).toBe(MODULE_IDS.length)+ })++ it('lists every module the router gates on', () => {+ // App.tsx wraps routes in <ModuleRoute module="..."> using these exact+ // strings. A rename here without one there renders a permanently+ // blocked page, so pin the set.+ expect([...MODULE_IDS].sort()).toEqual(+ [+ 'accounts',+ 'assets',+ 'budgets',+ 'categories',+ 'goals',+ 'import',+ 'invoices',+ 'payees',+ 'recurring',+ 'reports',+ 'rules',+ 'split_groups',+ 'transactions',+ ].sort(),+ )+ })+})++describe('isModuleId', () => {+ it('accepts every known module', () => {+ for (const id of MODULE_IDS) {+ expect(isModuleId(id)).toBe(true)+ }+ })++ it('rejects anything else', () => {+ expect(isModuleId('dashboard')).toBe(false)+ expect(isModuleId('agents')).toBe(false)+ expect(isModuleId('')).toBe(false)+ expect(isModuleId('Transactions')).toBe(false)+ })++ it('is not fooled by Object.prototype members', () => {+ // `includes` is safe here, but a future switch to a plain-object lookup+ // would regress on exactly these.+ expect(isModuleId('constructor')).toBe(false)+ expect(isModuleId('toString')).toBe(false)+ })+})diff --git a/frontend/src/lib/month-utils.test.ts b/frontend/src/lib/month-utils.test.tsnew file mode 100644index 00000000..8a5d9647--- /dev/null+++ b/frontend/src/lib/month-utils.test.ts@@ -0,0 +1,134 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++import {+ currentMonth,+ monthFromRange,+ monthLabel,+ monthLastDay,+ monthRange,+ shiftMonth,+} from '@/lib/month-utils'++afterEach(() => {+ vi.useRealTimers()+})++describe('currentMonth', () => {+ it('returns the browser-local month, zero padded', () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date(2026, 0, 15))++ expect(currentMonth()).toBe('2026-01')+ })++ it('pads a double-digit month correctly too', () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date(2026, 10, 3))++ expect(currentMonth()).toBe('2026-11')+ })+})++describe('shiftMonth', () => {+ it('steps forward and back within a year', () => {+ expect(shiftMonth('2026-06', 1)).toBe('2026-07')+ expect(shiftMonth('2026-06', -1)).toBe('2026-05')+ })++ it('rolls over the year boundary in both directions', () => {+ expect(shiftMonth('2026-12', 1)).toBe('2027-01')+ expect(shiftMonth('2026-01', -1)).toBe('2025-12')+ })++ it('handles multi-month jumps', () => {+ expect(shiftMonth('2026-06', 12)).toBe('2027-06')+ expect(shiftMonth('2026-06', -18)).toBe('2024-12')+ })++ it('returns the same month for a zero shift', () => {+ expect(shiftMonth('2026-06', 0)).toBe('2026-06')+ })+})++describe('monthLastDay', () => {+ it('knows the length of each month', () => {+ expect(monthLastDay('2026-01')).toBe(31)+ expect(monthLastDay('2026-04')).toBe(30)+ })++ it('is leap-year aware', () => {+ expect(monthLastDay('2024-02')).toBe(29)+ expect(monthLastDay('2026-02')).toBe(28)+ // 2000 is a leap year, 1900 is not.+ expect(monthLastDay('2000-02')).toBe(29)+ expect(monthLastDay('1900-02')).toBe(28)+ })+})++describe('monthRange', () => {+ it('spans the whole month as timezone-naive strings', () => {+ expect(monthRange('2026-06')).toEqual({ from: '2026-06-01', to: '2026-06-30' })+ expect(monthRange('2026-01')).toEqual({ from: '2026-01-01', to: '2026-01-31' })+ })++ it('pads a short last day', () => {+ expect(monthRange('2026-02')).toEqual({ from: '2026-02-01', to: '2026-02-28' })+ })++ it('carries no time component, matching the ?from/?to params', () => {+ const { from, to } = monthRange('2026-06')+ expect(from).not.toMatch(/T/)+ expect(to).not.toMatch(/T/)+ })+})++describe('monthLabel', () => {+ it('localises the month name', () => {+ expect(monthLabel('2026-05', 'en-US')).toMatch(/May/)+ expect(monthLabel('2026-05', 'pt-BR')).toMatch(/maio/i)+ })++ it('includes the year', () => {+ expect(monthLabel('2026-05', 'en-US')).toMatch(/2026/)+ })++ it('names the right month at both ends of the year', () => {+ // Building the date on day 2 rather than day 1 is what keeps a negative+ // UTC offset from rolling the label back into the previous month.+ expect(monthLabel('2026-01', 'en-US')).toMatch(/January/)+ expect(monthLabel('2026-12', 'en-US')).toMatch(/December/)+ })+})++describe('monthFromRange', () => {+ it('recognises a range that spans exactly one month', () => {+ expect(monthFromRange('2026-06-01', '2026-06-30')).toBe('2026-06')+ expect(monthFromRange('2024-02-01', '2024-02-29')).toBe('2024-02')+ })++ it('rejects a range that stops short of the month end', () => {+ // A custom range must not make the stepper claim a whole month is+ // selected, or stepping would silently widen the user's filter.+ expect(monthFromRange('2026-06-01', '2026-06-29')).toBeNull()+ })++ it('rejects a range that starts mid-month', () => {+ expect(monthFromRange('2026-06-02', '2026-06-30')).toBeNull()+ })++ it('rejects a range spanning several months', () => {+ expect(monthFromRange('2026-06-01', '2026-07-31')).toBeNull()+ })++ it('returns null when either end is missing', () => {+ expect(monthFromRange(null, '2026-06-30')).toBeNull()+ expect(monthFromRange('2026-06-01', null)).toBeNull()+ expect(monthFromRange(undefined, undefined)).toBeNull()+ expect(monthFromRange('', '')).toBeNull()+ })++ it('round-trips with monthRange', () => {+ const { from, to } = monthRange('2026-11')+ expect(monthFromRange(from, to)).toBe('2026-11')+ })+})diff --git a/frontend/src/lib/relative-time.test.ts b/frontend/src/lib/relative-time.test.tsnew file mode 100644index 00000000..2e7c4563--- /dev/null+++ b/frontend/src/lib/relative-time.test.ts@@ -0,0 +1,58 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { formatRelative } from '@/lib/relative-time'++const NOW = new Date('2026-06-15T12:00:00.000Z')++/** ISO string for `minutes` before the frozen now. */+function ago(minutes: number): string {+ return new Date(NOW.getTime() - minutes * 60_000).toISOString()+}++describe('formatRelative', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ vi.setSystemTime(NOW)+ })++ afterEach(() => {+ vi.useRealTimers()+ })++ it('collapses anything under a minute to "now"', () => {+ expect(formatRelative(ago(0))).toBe('now')+ expect(formatRelative(ago(0.5))).toBe('now')+ })++ it('counts whole minutes up to an hour', () => {+ expect(formatRelative(ago(1))).toBe('1m ago')+ expect(formatRelative(ago(59))).toBe('59m ago')+ })++ it('switches to hours at sixty minutes', () => {+ expect(formatRelative(ago(60))).toBe('1h ago')+ expect(formatRelative(ago(60 * 23))).toBe('23h ago')+ })++ it('says yesterday for the first full day', () => {+ expect(formatRelative(ago(60 * 24))).toBe('yesterday')+ expect(formatRelative(ago(60 * 47))).toBe('yesterday')+ })++ it('counts days up to a week', () => {+ expect(formatRelative(ago(60 * 48))).toBe('2d ago')+ expect(formatRelative(ago(60 * 24 * 6))).toBe('6d ago')+ })++ it('falls back to a calendar date past a week', () => {+ const result = formatRelative(ago(60 * 24 * 30))+ expect(result).not.toMatch(/ago|now|yesterday/)+ expect(result).toMatch(/May/)+ })++ it('returns an empty string for an unparseable timestamp', () => {+ // Never render "NaNm ago" into the UI.+ expect(formatRelative('not a date')).toBe('')+ expect(formatRelative('')).toBe('')+ })+})diff --git a/frontend/src/lib/semver.test.ts b/frontend/src/lib/semver.test.tsnew file mode 100644index 00000000..c677a83b--- /dev/null+++ b/frontend/src/lib/semver.test.ts@@ -0,0 +1,107 @@+import { describe, expect, it } from 'vitest'++import { compareSemver, isUpdateAvailable, parseSemver } from '@/lib/semver'++describe('parseSemver', () => {+ it('parses a plain version', () => {+ expect(parseSemver('1.2.3')).toEqual({+ major: 1,+ minor: 2,+ patch: 3,+ prerelease: [],+ })+ })++ it('accepts the v prefix that GitHub tags carry', () => {+ expect(parseSemver('v0.14.5')).toMatchObject({+ major: 0,+ minor: 14,+ patch: 5,+ })+ })++ it('trims surrounding whitespace', () => {+ expect(parseSemver(' v1.0.0 ')).toMatchObject({ major: 1 })+ })++ it('splits the prerelease into identifiers', () => {+ expect(parseSemver('1.0.0-rc.2')?.prerelease).toEqual(['rc', '2'])+ })++ it('ignores build metadata', () => {+ expect(parseSemver('1.0.0+build.7')).toMatchObject({+ major: 1,+ prerelease: [],+ })+ })++ it('returns null for anything that is not a version', () => {+ expect(parseSemver('')).toBeNull()+ expect(parseSemver(null)).toBeNull()+ expect(parseSemver(undefined)).toBeNull()+ expect(parseSemver('latest')).toBeNull()+ expect(parseSemver('1.2')).toBeNull()+ expect(parseSemver('1.2.3.4')).toBeNull()+ })+})++describe('compareSemver', () => {+ const parse = (v: string) => parseSemver(v)!++ it('orders by major, then minor, then patch', () => {+ expect(compareSemver(parse('2.0.0'), parse('1.9.9'))).toBeGreaterThan(0)+ expect(compareSemver(parse('1.3.0'), parse('1.2.9'))).toBeGreaterThan(0)+ expect(compareSemver(parse('1.2.4'), parse('1.2.3'))).toBeGreaterThan(0)+ })++ it('treats equal versions as equal', () => {+ expect(compareSemver(parse('1.2.3'), parse('1.2.3'))).toBe(0)+ })++ it('ranks a stable release above its own prerelease', () => {+ expect(compareSemver(parse('1.0.0'), parse('1.0.0-rc.1'))).toBeGreaterThan(0)+ expect(compareSemver(parse('1.0.0-rc.1'), parse('1.0.0'))).toBeLessThan(0)+ })++ it('compares numeric prerelease identifiers numerically', () => {+ // String comparison would put rc.10 below rc.9.+ expect(compareSemver(parse('1.0.0-rc.10'), parse('1.0.0-rc.9'))).toBeGreaterThan(0)+ })++ it('ranks a numeric identifier below an alphanumeric one', () => {+ expect(compareSemver(parse('1.0.0-1'), parse('1.0.0-alpha'))).toBeLessThan(0)+ })++ it('ranks a longer prerelease above its prefix', () => {+ expect(compareSemver(parse('1.0.0-rc.1'), parse('1.0.0-rc'))).toBeGreaterThan(0)+ })+})++describe('isUpdateAvailable', () => {+ it('is true only when the latest release is genuinely newer', () => {+ expect(isUpdateAvailable('0.14.5', '0.14.6')).toBe(true)+ expect(isUpdateAvailable('0.14.5', 'v0.15.0')).toBe(true)+ })++ it('is false when already current or ahead', () => {+ expect(isUpdateAvailable('0.14.5', '0.14.5')).toBe(false)+ expect(isUpdateAvailable('0.15.0', '0.14.5')).toBe(false)+ })++ it('does not offer a prerelease as an update to a stable install', () => {+ expect(isUpdateAvailable('1.0.0', '1.0.0-rc.1')).toBe(false)+ })++ it('offers the stable release to someone on its prerelease', () => {+ expect(isUpdateAvailable('1.0.0-rc.1', '1.0.0')).toBe(true)+ })++ it('stays quiet when either version is unreadable', () => {+ // A dev build reports something that is not a version. Nagging the user+ // with a bogus update banner is worse than saying nothing.+ expect(isUpdateAvailable('dev', '1.0.0')).toBe(false)+ expect(isUpdateAvailable('1.0.0', 'nightly')).toBe(false)+ expect(isUpdateAvailable(null, '1.0.0')).toBe(false)+ expect(isUpdateAvailable('1.0.0', undefined)).toBe(false)+ })+})diff --git a/frontend/src/lib/theme-utils.test.ts b/frontend/src/lib/theme-utils.test.tsnew file mode 100644index 00000000..9d7fbbda--- /dev/null+++ b/frontend/src/lib/theme-utils.test.ts@@ -0,0 +1,84 @@+import { afterEach, describe, expect, it } from 'vitest'++import { setThemeBasedOnSystem } from '@/lib/theme-utils'++const VARS = [+ '--primary',+ '--ring',+ '--sidebar-primary',+ '--accent',+ '--accent-foreground',+ '--muted',+ '--sidebar-accent',+ '--sidebar-accent-foreground',+]++function readVar(name: string): string {+ return document.documentElement.style.getPropertyValue(name)+}++afterEach(() => {+ for (const name of VARS) {+ document.documentElement.style.removeProperty(name)+ }+})++describe('setThemeBasedOnSystem', () => {+ it('applies the light colour on a light theme', () => {+ setThemeBasedOnSystem('#ff0000', '#0000ff', 'light')++ expect(readVar('--primary')).toBe('#ff0000')+ expect(readVar('--ring')).toBe('#ff0000')+ expect(readVar('--sidebar-primary')).toBe('#ff0000')+ })++ it('applies the dark colour on a dark theme', () => {+ setThemeBasedOnSystem('#ff0000', '#0000ff', 'dark')++ expect(readVar('--primary')).toBe('#0000ff')+ })++ it('treats an unknown theme as light', () => {+ setThemeBasedOnSystem('#ff0000', '#0000ff', undefined)++ expect(readVar('--primary')).toBe('#ff0000')+ })++ it('mixes toward black on dark and toward white on light', () => {+ // Getting this backwards produces an accent that vanishes into the+ // background it sits on.+ setThemeBasedOnSystem('#ff0000', '#0000ff', 'dark')+ expect(readVar('--accent')).toContain('black')+ expect(readVar('--accent-foreground')).toContain('white')++ setThemeBasedOnSystem('#ff0000', '#0000ff', 'light')+ expect(readVar('--accent')).toContain('white')+ expect(readVar('--accent-foreground')).toContain('black')+ })++ it('derives every accent variable from the chosen colour', () => {+ setThemeBasedOnSystem('#ff0000', '#0000ff', 'light')++ for (const name of VARS) {+ expect(readVar(name), name).not.toBe('')+ }+ })++ it('clears the overrides when the deployment sets no colour', () => {+ // Leaving stale properties behind would pin a previous admin's brand+ // colour after they cleared it.+ setThemeBasedOnSystem('#ff0000', '#0000ff', 'light')+ setThemeBasedOnSystem(null, null, 'light')++ for (const name of VARS) {+ expect(readVar(name), name).toBe('')+ }+ })++ it('clears when only the colour for the active theme is missing', () => {+ setThemeBasedOnSystem('#ff0000', '#0000ff', 'light')+ setThemeBasedOnSystem(null, '#0000ff', 'light')++ expect(readVar('--primary')).toBe('')+ })+})diff --git a/frontend/src/lib/utils.test.ts b/frontend/src/lib/utils.test.tsnew file mode 100644index 00000000..6186c4c9--- /dev/null+++ b/frontend/src/lib/utils.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest'++import { cn, normalizeText } from '@/lib/utils'++describe('cn', () => {+ it('joins class names', () => {+ expect(cn('a', 'b')).toBe('a b')+ })++ it('drops falsy entries', () => {+ expect(cn('a', false, null, undefined, '', 'b')).toBe('a b')+ })++ it('supports conditional objects and arrays', () => {+ expect(cn({ a: true, b: false }, ['c'])).toBe('a c')+ })++ it('lets the last conflicting Tailwind utility win', () => {+ // This is the reason cn exists: a caller className has to be able to+ // override a component's default padding rather than fight it.+ expect(cn('px-2', 'px-4')).toBe('px-4')+ expect(cn('text-sm', 'text-lg')).toBe('text-lg')+ })++ it('keeps utilities that do not conflict', () => {+ expect(cn('px-2', 'py-4')).toBe('px-2 py-4')+ })++ it('returns an empty string with no input', () => {+ expect(cn()).toBe('')+ })+})++describe('normalizeText', () => {+ it('lowercases', () => {+ expect(normalizeText('Orçamento')).toBe('orcamento')+ })++ it('strips diacritics so an unaccented search still matches', () => {+ // Typing "orcamento" has to find "Orçamento"; Brazilian users rarely+ // type the cedilla into a search box.+ expect(normalizeText('Orçamento')).toBe('orcamento')+ expect(normalizeText('Salário')).toBe('salario')+ expect(normalizeText('Café')).toBe('cafe')+ expect(normalizeText('São Paulo')).toBe('sao paulo')+ })++ it('handles other supported alphabets without dropping characters', () => {+ expect(normalizeText('Żywność')).toBe('zywnosc')+ expect(normalizeText('Ünal')).toBe('unal')+ })++ it('leaves plain ASCII untouched apart from case', () => {+ expect(normalizeText('Groceries')).toBe('groceries')+ })++ it('returns an empty string unchanged', () => {+ expect(normalizeText('')).toBe('')+ })++ it('produces a value that substring matching can use directly', () => {+ expect(normalizeText('Conta Corrente').includes(normalizeText('corrente'))).toBe(+ true,+ )+ })+})diff --git a/frontend/src/lib/workspace-kinds.test.ts b/frontend/src/lib/workspace-kinds.test.tsnew file mode 100644index 00000000..966d9105--- /dev/null+++ b/frontend/src/lib/workspace-kinds.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest'++import i18n from '@/lib/i18n'+import {+ WORKSPACE_KINDS,+ WORKSPACE_KIND_ICON,+ WORKSPACE_KIND_LABEL_KEY,+} from '@/lib/workspace-kinds'++describe('WORKSPACE_KINDS', () => {+ it('has no duplicates', () => {+ expect(new Set(WORKSPACE_KINDS).size).toBe(WORKSPACE_KINDS.length)+ })++ it('gives every kind a label key and an icon', () => {+ for (const kind of WORKSPACE_KINDS) {+ expect(WORKSPACE_KIND_LABEL_KEY[kind], `${kind} label key`).toBeDefined()+ expect(WORKSPACE_KIND_ICON[kind], `${kind} icon`).toBeDefined()+ }+ })++ it('resolves every label key against the English bundle', () => {+ // A missing key renders as "workspace.kindPersonal" in the create dialog.+ for (const kind of WORKSPACE_KINDS) {+ const key = WORKSPACE_KIND_LABEL_KEY[kind]+ expect(i18n.exists(key), `${key} missing from en`).toBe(true)+ expect(i18n.t(key), key).not.toBe(key)+ }+ })++ it('resolves every label key in pt-BR as well', () => {+ // en and pt-BR are the two locales that must always be complete.+ //+ // fallbackLng:false is load-bearing. Without it i18next resolves through+ // the English fallback, so `exists(key, { lng: 'pt-BR' })` answers true for+ // a key pt-BR does not have and this test proves nothing.+ for (const kind of WORKSPACE_KINDS) {+ const key = WORKSPACE_KIND_LABEL_KEY[kind]+ expect(+ i18n.exists(key, { lng: 'pt-BR', fallbackLng: false }),+ `${key} missing from pt-BR`,+ ).toBe(true)+ }+ })++ it('the pt-BR check would actually catch a missing key', () => {+ // Guards the guard: accounts.multiInstitutionLink ships in en only, so a+ // check that passes here is resolving through the fallback.+ expect(+ i18n.exists('accounts.multiInstitutionLink', {+ lng: 'pt-BR',+ fallbackLng: false,+ }),+ ).toBe(false)+ })+})diff --git a/frontend/src/pages/login.test.tsx b/frontend/src/pages/login.test.tsxnew file mode 100644index 00000000..ccdca82a--- /dev/null+++ b/frontend/src/pages/login.test.tsx@@ -0,0 +1,205 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { screen, waitFor } from '@testing-library/react'+import type { AxiosError } from 'axios'++import LoginPage from '@/pages/login'+import { renderWithProviders, t } from '@/test/utils'++const navigate = vi.hoisted(() => vi.fn())+vi.mock('react-router-dom', async (importOriginal) => ({+ ...(await importOriginal<typeof import('react-router-dom')>()),+ useNavigate: () => navigate,+}))++const authContext = vi.hoisted(() => ({+ login: vi.fn(),+ verify2fa: vi.fn(),+ loginWithToken: vi.fn(),+ token: null as string | null,+}))+vi.mock('@/contexts/auth-context', () => ({ useAuth: () => authContext }))++const api = vi.hoisted(() => ({+ setup: { status: vi.fn() },+ auth: { oidcConfig: vi.fn() },+ admin: { registrationStatus: vi.fn(), defaultColors: vi.fn() },+}))+vi.mock('@/lib/api', () => ({+ setup: api.setup,+ auth: api.auth,+ admin: api.admin,+}))++vi.mock('@/lib/webauthn', () => ({+ isPasskeySupported: () => false,+ passkeyFailure: () => 'unknown',+ startPasskeyAuthentication: vi.fn(),+}))++vi.mock('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'dark' }) }))++/** Build the axios-shaped rejection the page branches on. */+function httpError(status?: number): AxiosError {+ return (status === undefined+ ? { isAxiosError: true, response: undefined }+ : { isAxiosError: true, response: { status } }) as AxiosError+}++beforeEach(() => {+ vi.clearAllMocks()+ authContext.token = null+ api.setup.status.mockResolvedValue({ has_users: true })+ api.auth.oidcConfig.mockResolvedValue({+ enabled: false,+ provider_name: 'OIDC',+ local_auth_enabled: true,+ })+ api.admin.registrationStatus.mockResolvedValue({ enabled: true })+ api.admin.defaultColors.mockResolvedValue({ light: null, dark: null })+})++async function renderLogin() {+ const rendered = renderWithProviders(<LoginPage />, { route: '/login' })+ await screen.findByLabelText(t('auth.email'))+ return rendered+}++describe('LoginPage', () => {+ it('renders the credentials form', async () => {+ await renderLogin()++ expect(screen.getByLabelText(t('auth.email'))).toBeInTheDocument()+ expect(screen.getByLabelText(t('auth.password'))).toBeInTheDocument()+ expect(+ screen.getByRole('button', { name: t('auth.login') }),+ ).toBeInTheDocument()+ })++ it('signs in and lands on the dashboard', async () => {+ authContext.login.mockResolvedValue({ requires_2fa: false })+ const { user } = await renderLogin()++ await user.type(screen.getByLabelText(t('auth.email')), '[email protected]')+ await user.type(screen.getByLabelText(t('auth.password')), 'secret')+ await user.click(screen.getByRole('button', { name: t('auth.login') }))++ await waitFor(() =>+ expect(authContext.login).toHaveBeenCalledWith(+ '[email protected]',+ 'secret',+ ),+ )+ await waitFor(() => expect(navigate).toHaveBeenCalledWith('/'))+ })++ it('asks for the second factor instead of navigating when 2FA is on', async () => {+ authContext.login.mockResolvedValue({+ requires_2fa: true,+ temp_token: 'temp',+ available_methods: ['totp'],+ })+ const { user } = await renderLogin()++ await user.type(screen.getByLabelText(t('auth.email')), '[email protected]')+ await user.type(screen.getByLabelText(t('auth.password')), 'secret')+ await user.click(screen.getByRole('button', { name: t('auth.login') }))++ expect(await screen.findByText(t('auth.twoFactorTitle'))).toBeInTheDocument()+ expect(navigate).not.toHaveBeenCalledWith('/')+ })++ it('tells the user their credentials were rejected', async () => {+ authContext.login.mockRejectedValue(httpError(401))+ const { user } = await renderLogin()++ await user.type(screen.getByLabelText(t('auth.email')), '[email protected]')+ await user.type(screen.getByLabelText(t('auth.password')), 'wrong')+ await user.click(screen.getByRole('button', { name: t('auth.login') }))++ expect(+ await screen.findByText(t('auth.invalidCredentials')),+ ).toBeInTheDocument()+ })++ it('distinguishes an outage from a wrong password', async () => {+ // Issue #318: collapsing every failure into "invalid credentials" made a+ // stopped backend look like the user's own mistake.+ authContext.login.mockRejectedValue(httpError())+ const { user } = await renderLogin()++ await user.type(screen.getByLabelText(t('auth.email')), '[email protected]')+ await user.type(screen.getByLabelText(t('auth.password')), 'right')+ await user.click(screen.getByRole('button', { name: t('auth.login') }))++ expect(await screen.findByText(t('auth.serverError'))).toBeInTheDocument()+ expect(+ screen.queryByText(t('auth.invalidCredentials')),+ ).not.toBeInTheDocument()+ })++ it('reports a 5xx as an outage too', async () => {+ authContext.login.mockRejectedValue(httpError(502))+ const { user } = await renderLogin()++ await user.type(screen.getByLabelText(t('auth.email')), '[email protected]')+ await user.type(screen.getByLabelText(t('auth.password')), 'right')+ await user.click(screen.getByRole('button', { name: t('auth.login') }))++ expect(await screen.findByText(t('auth.serverError'))).toBeInTheDocument()+ })++ it('names rate limiting rather than blaming the password', async () => {+ authContext.login.mockRejectedValue(httpError(429))+ const { user } = await renderLogin()++ await user.type(screen.getByLabelText(t('auth.email')), '[email protected]')+ await user.type(screen.getByLabelText(t('auth.password')), 'right')+ await user.click(screen.getByRole('button', { name: t('auth.login') }))++ expect(await screen.findByText(t('auth.tooManyAttempts'))).toBeInTheDocument()+ })++ it('sends an already-signed-in visitor away from the login screen', async () => {+ authContext.token = 'jwt'++ renderWithProviders(<LoginPage />, { route: '/login' })++ await waitFor(() =>+ expect(navigate).toHaveBeenCalledWith('/', { replace: true }),+ )+ })++ it('redirects a fresh install to the setup wizard', async () => {+ // No users yet: sending someone to a login form they cannot pass is a+ // dead end.+ api.setup.status.mockResolvedValue({ has_users: false })++ renderWithProviders(<LoginPage />, { route: '/login' })++ await waitFor(() =>+ expect(navigate).toHaveBeenCalledWith('/setup', { replace: true }),+ )+ })++ it('offers registration when the server allows it', async () => {+ await renderLogin()++ expect(+ await screen.findByRole('link', { name: t('auth.register') }),+ ).toBeInTheDocument()+ })++ it('survives the optional config calls failing', async () => {+ // A reverse proxy that blocks /api/admin must not blank the login form.+ api.admin.registrationStatus.mockRejectedValue(new Error('403'))+ api.admin.defaultColors.mockRejectedValue(new Error('403'))+ api.auth.oidcConfig.mockRejectedValue(new Error('500'))++ await renderLogin()++ expect(screen.getByLabelText(t('auth.email'))).toBeInTheDocument()+ expect(+ screen.getByRole('button', { name: t('auth.login') }),+ ).toBeInTheDocument()+ })+})diff --git a/frontend/src/pages/pages.contract.test.ts b/frontend/src/pages/pages.contract.test.tsnew file mode 100644index 00000000..10749081--- /dev/null+++ b/frontend/src/pages/pages.contract.test.ts@@ -0,0 +1,51 @@+/**+ * Evaluates every page module.+ *+ * Every route in App.tsx is a `lazy(() => import(...))`. A page that fails to+ * evaluate — a bad export, a circular import, a top-level call into something+ * undefined — does not fail the build, because `tsc` checks modules in+ * isolation and Vite only resolves the chunk when a user navigates to it. The+ * first person to find out is whoever clicks the nav link.+ *+ * The list comes from a glob rather than being written out, so adding a page+ * covers it automatically. A hardcoded list plus an "is this list complete"+ * assertion would fail every PR that adds a page, which teaches contributors+ * that this file is an obstacle rather than a safety net.+ */+import { describe, expect, it } from 'vitest'++const modules = import.meta.glob('@/pages/**/*.tsx') as Record<+ string,+ () => Promise<Record<string, unknown>>+>++const paths = Object.keys(modules)+ .filter((path) => !path.includes('.test.'))+ .sort()++describe('page modules', () => {+ it('finds the page tree', () => {+ // If a refactor moves pages elsewhere, this suite would otherwise pass+ // silently over an empty list.+ expect(paths.length).toBeGreaterThan(20)+ })++ for (const path of paths) {+ const name = path.replace(/^.*\/pages\//, '').replace(/\.tsx$/, '')++ it(`${name} evaluates and default-exports a component`, async () => {+ const module = await modules[path]()++ // A plain page is a function; one wrapped in memo or forwardRef is an+ // object carrying $$typeof. Both are renderable.+ const component = module.default+ expect(component).toBeDefined()+ expect(+ typeof component === 'function' ||+ (typeof component === 'object' &&+ component !== null &&+ '$$typeof' in component),+ ).toBe(true)+ })+ }+})diff --git a/frontend/src/pages/register.test.tsx b/frontend/src/pages/register.test.tsxnew file mode 100644index 00000000..c02bb094--- /dev/null+++ b/frontend/src/pages/register.test.tsx@@ -0,0 +1,186 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { screen, waitFor } from '@testing-library/react'+import type { AxiosError } from 'axios'++import RegisterPage from '@/pages/register'+import { renderWithProviders, t } from '@/test/utils'++const navigate = vi.hoisted(() => vi.fn())+vi.mock('react-router-dom', async (importOriginal) => ({+ ...(await importOriginal<typeof import('react-router-dom')>()),+ useNavigate: () => navigate,+}))++const authContext = vi.hoisted(() => ({ register: vi.fn() }))+vi.mock('@/contexts/auth-context', () => ({ useAuth: () => authContext }))++const api = vi.hoisted(() => ({+ admin: { registrationStatus: vi.fn(), defaultColors: vi.fn() },+ auth: { oidcConfig: vi.fn() },+}))+vi.mock('@/lib/api', () => ({ admin: api.admin, auth: api.auth }))++vi.mock('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'dark' }) }))++function httpError(status?: number): AxiosError {+ return (status === undefined+ ? { isAxiosError: true, response: undefined }+ : { isAxiosError: true, response: { status } }) as AxiosError+}++beforeEach(() => {+ vi.clearAllMocks()+ api.admin.registrationStatus.mockResolvedValue({ enabled: true })+ api.admin.defaultColors.mockResolvedValue({ light: null, dark: null })+ api.auth.oidcConfig.mockResolvedValue({+ enabled: false,+ provider_name: 'OIDC',+ local_auth_enabled: true,+ })+})++async function renderRegister() {+ const rendered = renderWithProviders(<RegisterPage />, { route: '/register' })+ await screen.findByLabelText(t('auth.email'))+ return rendered+}++async function fill(+ user: Awaited<ReturnType<typeof renderRegister>>['user'],+ { password = 'sufficiently-long', confirm = 'sufficiently-long' } = {},+) {+ await user.type(screen.getByLabelText(t('auth.email')), '[email protected]')+ await user.type(screen.getByLabelText(t('auth.password')), password)+ await user.type(screen.getByLabelText(t('auth.confirmPassword')), confirm)+}++describe('RegisterPage', () => {+ it('renders the signup form', async () => {+ await renderRegister()++ expect(screen.getByLabelText(t('auth.email'))).toBeInTheDocument()+ expect(screen.getByLabelText(t('auth.password'))).toBeInTheDocument()+ expect(screen.getByLabelText(t('auth.confirmPassword'))).toBeInTheDocument()+ expect(screen.getByLabelText(t('auth.currency'))).toBeInTheDocument()+ })++ it('registers and lands on the dashboard', async () => {+ authContext.register.mockResolvedValue(undefined)+ const { user } = await renderRegister()++ await fill(user)+ await user.click(screen.getByRole('button', { name: t('auth.register') }))++ // Exactly once: reading calls[0] alone would wave through a double+ // submit, which on this endpoint means a second account attempt.+ await waitFor(() => expect(authContext.register).toHaveBeenCalledTimes(1))+ // Assert the whole payload: sending the confirm field as the password, or+ // dropping the currency, is exactly the kind of slip a looser assertion+ // on the email alone would wave through.+ const [email, password, preferences] = authContext.register.mock.calls[0]+ expect(email).toBe('[email protected]')+ expect(password).toBe('sufficiently-long')+ expect(preferences).toEqual({ currency_display: 'USD', language: 'en' })+ await waitFor(() => expect(navigate).toHaveBeenCalledWith('/'))+ })++ it('refuses to submit when the two passwords differ', async () => {+ const { user } = await renderRegister()++ await fill(user, { password: 'first-password', confirm: 'second-password' })+ await user.click(screen.getByRole('button', { name: t('auth.register') }))++ expect(+ await screen.findByText(t('auth.passwordMismatch')),+ ).toBeInTheDocument()+ // Catching it client-side keeps a guaranteed-doomed request off the wire.+ expect(authContext.register).not.toHaveBeenCalled()+ })++ it('refuses a password that is too short', async () => {+ const { user } = await renderRegister()++ await fill(user, { password: 'short', confirm: 'short' })+ await user.click(screen.getByRole('button', { name: t('auth.register') }))++ expect(+ await screen.findByText(t('auth.passwordTooShort')),+ ).toBeInTheDocument()+ expect(authContext.register).not.toHaveBeenCalled()+ })++ it('distinguishes an outage from a rejected signup', async () => {+ authContext.register.mockRejectedValue(httpError())+ const { user } = await renderRegister()++ await fill(user)+ await user.click(screen.getByRole('button', { name: t('auth.register') }))++ expect(await screen.findByText(t('auth.serverError'))).toBeInTheDocument()+ })++ it('names rate limiting', async () => {+ authContext.register.mockRejectedValue(httpError(429))+ const { user } = await renderRegister()++ await fill(user)+ await user.click(screen.getByRole('button', { name: t('auth.register') }))++ expect(await screen.findByText(t('auth.tooManyAttempts'))).toBeInTheDocument()+ })++ it('reports a rejected signup', async () => {+ authContext.register.mockRejectedValue(httpError(400))+ const { user } = await renderRegister()++ await fill(user)+ await user.click(screen.getByRole('button', { name: t('auth.register') }))++ expect(+ await screen.findByText(t('auth.registrationError')),+ ).toBeInTheDocument()+ })++ it('turns visitors away when registration is closed', async () => {+ // Otherwise a self-hosted admin who disabled signups still hands out a+ // working form whose submit always fails.+ api.admin.registrationStatus.mockResolvedValue({ enabled: false })++ renderWithProviders(<RegisterPage />, { route: '/register' })++ await waitFor(() =>+ expect(navigate).toHaveBeenCalledWith('/login', { replace: true }),+ )+ })++ it('turns visitors away in an OIDC-only deployment', async () => {+ api.auth.oidcConfig.mockResolvedValue({+ enabled: true,+ provider_name: 'Keycloak',+ local_auth_enabled: false,+ })++ renderWithProviders(<RegisterPage />, { route: '/register' })++ await waitFor(() =>+ expect(navigate).toHaveBeenCalledWith('/login', { replace: true }),+ )+ })++ it('still renders the form when the oidc config call fails', async () => {+ api.auth.oidcConfig.mockRejectedValue(new Error('500'))++ await renderRegister()++ expect(+ screen.getByRole('button', { name: t('auth.register') }),+ ).toBeInTheDocument()+ expect(navigate).not.toHaveBeenCalledWith('/login', { replace: true })+ })++ it('defaults the currency to USD', async () => {+ await renderRegister()++ expect(screen.getByLabelText(t('auth.currency'))).toHaveTextContent('USD')+ })+})diff --git a/frontend/src/test/setup.ts b/frontend/src/test/setup.tsnew file mode 100644index 00000000..eb83b6be--- /dev/null+++ b/frontend/src/test/setup.ts@@ -0,0 +1,111 @@+/**+ * Global test setup: jest-dom matchers, DOM cleanup, and the browser APIs+ * jsdom does not implement.+ *+ * The polyfills below are not decoration. Radix primitives (dialog, select,+ * dropdown) and Recharts call into pointer capture, ResizeObserver and+ * scrollIntoView while rendering, and jsdom throws on all of them. Without+ * these, a component test fails on the environment rather than on the+ * component, which is the fastest way to make people stop writing tests.+ */+import '@testing-library/jest-dom/vitest'+import { cleanup } from '@testing-library/react'+import { afterEach, vi } from 'vitest'++// Testing Library only auto-cleans when vitest runs with `globals: true`, and+// this project imports `describe`/`it`/`expect` explicitly instead. Unmount by+// hand so one test's DOM never leaks into the next one's queries.+afterEach(() => {+ cleanup()+ localStorage.clear()+ sessionStorage.clear()+})++// next-themes reads this on mount. jsdom ships no implementation at all.+Object.defineProperty(window, 'matchMedia', {+ writable: true,+ value: (query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addListener: vi.fn(),+ removeListener: vi.fn(),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ dispatchEvent: vi.fn(),+ }),+})++class MockObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+ takeRecords() {+ return []+ }+}++// Recharts' ResponsiveContainer and several Radix primitives construct one of+// these on mount.+globalThis.ResizeObserver = MockObserver as unknown as typeof ResizeObserver+globalThis.IntersectionObserver =+ MockObserver as unknown as typeof IntersectionObserver++// Radix Select and DropdownMenu move focus with these three. jsdom implements+// none of them, and the omission surfaces as "target.hasPointerCapture is not+// a function" deep inside the primitive.+Element.prototype.hasPointerCapture = vi.fn(() => false)+Element.prototype.setPointerCapture = vi.fn()+Element.prototype.releasePointerCapture = vi.fn()+Element.prototype.scrollIntoView = vi.fn()++// jsdom parses CSS animations but never runs them, so Radix's exit animations+// would wait forever on a promise that never settles.+Element.prototype.getAnimations = vi.fn(() => [])++window.scrollTo = vi.fn()++// pdfjs-dist touches these at module scope, so importing the attachment+// viewer throws before any component renders. That import is transitive from+// the transactions, dashboard and account-detail pages, which would put three+// of the busiest screens out of reach of any test. The stubs only need to+// exist for the module to evaluate; nothing here renders a real PDF.+class MockDOMMatrix {+ a = 1+ b = 0+ c = 0+ d = 1+ e = 0+ f = 0+ multiply() {+ return this+ }+ translate() {+ return this+ }+ scale() {+ return this+ }+ inverse() {+ return this+ }+}++globalThis.DOMMatrix ??= MockDOMMatrix as unknown as typeof DOMMatrix+globalThis.Path2D ??= class {} as unknown as typeof Path2D+globalThis.ImageData ??= class {+ data = new Uint8ClampedArray()+ width = 0+ height = 0+} as unknown as typeof ImageData++// Recharts measures text through a canvas context. jsdom has no canvas backend+// and logs a noisy "not implemented" error for every chart that renders.+HTMLCanvasElement.prototype.getContext = vi.fn(+ () =>+ ({+ measureText: () => ({ width: 0 }),+ fillText: () => {},+ clearRect: () => {},+ }) as unknown as CanvasRenderingContext2D,+) as unknown as HTMLCanvasElement['getContext']diff --git a/frontend/src/test/utils.tsx b/frontend/src/test/utils.tsxnew file mode 100644index 00000000..053752ea--- /dev/null+++ b/frontend/src/test/utils.tsx@@ -0,0 +1,94 @@+/**+ * Shared render helper.+ *+ * Almost every component here reads from at least one of three providers:+ * TanStack Query, the router, and i18n. Wiring them per test file drifts, so+ * they live in one place and `renderWithProviders` is what tests call.+ *+ * i18n is the real instance with the real English bundle, not a stub that+ * echoes keys back. That is deliberate: a test asserting on "Save changes"+ * fails when someone deletes the key, which is exactly the regression the+ * locale files keep having.+ */+import type { ReactElement, ReactNode } from 'react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { I18nextProvider } from 'react-i18next'+import { MemoryRouter, Route, Routes } from 'react-router-dom'+import { render, type RenderOptions, type RenderResult } from '@testing-library/react'+import userEvent from '@testing-library/user-event'++import i18n from '@/lib/i18n'++/**+ * Retries and caching are useful in the app and only add flake in a test: a+ * failed query would be retried past the assertion, and a cached one would+ * leak into the next test. Both are off.+ */+export function createTestQueryClient(): QueryClient {+ return new QueryClient({+ defaultOptions: {+ queries: { retry: false, gcTime: 0, staleTime: 0 },+ mutations: { retry: false },+ },+ })+}++export interface ProviderOptions extends Omit<RenderOptions, 'wrapper'> {+ /** Initial URL for the memory router. */+ route?: string+ /**+ * Route pattern to mount the element under, for components that read params+ * with `useParams`. Pass `path="/accounts/:id"` with `route="/accounts/42"`.+ */+ path?: string+ queryClient?: QueryClient+}++export interface ProviderRenderResult extends RenderResult {+ queryClient: QueryClient+ /** Pre-bound user-event instance, so tests do not each call `setup()`. */+ user: ReturnType<typeof userEvent.setup>+}++export function renderWithProviders(+ ui: ReactElement,+ options: ProviderOptions = {},+): ProviderRenderResult {+ const {+ route = '/',+ path,+ queryClient = createTestQueryClient(),+ ...renderOptions+ } = options++ function Wrapper({ children }: { children: ReactNode }) {+ return (+ <I18nextProvider i18n={i18n}>+ <QueryClientProvider client={queryClient}>+ <MemoryRouter initialEntries={[route]}>+ {path ? (+ <Routes>+ <Route path={path} element={children} />+ </Routes>+ ) : (+ children+ )}+ </MemoryRouter>+ </QueryClientProvider>+ </I18nextProvider>+ )+ }++ return {+ ...render(ui, { wrapper: Wrapper, ...renderOptions }),+ queryClient,+ user: userEvent.setup(),+ }+}++/** Translate through the real bundle, so tests assert on the shipped copy. */+export function t(key: string, options?: Record<string, unknown>): string {+ return i18n.t(key, options) as string+}++export { i18n }diff --git a/frontend/tsconfig.app.json b/frontend/tsconfig.app.jsonindex eb3d9317..319e7c84 100644--- a/frontend/tsconfig.app.json+++ b/frontend/tsconfig.app.json@@ -29,5 +29,5 @@"noUncheckedSideEffectImports": true},"include": ["src"],- "exclude": ["**/*.test.ts", "**/*.test.tsx"]+ "exclude": ["**/*.test.ts", "**/*.test.tsx", "src/test/**"]}diff --git a/frontend/tsconfig.json b/frontend/tsconfig.jsonindex aa3c04f1..6ad1e228 100644--- a/frontend/tsconfig.json+++ b/frontend/tsconfig.json@@ -8,6 +8,7 @@"files": [],"references": [{ "path": "./tsconfig.app.json" },- { "path": "./tsconfig.node.json" }+ { "path": "./tsconfig.node.json" },+ { "path": "./tsconfig.test.json" }]}diff --git a/frontend/tsconfig.node.json b/frontend/tsconfig.node.jsonindex 8a94e959..7ad54d46 100644--- a/frontend/tsconfig.node.json+++ b/frontend/tsconfig.node.json@@ -22,5 +22,5 @@"noFallthroughCasesInSwitch": true,"noUncheckedSideEffectImports": true},- "include": ["vite.config.ts", "vitest.config.ts", "src/**/*.test.ts", "src/**/*.test.tsx"]+ "include": ["vite.config.ts", "vitest.config.ts"]}diff --git a/frontend/tsconfig.test.json b/frontend/tsconfig.test.jsonnew file mode 100644index 00000000..3126f00a--- /dev/null+++ b/frontend/tsconfig.test.json@@ -0,0 +1,38 @@+{+ /* Test files need the app's world, not the Node one: the DOM lib, JSX, the+ `@/` alias, and the jest-dom matchers that `src/test/setup.ts` registers.+ They used to be type-checked by tsconfig.node.json, which has none of+ those — workable while every test covered a pure function with relative+ imports, but not once they render components. */+ "compilerOptions": {+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.test.tsbuildinfo",+ "target": "ES2022",+ "useDefineForClassFields": true,+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "module": "ESNext",+ "types": ["vite/client", "node"],+ "skipLibCheck": true,++ /* Bundler mode */+ "moduleResolution": "bundler",+ "allowImportingTsExtensions": true,+ "verbatimModuleSyntax": true,+ "moduleDetection": "force",+ "noEmit": true,+ "jsx": "react-jsx",++ /* TS 7 removed baseUrl; paths resolve relative to this file. */+ "paths": {+ "@/*": ["./src/*"]+ },++ /* Linting */+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "erasableSyntaxOnly": true,+ "noFallthroughCasesInSwitch": true,+ "noUncheckedSideEffectImports": true+ },+ "include": ["src/**/*.test.ts", "src/**/*.test.tsx", "src/test/**/*"]+}diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.tsindex 5c37a94c..990e6f6e 100644--- a/frontend/vitest.config.ts+++ b/frontend/vitest.config.ts@@ -1,13 +1,29 @@import { defineConfig } from 'vitest/config'+import react from '@vitejs/plugin-react'import path from 'node:path'export default defineConfig({+ plugins: [react()],+ define: {+ // vite.config.ts injects this from the package version at build time.+ // Without it here, anything importing lib/build-info throws on import,+ // which takes the whole app shell down with it.+ __APP_VERSION__: JSON.stringify('0.0.0-test'),+ },resolve: {alias: {'@': path.resolve(import.meta.dirname, './src'),},},test: {- environment: 'node',+ // jsdom for everything, not only the component tests. The pure-function+ // suites under src/lib run fine in it and keeping one environment means a+ // new test file works wherever it is dropped, with no per-file docblock to+ // forget.+ environment: 'jsdom',+ setupFiles: ['./src/test/setup.ts'],+ // Vite serves the app's CSS through Tailwind; none of it affects what the+ // tests assert, so skip the transform and keep the suite fast.+ css: false,},})