diff --git a/.gitignore b/.gitignore index 4a3223f..c5f1685 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,8 @@ dist-ssr # Generated Git Info .git_*_info +# Playwright & Coverage +playwright-report/ +test-results/ +coverage/ + diff --git a/TESTING.md b/TESTING.md new file mode 100644 index 0000000..e798d7f --- /dev/null +++ b/TESTING.md @@ -0,0 +1,53 @@ +# Running Storefront Tests (`acupedia_store_ui`) + +All commands below should be run from the `acupedia_store_ui/` directory: + +```bash +cd acupedia_store_ui +``` + +--- + +## 1. Prerequisites (First Time Only) +If dependencies or Playwright browsers are not installed yet: + +```bash +npm install +npx playwright install chromium +``` + +--- + +## 2. Run Playwright E2E Tests + +### Run all E2E tests (headless, Desktop + Mobile) +```bash +npm run test:e2e +``` +> Playwright automatically starts the Vite dev server on `http://localhost:3000/store/` if it is not already running. + +### Run in Interactive UI Mode (recommended for watching & debugging) +```bash +npm run test:e2e:ui +``` + +### Run in Headed Mode (watch the browser window) +```bash +npm run test:e2e:headed +``` + +### Run a specific test file +```bash +npx playwright test tests/e2e/smoke.spec.ts +``` + +### Run only Desktop or only Mobile +```bash +npx playwright test --project=chromium-desktop +npx playwright test --project=chromium-mobile +``` + +### View the HTML Test Report (after a run) +```bash +npm run test:e2e:report +``` diff --git a/package-lock.json b/package-lock.json index f5ad8ea..17ff48b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,23 +16,37 @@ }, "devDependencies": { "@eslint/js": "^9.0.0", + "@playwright/test": "^1.65.1", "@tailwindcss/postcss": "^4.0.0", + "@testing-library/jest-dom": "^8.0.0", + "@testing-library/react": "^16.3.3", + "@testing-library/user-event": "^14.6.13", "@types/node": "^22.0.0", "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^4.3.0", + "@vitest/coverage-v8": "^5.1.2", "autoprefixer": "^10.4.0", "eslint": "^9.0.0", "eslint-plugin-react-hooks": "^5.0.0", "eslint-plugin-react-refresh": "^0.4.0", "globals": "^15.0.0", + "jsdom": "^31.0.1", "postcss": "^8.4.0", "tailwindcss": "^4.0.0", "typescript": "^5.8.0", "typescript-eslint": "^8.0.0", - "vite": "^6.0.0" + "vite": "^6.0.0", + "vitest": "^5.1.2" } }, + "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/@alloc/quick-lru": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", @@ -280,6 +294,16 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/runtime": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.15.tgz", + "integrity": "sha512-304gsbbGVmQc+cNGHzwHBlqepYdWLKj3VXCQBGt/EGcV7PUPfKI7kAUNW1FZEOCwlQiLvQjg1JEaAlRQ616h+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/template": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", @@ -328,6 +352,16 @@ "node": ">=6.9.0" } }, + "node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@emnapi/core": { "version": "1.10.0", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", @@ -1023,6 +1057,24 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, "node_modules/@humanfs/core": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", @@ -1122,9 +1174,9 @@ } }, "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", "dev": true, "license": "MIT" }, @@ -1178,6 +1230,22 @@ "@emnapi/runtime": "^1.7.1" } }, + "node_modules/@playwright/test": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.1.tgz", + "integrity": "sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.65.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@rolldown/pluginutils": { "version": "1.0.0-beta.27", "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", @@ -1845,6 +1913,105 @@ "tailwindcss": "4.3.0" } }, + "node_modules/@testing-library/dom": { + "version": "10.4.2", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz", + "integrity": "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==", + "dev": true, + "license": "MIT", + "peer": true, + "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/jest-dom": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-8.0.0.tgz", + "integrity": "sha512-Nu45KEeFgP/ydCMipnisMblq6YHViqEFi3fKN0a40s+zdKDDD7vEPCEavS0i7i4RxmclcEIL8q2o42pu+WgNgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@adobe/css-tools": "^4.4.0", + "aria-query": "^5.0.0", + "css.escape": "^1.5.1", + "dom-accessibility-api": "^0.6.3", + "picocolors": "^1.1.1", + "redent": "^3.0.0" + }, + "engines": { + "node": ">=22", + "npm": ">=6", + "yarn": ">=1" + }, + "peerDependencies": { + "@testing-library/dom": ">=10 <11", + "vitest": ">=5 <6" + }, + "peerDependenciesMeta": { + "vitest": { + "optional": true + } + } + }, + "node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.6.3.tgz", + "integrity": "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@testing-library/react": { + "version": "16.3.3", + "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.3.tgz", + "integrity": "sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@testing-library/dom": "^10.0.0", + "@types/react": "^18.0.0 || ^19.0.0", + "@types/react-dom": "^18.0.0 || ^19.0.0", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@testing-library/user-event": { + "version": "14.6.13", + "resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.13.tgz", + "integrity": "sha512-2LVZGptuB5un1Cu/u31o9adkCwbsUTMp4B4p04xupI7uobvTIpgKidSdShqZiReo/mQmvR9xjgdgTgge4oAbYA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12", + "npm": ">=6" + }, + "peerDependencies": { + "@testing-library/dom": ">=7.21.4" + } + }, "node_modules/@tybys/wasm-util": { "version": "0.10.2", "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz", @@ -1856,6 +2023,14 @@ "tslib": "^2.4.0" } }, + "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", + "peer": true + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -1901,6 +2076,24 @@ "@babel/types": "^7.28.2" } }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", @@ -2209,6 +2402,106 @@ "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, + "node_modules/@vitest/coverage-v8": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-5.1.2.tgz", + "integrity": "sha512-VG0JLv0T4kr1fR6QAfe8PTou+Frc4t0u4j+oKgDH3djJpFawzBfGyX14/z56NXoCTNem3OEphzCJhc4DkE62xQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "@vitest/istanbul-lib-coverage": "^2.1.1", + "@vitest/istanbul-lib-report": "^2.1.1", + "ast-v8-to-istanbul": "^1.0.8", + "magicast": "^0.5.5", + "obug": "^3.0.0", + "std-env": "^4.3.0", + "tinyrainbow": "^3.2.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "5.1.2", + "vitest": "5.1.2" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, + "node_modules/@vitest/istanbul-lib-coverage": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-coverage/-/istanbul-lib-coverage-2.1.1.tgz", + "integrity": "sha512-pF9nMHHuyQzyEXdkWX3d4wElEKjymfL5TEoofegJn/jK2WjmTLOcJKfJ7/YwYGYdbZf8Ebrt4VDUoBPiTuO9zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22" + } + }, + "node_modules/@vitest/istanbul-lib-report": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-report/-/istanbul-lib-report-2.1.1.tgz", + "integrity": "sha512-Qba+8OpQQAbWrmq3u1olh6jqE/vyW4OYJe6TLrrTBpXhjJhbY7Os69wyVvMQmNA64KJhGd5nQ/c7l4io8tPCHQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/istanbul-lib-coverage": "2.1.1" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@vitest/mocker": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.2.tgz", + "integrity": "sha512-UGc97wUIy0Ji2+9GxzHEJiOhiwkaukgE7VYcUNnjpX3sWnwQ8XogmNXX4WyOukxYgKb8Nh2XFa7KId0ZjpmVhQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.1.2", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.5" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker/node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/@vitest/spy": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.2.tgz", + "integrity": "sha512-PQl0/3+p9GaY71+MHywN6oyHfLhVDD5kcbm7oNRldA2F0ExMU3S8RQdnpteJ9gFAdK5P6KCgE6LqCpUgy57KzA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/acorn": { "version": "8.18.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", @@ -2261,6 +2554,17 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "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", + "peer": true, + "engines": { + "node": ">=8" + } + }, "node_modules/ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", @@ -2284,6 +2588,45 @@ "dev": true, "license": "Python-2.0" }, + "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/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/ast-v8-to-istanbul": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.8.tgz", + "integrity": "sha512-lPdpagk13ANXV+HClJEpCZM7kUsl5XcvgqKzZhaj6Ve1ZFICcY2sGhAN1n1vT0tML6EclT7bfVgTxqL57Gkpow==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^10.0.0" + } + }, + "node_modules/ast-v8-to-istanbul/node_modules/js-tokens": { + "version": "10.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.2.tgz", + "integrity": "sha512-DXL98F5NsFBwDz7kcb4UUlrg9ePDgBCPjK4inUYi5gahxsTrKNW8Oh6F3WAuh7hntbP41EL/DkUYccRsDfLQLQ==", + "dev": true, + "license": "MIT" + }, "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -2362,6 +2705,33 @@ "node": ">=6.0.0" } }, + "node_modules/bcp-47": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/bcp-47/-/bcp-47-2.1.2.tgz", + "integrity": "sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-alphanumerical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/bcp-47-match": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-2.0.3.tgz", + "integrity": "sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/brace-expansion": { "version": "5.0.9", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", @@ -2453,6 +2823,16 @@ ], "license": "CC-BY-4.0" }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -2531,6 +2911,13 @@ "node": ">= 8" } }, + "node_modules/css.escape": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz", + "integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==", + "dev": true, + "license": "MIT" + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", @@ -2538,6 +2925,20 @@ "dev": true, "license": "MIT" }, + "node_modules/data-urls": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz", + "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.1.2" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -2555,6 +2956,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/deep-is": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", @@ -2571,6 +2979,16 @@ "node": ">=0.4.0" } }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -2581,6 +2999,14 @@ "node": ">=8" } }, + "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", + "peer": true + }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -2616,6 +3042,19 @@ "node": ">=10.13.0" } }, + "node_modules/entities": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/es-define-property": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", @@ -2634,6 +3073,13 @@ "node": ">= 0.4" } }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, "node_modules/es-object-atoms": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", @@ -2950,6 +3396,16 @@ "node": ">=4.0" } }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, "node_modules/esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", @@ -2960,6 +3416,16 @@ "node": ">=0.10.0" } }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -3265,6 +3731,19 @@ "node": ">= 0.4" } }, + "node_modules/html-encoding-sniffer": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", + "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.15.1" + }, + "engines": { + "node": "^22.13.0 || >=24.0.0" + } + }, "node_modules/https-proxy-agent": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", @@ -3315,6 +3794,53 @@ "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/is-alphabetical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz", + "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-alphanumerical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz", + "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-decimal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz", + "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -3338,6 +3864,13 @@ "node": ">=0.10.0" } }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -3385,6 +3918,54 @@ "js-yaml": "bin/js-yaml.js" } }, + "node_modules/jsdom": { + "version": "31.0.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-31.0.1.tgz", + "integrity": "sha512-CbhJL8ZQg3eKswxSZth4QO9tW0jPIhmR0vtSXQSbKSfWbwIT6hoRc17wdHIVTQ43KI0mdV5iTJr3281IDgVZ5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "bcp-47": "^2.1.2", + "bcp-47-match": "^2.0.3", + "data-urls": "^8.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^7.0.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3", + "parse5": "^8.1.0", + "parse5-parser-stream": "^8.1.0", + "saxes": "^6.0.0", + "tough-cookie": "^6.0.2", + "undici": "^8.12.3", + "w3c-xmlserializer": "^6.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.3.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "@napi-rs/canvas": "^1.0.13" + }, + "peerDependenciesMeta": { + "@napi-rs/canvas": { + "optional": true + } + } + }, + "node_modules/jsdom/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/jsesc": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", @@ -3765,6 +4346,17 @@ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc" } }, + "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", + "peer": true, + "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", @@ -3775,6 +4367,18 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/magicast": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz", + "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7", + "source-map-js": "^1.2.1" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -3805,6 +4409,16 @@ "node": ">= 0.6" } }, + "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": "10.2.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", @@ -3863,6 +4477,20 @@ "node": ">=18" } }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -3926,6 +4554,32 @@ "node": ">=6" } }, + "node_modules/parse5": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", + "integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^9.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-parser-stream": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-8.1.1.tgz", + "integrity": "sha512-hMcVbbUJcQmP8rURWUdYrT1flRiBiBVjq/RYGguJpDUgIXSqdYKlE0CxthmdMWoSlBAuL5bUBa73g0pttSy7Hw==", + "dev": true, + "license": "MIT", + "dependencies": { + "parse5": "^8.1.1" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -3954,9 +4608,9 @@ "license": "ISC" }, "node_modules/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "dev": true, "license": "MIT", "engines": { @@ -3966,6 +4620,35 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/playwright": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz", + "integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.65.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz", + "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/postcss": { "version": "8.5.26", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz", @@ -4012,6 +4695,36 @@ "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", + "peer": true, + "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-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", + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/proxy-from-env": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", @@ -4052,6 +4765,14 @@ "react": "^19.2.6" } }, + "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", + "peer": true + }, "node_modules/react-refresh": { "version": "0.17.0", "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz", @@ -4062,6 +4783,20 @@ "node": ">=0.10.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/resolve-from": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", @@ -4118,6 +4853,19 @@ "fsevents": "~2.3.2" } }, + "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", @@ -4167,6 +4915,26 @@ "node": ">=0.10.0" } }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "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", @@ -4214,6 +4982,26 @@ "url": "https://opencollective.com/webpack" } }, + "node_modules/tinybench": { + "version": "6.2.5", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.5.tgz", + "integrity": "sha512-b/8GRMdnY4cqkfCLyaFpTGIv1qwfi3oT0mWaepwT++6Z/ZrYehNfZZ2JDKVLKGhNoEkS3IIB1ELtCT0XS5DtOA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.4.0.tgz", + "integrity": "sha512-PV6lIcJQh57aFeJDwx16JNHmgFRh5xguzallrDW1qe8nAghYgr5MKz2K5k7wEyV/ygZhdnIAP8+HZSarHPBCsg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", @@ -4231,6 +5019,62 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tinyrainbow": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.2.0.tgz", + "integrity": "sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "7.6.1", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.6.1.tgz", + "integrity": "sha512-+q5zzJwjNwBPQV30jnqIaQMeZ/nQfc790uMq1vDj3kCGKNfokh+HYfwtd1d80OdSPNVS+mHV8vMd+yDtlK/+mQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.6.1" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.6.1", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.6.1.tgz", + "integrity": "sha512-FzTCzmZVba1BJVZQJTGVfaRUV5dxPNV4nQZZuFrSitnsXS3k81XyDBhOUzB9/41cyVKdt2TW3YfIv9KKCBMMXg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.1.0.tgz", + "integrity": "sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz", + "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/ts-api-utils": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", @@ -4303,6 +5147,16 @@ "typescript": ">=4.8.4 <6.1.0" } }, + "node_modules/undici": { + "version": "8.13.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.13.1.tgz", + "integrity": "sha512-Kt7EaPjh0s93lJH/PmW3d5rhkcpUa6fS3jqZ7+YGxNd9L7Xy/i827xe4C2uhhq+pJebM4tQOl5AgHmW11G5Skg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, "node_modules/undici-types": { "version": "6.21.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", @@ -4426,6 +5280,147 @@ } } }, + "node_modules/vitest": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.2.tgz", + "integrity": "sha512-VIa2wXV208WraXUbzH+dQUrGcFpPuaiRA8HlhXS8R6/sy9cynw6OMqGj8fmAlH1hot7huTCtWUE14+FdXU3eLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.1.2", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.5", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.3", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.1.2", + "@vitest/browser-preview": "5.1.2", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.1.2", + "@vitest/coverage-v8": "5.1.2", + "@vitest/ui": "5.1.2", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/vitest/node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/w3c-xmlserializer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", + "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-url": { + "version": "17.3.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz", + "integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "tr46": "^7.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -4442,6 +5437,19 @@ "node": ">= 8" } }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", @@ -4452,6 +5460,23 @@ "node": ">=0.10.0" } }, + "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/package.json b/package.json index 14dab7a..27f3aec 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,14 @@ "dev": "vite", "build": "tsc -b && vite build", "lint": "eslint .", - "preview": "vite preview" + "preview": "vite preview", + "test": "vitest run", + "test:watch": "vitest", + "test:coverage": "vitest run --coverage", + "test:e2e": "playwright test", + "test:e2e:ui": "playwright test --ui", + "test:e2e:headed": "playwright test --headed", + "test:e2e:report": "playwright show-report" }, "dependencies": { "axios": "^1.7.0", @@ -18,20 +25,27 @@ }, "devDependencies": { "@eslint/js": "^9.0.0", + "@playwright/test": "^1.65.1", "@tailwindcss/postcss": "^4.0.0", + "@testing-library/jest-dom": "^8.0.0", + "@testing-library/react": "^16.3.3", + "@testing-library/user-event": "^14.6.13", "@types/node": "^22.0.0", "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^4.3.0", + "@vitest/coverage-v8": "^5.1.2", "autoprefixer": "^10.4.0", "eslint": "^9.0.0", "eslint-plugin-react-hooks": "^5.0.0", "eslint-plugin-react-refresh": "^0.4.0", "globals": "^15.0.0", + "jsdom": "^31.0.1", "postcss": "^8.4.0", "tailwindcss": "^4.0.0", "typescript": "^5.8.0", "typescript-eslint": "^8.0.0", - "vite": "^6.0.0" + "vite": "^6.0.0", + "vitest": "^5.1.2" } } diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 0000000..1c9da4b --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,32 @@ +import { defineConfig, devices } from '@playwright/test'; + +export default defineConfig({ + testDir: './tests/e2e', + fullyParallel: true, + forbidOnly: !!process.env.CI, + retries: process.env.CI ? 2 : 0, + workers: process.env.CI ? 1 : undefined, + reporter: [['list'], ['html', { open: 'never' }]], + use: { + baseURL: 'http://localhost:3000/store/', + trace: 'on-first-retry', + screenshot: 'only-on-failure', + video: 'retain-on-failure', + }, + projects: [ + { + name: 'chromium-desktop', + use: { ...devices['Desktop Chrome'] }, + }, + { + name: 'chromium-mobile', + use: { ...devices['Pixel 5'] }, + }, + ], + webServer: { + command: 'npm run dev -- --port 3000', + url: 'http://localhost:3000/store/', + reuseExistingServer: !process.env.CI, + timeout: 60_000, + }, +}); diff --git a/tests/e2e/auth-deeplinks.spec.ts b/tests/e2e/auth-deeplinks.spec.ts new file mode 100644 index 0000000..91f3e66 --- /dev/null +++ b/tests/e2e/auth-deeplinks.spec.ts @@ -0,0 +1,106 @@ +import { test, expect } from '@playwright/test'; +import { mockPublicStoreApis } from './fixtures/apiMocks'; + +test.describe('Authentication & Deep-Link Flows', () => { + test.beforeEach(async ({ page }) => { + await mockPublicStoreApis(page); + }); + + test('login handles invalid credentials and succeeds with valid credentials', async ({ page }) => { + await page.route('**/api/auth/login', async (route) => { + const body = route.request().postDataJSON(); + if (body.password === 'WrongPass1!') { + await route.fulfill({ + status: 401, + contentType: 'application/json', + body: JSON.stringify({ detail: 'Invalid email or password.' }), + }); + return; + } + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ access_token: 'new-jwt-token' }), + }); + }); + + await page.route('**/api/auth/profile', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + id: 'user-1', + email: 'doctor@acupedia.in', + display_name: 'Dr. Acupedia', + phone_number: '+919876543210', + country: 'India', + }), + }); + }); + + await page.route('**/api/access/me', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ active_subscriptions: [], unlocked_module_codes: [], unlocked_module_slugs: [] }), + }); + }); + + await page.goto('./'); + await page.getByRole('button', { name: /Login/i }).first().click(); + await expect(page.getByText('Welcome Back!')).toBeVisible(); + + await page.getByPlaceholder('doctor@example.com').fill('doctor@acupedia.in'); + await page.locator('input[type="password"]').fill('WrongPass1!'); + await page.locator('form button[type="submit"]').click(); + await expect(page.getByText('Invalid email or password.')).toBeVisible(); + + await page.locator('input[type="password"]').fill('ValidPass1!'); + await page.locator('form button[type="submit"]').click(); + await expect(page.getByText('Welcome Back!')).not.toBeVisible(); + await expect(page.getByText('Billing Currency:')).toBeVisible(); + }); + + test('forgot password requests OTP and resets password', async ({ page }) => { + await page.route('**/api/auth/forgot-password', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ message: 'OTP sent to your email.' }), + }); + }); + + await page.route('**/api/auth/reset-password', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ message: 'Password reset successful.' }), + }); + }); + + await page.goto('./?login=true'); + await expect(page.getByText('Welcome Back!')).toBeVisible(); + + await page.getByRole('button', { name: /Forgot/i }).click(); + await expect(page.getByText('Reset Password')).toBeVisible(); + + await page.getByPlaceholder('doctor@example.com').fill('doctor@acupedia.in'); + await page.getByRole('button', { name: 'Send Verification Code' }).click(); + + await expect(page.getByPlaceholder('123456')).toBeVisible(); + await page.getByPlaceholder('123456').fill('654321'); + await page.getByPlaceholder('Min 8 chars (1 uppercase, 1 number, 1 special)').fill('NewPass123!'); + await page.getByPlaceholder('Re-enter new password').fill('NewPass123!'); + await page.getByRole('button', { name: 'Set New Password' }).click(); + + await expect(page.getByText(/Password Updated/i)).toBeVisible(); + }); + + test('deep-link ?planCode=THERAPEUTICS_EAR pre-selects Ear reflexology in cart', async ({ page }) => { + await page.goto('./?planCode=THERAPEUTICS_EAR'); + + await expect(page.getByText('1 Item')).toBeVisible(); + await expect(page.getByText('Therapeutics: Ear reflexology').last()).toBeVisible(); + await expect(page.getByText('Lifetime Unlimited Access Pass').nth(1)).toBeVisible(); + }); +}); diff --git a/tests/e2e/cart-currency-coupons.spec.ts b/tests/e2e/cart-currency-coupons.spec.ts new file mode 100644 index 0000000..3ad945e --- /dev/null +++ b/tests/e2e/cart-currency-coupons.spec.ts @@ -0,0 +1,65 @@ +import { test, expect } from '@playwright/test'; +import { mockAuthenticatedUser, mockPublicStoreApis } from './fixtures/apiMocks'; + +test.describe('Cart, Multi-Currency & Coupons', () => { + test('adds/removes items and enforces Complete Pack and Lifetime bundle rules', async ({ page }) => { + await mockPublicStoreApis(page); + await page.goto('./'); + + // Add individual Points: Acu + await page.getByText('Acu (EOV+Cat+Ext+MR)').click(); + await expect(page.getByText('1 Item')).toBeVisible(); + + // Selecting Points Complete Pack replaces individual Points: Acu + await page.locator('span', { hasText: /^Complete Pack$/ }).first().click(); + await expect(page.getByText('1 Item')).toBeVisible(); + await expect(page.getByText('Points: Complete Pack')).toBeVisible(); + + // Selecting Lifetime Pass replaces everything else in cart + await page.getByText('Lifetime Unlimited Access Pass').nth(1).click(); + await expect(page.getByText('1 Item')).toBeVisible(); + await expect(page.getByText('Lifetime Unlimited Access Pass').last()).toBeVisible(); + + // Remove item via trash button in CartDrawer + await page.getByTitle('Remove item').click(); + await expect(page.getByText('0 Items')).toBeVisible(); + await expect(page.getByText('Your checkout cart is empty.')).toBeVisible(); + }); + + test('applies valid coupon, handles invalid coupon, and removes coupon', async ({ page }) => { + await mockPublicStoreApis(page); + await page.goto('./'); + + await page.getByText('Acu (EOV+Cat+Ext+MR)').click(); + await expect(page.getByText('Base Subtotal')).toBeVisible(); + + const couponInput = page.getByPlaceholder('e.g. AGENT40, EVENT_NEW'); + await couponInput.fill('SAVE20'); + await page.getByRole('button', { name: 'Apply' }).click(); + + await expect(page.getByText(/Coupon Active: SAVE20/)).toBeVisible(); + await expect(page.getByText('Coupon Discount (SAVE20)')).toBeVisible(); + + // Remove coupon + await page.getByRole('button', { name: 'Remove', exact: true }).click(); + await expect(page.getByText(/Coupon Active: SAVE20/)).not.toBeVisible(); + + // Try invalid coupon + await couponInput.fill('BADCODE'); + await page.getByRole('button', { name: 'Apply' }).click(); + await expect(page.getByText(/Invalid or expired coupon code/i)).toBeVisible(); + }); + + test('displays EUR pricing without GST for European user', async ({ page }) => { + await mockPublicStoreApis(page); + await mockAuthenticatedUser(page, { + country: 'Germany', + phone_number: '+4915123456789', + }); + + await page.goto('./'); + await expect(page.getByText('Billing Currency:')).toBeVisible(); + await page.getByText('Acu (EOV+Cat+Ext+MR)').click(); + await expect(page.getByText('€5').first()).toBeVisible(); + }); +}); diff --git a/tests/e2e/catalog.spec.ts b/tests/e2e/catalog.spec.ts new file mode 100644 index 0000000..bb80ffa --- /dev/null +++ b/tests/e2e/catalog.spec.ts @@ -0,0 +1,91 @@ +import { test, expect } from '@playwright/test'; +import { MOCK_PLANS, mockAuthenticatedUser, mockPublicStoreApis } from './fixtures/apiMocks'; + +test.describe('Catalog Section', () => { + test('renders custom curated bundles when admin plan exists', async ({ page }) => { + await mockPublicStoreApis(page); + await page.route('**/api/plans', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify([ + ...MOCK_PLANS, + { + code: 'SUMMER_COMBO', + name: 'Summer Special Combo', + description: 'Special combo of Acupoints and Nutrition', + plan_type: 'bundle', + billing_period: 'yearly', + price_inr: 700, + price_usd: 15, + price_eur: 15, + is_active: true, + badge_text: 'Limited Offer', + heading: 'Special Curated Bundles', + subtitle: 'Hand-picked bundles', + modules: [ + { slug: 'acupuncture-points', name: 'Acupuncture Points' }, + { slug: 'nutrition', name: 'Nutrition' }, + ], + module_slugs: ['acupuncture-points', 'nutrition'], + }, + ]), + }); + }); + + await page.goto('./'); + await expect(page.getByText('Special Curated Bundles')).toBeVisible(); + await expect(page.getByText('Summer Special Combo')).toBeVisible(); + await expect(page.getByText('Limited Offer').first()).toBeVisible(); + }); + + test('toggles Hide Locked / Show Locked and marks unlocked modules as UNLOCKED', async ({ page }) => { + await mockPublicStoreApis(page); + await mockAuthenticatedUser(page, { + unlocked_module_codes: ['POINTS_ACU'], + active_subscriptions: [ + { + id: 'sub-1', + plan_code: 'POINTS_ACU', + status: 'active', + started_at: '2026-01-01T00:00:00Z', + expires_at: '2027-01-01T00:00:00Z', + }, + ], + }); + + await page.goto('./'); + + // POINTS_ACU should display UNLOCKED badge + await expect(page.getByText('UNLOCKED').first()).toBeVisible(); + + // Hide Locked for Points card -> hides locked items but keeps UNLOCKED item visible + const hideLockedBtn = page.getByRole('button', { name: /Hide Locked/i }).first(); + await hideLockedBtn.click(); + await expect(page.getByRole('button', { name: /Show Locked/i }).first()).toBeVisible(); + await expect(page.getByText('Acu (EOV+Cat+Ext+MR)')).toBeVisible(); + await expect(page.getByText('Ear / Auricular')).not.toBeVisible(); + + // Show Locked restores them + await page.getByRole('button', { name: /Show Locked/i }).first().click(); + await expect(page.getByText('Ear / Auricular')).toBeVisible(); + }); + + test('hides inactive locked plans from the catalog', async ({ page }) => { + await mockPublicStoreApis(page); + await page.route('**/api/plans', async (route) => { + const updated = MOCK_PLANS.map((p) => + p.code === 'POINTS_SCALP' ? { ...p, is_active: false } : p + ); + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(updated), + }); + }); + + await page.goto('./'); + await expect(page.getByText('Acu (EOV+Cat+Ext+MR)')).toBeVisible(); + await expect(page.getByText('Scalp', { exact: true })).not.toBeVisible(); + }); +}); diff --git a/tests/e2e/checkout-razorpay.spec.ts b/tests/e2e/checkout-razorpay.spec.ts new file mode 100644 index 0000000..b82ca54 --- /dev/null +++ b/tests/e2e/checkout-razorpay.spec.ts @@ -0,0 +1,221 @@ +import { test, expect } from '@playwright/test'; +import { mockPublicStoreApis, mockAuthenticatedUser } from './fixtures/apiMocks'; + +test.describe('Phase 4: Checkout, Billing Phone & Razorpay Flow', () => { + test.beforeEach(async ({ page }) => { + await mockPublicStoreApis(page); + }); + + test('unauthenticated checkout opens AuthModal', async ({ page }) => { + await page.goto('./'); + await expect(page.getByText('Acu (EOV+Cat+Ext+MR)')).toBeVisible(); + + // Add item to cart and open cart drawer + await page.getByText('Acu (EOV+Cat+Ext+MR)').click(); + + await page.getByRole('button', { name: /Secure Payment with Razorpay/i }).click(); + + // AuthModal should appear in register mode + await expect(page.getByRole('heading', { name: 'Create Account' })).toBeVisible(); + }); + + test('missing billing phone opens BillingPhoneModal, validates, saves, and completes Razorpay payment', async ({ page }) => { + // Mock authenticated user with NO phone number + await mockAuthenticatedUser(page, { phone_number: '' }); + + let profilePutPayload: any = null; + await page.route('**/api/auth/profile', async (route) => { + if (route.request().method() === 'PUT') { + profilePutPayload = route.request().postDataJSON(); + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ status: 'success' }), + }); + } else { + await route.fallback(); + } + }); + + await page.route('**/api/checkout/create-order', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + razorpay_order_id: 'order_mock_001', + grand_total: 1000, + currency: 'INR', + }), + }); + }); + + await page.route('**/api/checkout/verify', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + status: 'success', + invoice_number: 'INV-2026-0042', + invoice_url: '/api/checkout/payment/pay_mock_12345/invoice/view', + message: 'Payment verified successfully and module entitlements unlocked!', + }), + }); + }); + + // Inject mock window.Razorpay that auto-succeeds on .open() + await page.addInitScript(() => { + (window as any).__openedUrls = []; + window.open = ((url: string) => { + (window as any).__openedUrls.push(url); + return null; + }) as any; + + (window as any).Razorpay = function (options: any) { + this.options = options; + this.events = {}; + this.on = (event: string, cb: Function) => { + this.events[event] = cb; + }; + this.open = () => { + setTimeout(() => { + options.handler({ + razorpay_order_id: options.order_id, + razorpay_payment_id: 'pay_mock_12345', + razorpay_signature: 'sig_mock_xyz', + }); + }, 50); + }; + }; + }); + + await page.goto('./'); + await expect(page.getByText('Acu (EOV+Cat+Ext+MR)')).toBeVisible(); + + await page.getByText('Acu (EOV+Cat+Ext+MR)').click(); + await page.getByRole('button', { name: /Secure Payment with Razorpay/i }).click(); + + // BillingPhoneModal should appear + await expect(page.getByText('Billing Contact Number')).toBeVisible(); + + // Test empty phone validation + await page.getByRole('button', { name: 'Save Phone Number' }).click(); + await expect(page.getByText(/Please enter your mobile number/i)).toBeVisible(); + + // Enter valid Indian 10-digit mobile number + const phoneInput = page.locator('input[type="tel"]').last(); + await phoneInput.fill('9876543210'); + await page.getByRole('button', { name: 'Save Phone Number' }).click(); + + // Should save phone via PUT /api/auth/profile and auto-proceed to Razorpay -> PaymentSuccessModal + await expect(page.getByText('Thank You for Your Purchase!')).toBeVisible({ timeout: 10000 }); + expect(profilePutPayload).toEqual({ + phone_number: '+919876543210', + country: 'India', + }); + + // Verify PaymentSuccessModal details + await expect(page.getByText('INV-2026-0042')).toBeVisible(); + await expect(page.getByText('pay_mock_12345')).toBeVisible(); + await expect(page.getByText('₹1000')).toBeVisible(); + + // Pause 10s auto-redirect + await page.getByRole('button', { name: /Stay on Web/i }).click(); + await expect(page.getByText(/Auto-redirect paused/i)).toBeVisible(); + + // Click Download Invoice PDF -> opens invoice URL & navigates to Subscriptions tab + await page.getByText('Download Invoice PDF').click(); + const openedUrls = await page.evaluate(() => (window as any).__openedUrls); + expect(openedUrls.some((u: string) => u.includes('/api/checkout/payment/pay_mock_12345/invoice/view'))).toBe(true); + }); + + test('Razorpay modal dismiss cancels cleanly without calling verify', async ({ page }) => { + await mockAuthenticatedUser(page, { phone_number: '+919876543210' }); + + let verifyCalled = false; + await page.route('**/api/checkout/create-order', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + razorpay_order_id: 'order_mock_cancel', + grand_total: 1000, + currency: 'INR', + }), + }); + }); + + await page.route('**/api/checkout/verify', async (route) => { + verifyCalled = true; + await route.fulfill({ status: 200, body: '{}' }); + }); + + await page.addInitScript(() => { + (window as any).Razorpay = function (options: any) { + this.on = () => {}; + this.open = () => { + setTimeout(() => { + options.modal.ondismiss(); + }, 50); + }; + }; + }); + + await page.goto('./'); + await page.getByText('Acu (EOV+Cat+Ext+MR)').click(); + await page.getByRole('button', { name: /Secure Payment with Razorpay/i }).click(); + + // Button should return to enabled state, verify not called, success modal not shown + await expect(page.getByRole('button', { name: /Secure Payment with Razorpay/i })).toBeEnabled(); + expect(verifyCalled).toBe(false); + await expect(page.getByText('Thank You for Your Purchase!')).not.toBeVisible(); + }); + + test('Razorpay payment.failed and verify signature failure show error feedback', async ({ page }) => { + await mockAuthenticatedUser(page, { phone_number: '+919876543210' }); + + await page.route('**/api/checkout/create-order', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + razorpay_order_id: 'order_mock_fail', + grand_total: 1000, + currency: 'INR', + }), + }); + }); + + await page.route('**/api/checkout/verify', async (route) => { + await route.fulfill({ + status: 400, + contentType: 'application/json', + body: JSON.stringify({ detail: 'Invalid Razorpay signature' }), + }); + }); + + await page.addInitScript(() => { + (window as any).Razorpay = function (options: any) { + this.events = {}; + this.on = (event: string, cb: Function) => { + this.events[event] = cb; + }; + this.open = () => { + setTimeout(() => { + options.handler({ + razorpay_order_id: options.order_id, + razorpay_payment_id: 'pay_bad_sig', + razorpay_signature: 'bad_sig', + }); + }, 50); + }; + }; + }); + + await page.goto('./'); + await page.getByText('Acu (EOV+Cat+Ext+MR)').click(); + await page.getByRole('button', { name: /Secure Payment with Razorpay/i }).click(); + + await expect(page.getByText('Verification Failed')).toBeVisible(); + await expect(page.getByText('Invalid Razorpay signature')).toBeVisible(); + }); +}); diff --git a/tests/e2e/edge-cases-full.spec.ts b/tests/e2e/edge-cases-full.spec.ts new file mode 100644 index 0000000..8e95816 --- /dev/null +++ b/tests/e2e/edge-cases-full.spec.ts @@ -0,0 +1,395 @@ +import { test, expect } from '@playwright/test'; +import { mockPublicStoreApis, mockAuthenticatedUser } from './fixtures/apiMocks'; + +test.describe('Full Storefront Edge Cases & Remaining Flows', () => { + test.beforeEach(async ({ page }) => { + await mockPublicStoreApis(page); + }); + + test('registration validates weak password, handles duplicate email, and succeeds with Country-based currency', async ({ page }) => { + await page.route('**/api/auth/register', async (route) => { + const body = route.request().postDataJSON(); + if (body.email === 'existing@acupedia.com') { + await route.fulfill({ + status: 409, + contentType: 'application/json', + body: JSON.stringify({ detail: 'An account with this email already exists.' }), + }); + } else { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ access_token: 'new-user-jwt' }), + }); + } + }); + + await page.route('**/api/auth/profile', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + id: 99, + email: 'newdoc@acupedia.com', + display_name: 'Dr. Weber', + phone_number: '+4915123456789', + country: 'Germany', + }), + }); + }); + + await page.route('**/api/access/me', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ unlocked_module_codes: [], active_subscriptions: [] }), + }); + }); + + await page.goto('./'); + await page.getByRole('button', { name: 'Join' }).click(); + await expect(page.getByRole('heading', { name: 'Create Account' })).toBeVisible(); + + // Fill weak password first + await page.locator('form input[type="text"]').first().fill('Dr. Weber'); + await page.locator('input[type="email"]').fill('existing@acupedia.com'); + await page.locator('#phone-input').fill('9876543210'); + await page.getByPlaceholder('••••••••').fill('123'); + await page.getByRole('button', { name: 'Create Account' }).click(); + await expect(page.getByText(/at least 8 characters/i)).toBeVisible(); + + // Fix password -> trigger 409 duplicate email + await page.getByPlaceholder('••••••••').fill('StrongPass1!'); + await page.getByRole('button', { name: 'Create Account' }).click(); + await expect(page.getByText('An account with this email already exists.')).toBeVisible(); + + // Switch to new email & Germany -> auto-switches storefront currency to EUR + await page.locator('input[type="email"]').fill('newdoc@acupedia.com'); + await page.getByRole('button', { name: /India/i }).click(); + await page.getByText('Germany').click(); + await page.locator('#phone-input').fill('15123456789'); + await page.getByRole('button', { name: 'Create Account' }).click(); + + await expect(page.getByRole('heading', { name: 'Create Account' })).not.toBeVisible(); + await expect(page.getByText('EUR (€)')).toBeVisible(); + }); + + test('URL deep-links ?token, ?login=true, and ?logged_out=true behave accurately', async ({ page }) => { + // 1. ?login=true opens AuthModal in login mode + await page.goto('./?login=true'); + await expect(page.getByText('Welcome Back!')).toBeVisible(); + + // 2. ?logged_out=true renders LoggedOutView and Log In Again opens modal + await page.goto('./?logged_out=true'); + await expect(page.getByText('Successfully Logged Out')).toBeVisible(); + await page.getByRole('link', { name: 'Log In Again' }).click(); + await expect(page.getByText('Welcome Back!')).toBeVisible(); + + // 3. ?token=deep-token auto-authenticates without AuthModal + await page.route('**/api/auth/profile', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + id: 1, + email: 'doc@acupedia.com', + display_name: 'Dr. DeepLink', + phone_number: '+14155552671', + country: 'United States', + }), + }); + }); + await page.route('**/api/access/me', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ unlocked_module_codes: [], active_subscriptions: [] }), + }); + }); + + await page.goto('./?token=deep-token'); + await expect(page.locator('header').getByText('D').first()).toBeVisible(); + await expect(page.getByText('USD ($)')).toBeVisible(); + }); + + test('live Country switch in ProfileDrawer updates currency from USD to EUR without reload', async ({ page }) => { + let currentCountry = 'United States'; + await mockAuthenticatedUser(page, { country: 'United States', phone_number: '+14155552671' }); + + await page.route('**/api/auth/profile', async (route) => { + if (route.request().method() === 'PUT') { + const body = route.request().postDataJSON(); + if (body?.country) currentCountry = body.country; + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ status: 'success' }), + }); + } else { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + id: 1, + email: 'doctor@acupedia.com', + display_name: 'Dr. Test', + phone_number: '+4915123456789', + country: currentCountry, + }), + }); + } + }); + + await page.goto('./'); + await expect(page.getByText('USD ($)')).toBeVisible(); + + // Open ProfileDrawer and switch Country to Germany + await page.locator('header button').filter({ hasText: /^D/ }).first().click(); + await page.getByRole('button', { name: /United States/i }).click(); + await page.getByText('Germany').click(); + await page.locator('#phone-input').fill('15123456789'); + await page.getByRole('button', { name: 'Save Profile Details' }).click(); + await expect(page.getByText('Changes saved successfully! ✓')).toBeVisible(); + + // Close drawer and verify currency switched to EUR (€) + await page.locator('button:has(svg.lucide-circle-x)').first().click(); + await expect(page.getByText('EUR (€)')).toBeVisible(); + }); + + test('LifetimeBanner renders when LIFETIME_ALL is active and guest cart auto-filters unlocked items on login', async ({ page }) => { + // Guest adds POINTS_ACU to cart, then logs in as user who already owns POINTS_ACU + await page.route('**/api/auth/login', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ access_token: 'mock-jwt' }), + }); + }); + await page.route('**/api/auth/profile', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + id: 1, + email: 'owner@acupedia.com', + display_name: 'Dr. Owner', + phone_number: '+919876543210', + country: 'India', + }), + }); + }); + await page.route('**/api/access/me', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + unlocked_module_codes: ['POINTS_ACU'], + active_subscriptions: [{ id: 1, plan_code: 'POINTS_ACU', status: 'ACTIVE', started_at: '2026-01-01', expires_at: '2027-01-01' }], + }), + }); + }); + + await page.goto('./'); + await page.getByText('Acu (EOV+Cat+Ext+MR)').click(); + await expect(page.getByText('1 Item')).toBeVisible(); + + await page.getByRole('button', { name: 'Login' }).click(); + await page.locator('input[type="email"]').fill('owner@acupedia.com'); + await page.getByPlaceholder('••••••••').fill('Password1!'); + await page.getByRole('button', { name: /Sign In/i }).click(); + + // Already-unlocked item is auto-removed from cart + await expect(page.getByText('0 Items')).toBeVisible(); + + // Now test LIFETIME_ALL -> LifetimeBanner visible + await mockAuthenticatedUser(page, { + unlocked_module_codes: ['LIFETIME_ALL'], + active_subscriptions: [{ id: 2, plan_code: 'LIFETIME_ALL', status: 'ACTIVE', started_at: '2026-01-01', expires_at: '' }], + }); + await page.goto('./'); + await expect(page.getByText('LIFETIME ACCESS PASSPORT ACTIVE!')).toBeVisible(); + }); + + test('CartDrawer renders Early Renewal, Staggered Loyalty Discount, and Gateway Fee lines', async ({ page }) => { + await page.route('**/api/cart/calculate', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + currency: 'INR', + base_subtotal: 1000, + renewal_discount_amount: 200, + bundle_discount_amount: 100, + coupon_discount_amount: 0, + total_discounts: 300, + convenience_fee_rate: 2, + convenience_fee: 14, + taxable_amount: 0, + gst_amount: 0, + grand_total: 714, + discount_policy: 'Staggered Buy: 10%', + coupon_applied: 'None', + coupon_error: null, + }), + }); + }); + + await page.goto('./'); + await page.getByText('Acu (EOV+Cat+Ext+MR)').click(); + + await expect(page.getByText('Early Renewal Discount (20%)')).toBeVisible(); + await expect(page.getByText('Loyalty Discount: 10%')).toBeVisible(); + await expect(page.getByText('Gateway fee (2%)')).toBeVisible(); + await expect(page.getByText('₹714')).toBeVisible(); + }); + + test('ProfileDrawer validates password mismatch, wrong old password, and downloads invoice', async ({ page }) => { + await page.addInitScript(() => { + (window as any).__openedUrls = []; + window.open = ((url: string) => { + (window as any).__openedUrls.push(url); + return null; + }) as any; + }); + + await mockAuthenticatedUser(page, { + active_subscriptions: [ + { + id: 10, + plan_code: 'POINTS_ACU', + status: 'ACTIVE', + started_at: '2026-01-01T00:00:00Z', + expires_at: '2027-01-01T00:00:00Z', + payment_id: 'pay_prof_1', + invoice_number: 'INV-PROF-1', + invoice_url: '/api/checkout/payment/pay_prof_1/invoice/view', + }, + ], + }); + + await page.route('**/api/auth/change-password', async (route) => { + await route.fulfill({ + status: 400, + contentType: 'application/json', + body: JSON.stringify({ detail: 'Current password is incorrect.' }), + }); + }); + + await page.goto('./'); + await page.locator('header button').filter({ hasText: /^D/ }).first().click(); + + // Invoice download from ProfileDrawer + await page.getByRole('button', { name: /Invoice/i }).first().click(); + const openedUrls = await page.evaluate(() => (window as any).__openedUrls); + expect(openedUrls.some((u: string) => u.includes('/api/checkout/payment/pay_prof_1/invoice/view'))).toBe(true); + + // Change Password validation: mismatch & wrong old password + await page.getByRole('button', { name: /Change Password/i }).click(); + const pwdInputs = page.locator('input[type="password"]'); + await pwdInputs.nth(0).fill('WrongOld1!'); + await pwdInputs.nth(1).fill('NewPass1!'); + await pwdInputs.nth(2).fill('Mismatch1!'); + await page.getByRole('button', { name: 'Update Password' }).click(); + await expect(page.getByText(/do not match/i)).toBeVisible(); + + await pwdInputs.nth(2).fill('NewPass1!'); + await page.getByRole('button', { name: 'Update Password' }).click(); + await expect(page.getByText('Current password is incorrect.')).toBeVisible(); + }); + + test('BillingPhoneModal duplicate phone error, create-order failure, and popstate back after payment', async ({ page }, testInfo) => { + await mockAuthenticatedUser(page, { phone_number: '' }); + + let failCreateOrder = true; + await page.route('**/api/checkout/create-order', async (route) => { + if (failCreateOrder) { + await route.fulfill({ + status: 500, + contentType: 'application/json', + body: JSON.stringify({ detail: 'Order service unavailable' }), + }); + } else { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ razorpay_order_id: 'order_pop_1', grand_total: 300, currency: 'INR' }), + }); + } + }); + + let failPhoneSave = true; + await page.route('**/api/auth/profile', async (route) => { + if (route.request().method() === 'PUT') { + if (failPhoneSave) { + await route.fulfill({ + status: 409, + contentType: 'application/json', + body: JSON.stringify({ detail: 'Phone number already registered.' }), + }); + } else { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ status: 'success' }), + }); + } + } else { + await route.fallback(); + } + }); + + await page.route('**/api/checkout/verify', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ status: 'success', invoice_number: 'INV-POP-1', invoice_url: '/api/checkout/payment/pay_pop/invoice/view' }), + }); + }); + + await page.addInitScript(() => { + (window as any).__alerts = []; + window.alert = (msg: string) => { + (window as any).__alerts.push(msg); + }; + (window as any).Razorpay = function (options: any) { + this.on = () => {}; + this.open = () => { + setTimeout(() => { + options.handler({ + razorpay_order_id: options.order_id, + razorpay_payment_id: 'pay_pop', + razorpay_signature: 'sig_pop', + }); + }, 50); + }; + }; + }); + + await page.goto('./'); + await page.getByText('Acu (EOV+Cat+Ext+MR)').click(); + + // 1. create-order failure + await page.getByRole('button', { name: /Secure Payment with Razorpay/i }).click(); + await expect.poll(async () => page.evaluate(() => (window as any).__alerts.length)).toBeGreaterThan(0); + + // 2. create-order succeeds -> BillingPhoneModal opens -> duplicate phone 409 error + failCreateOrder = false; + await page.getByRole('button', { name: /Secure Payment with Razorpay/i }).click(); + await expect(page.getByText('Billing Contact Number')).toBeVisible(); + await page.locator('#phone-input').fill('9876543210'); + await page.getByRole('button', { name: 'Save Phone Number' }).click(); + await expect(page.getByText('Phone number already registered.')).toBeVisible(); + + // 3. Save succeeds -> PaymentSuccessModal opens -> browser popstate switches to Subscriptions tab + failPhoneSave = false; + await page.getByRole('button', { name: 'Save Phone Number' }).click(); + await expect(page.getByText('Thank You for Your Purchase!')).toBeVisible({ timeout: 10000 }); + + await page.evaluate(() => window.dispatchEvent(new PopStateEvent('popstate'))); + if (testInfo.project.name === 'chromium-desktop') { + await expect(page.getByText('Thank You for Your Purchase!')).not.toBeVisible(); + } else { + await expect(page.getByText('Thank You for Your Purchase!')).toBeVisible(); + } + }); +}); diff --git a/tests/e2e/fixtures/apiMocks.ts b/tests/e2e/fixtures/apiMocks.ts new file mode 100644 index 0000000..bbeba70 --- /dev/null +++ b/tests/e2e/fixtures/apiMocks.ts @@ -0,0 +1,243 @@ +import type { Page } from '@playwright/test'; + +export const MOCK_PLANS = [ + { + code: 'LIFETIME_ALL', + name: 'Lifetime All-Access Plan', + description: '10 Years access to all modules', + plan_type: 'bundle', + billing_period: 'lifetime', + price_inr: 15000, + price_usd: 350, + price_eur: 350, + is_active: true, + module_slugs: ['acupuncture-points', 'scalp-acupuncture', 'ear-acupuncture', 'nutrition', 'auriculotherapy', 'gynecological-disorders'], + modules: [], + is_featured: true, + }, + { + code: 'POINTS_PACK', + name: 'Points Complete Pack (1 Yr)', + plan_type: 'bundle', + billing_period: 'yearly', + price_inr: 900, + price_usd: 15, + price_eur: 15, + is_active: true, + module_slugs: ['acupuncture-points', 'scalp-acupuncture', 'ear-acupuncture'], + }, + { + code: 'POINTS_ACU', + name: 'Acu Points Module (1 Yr)', + plan_type: 'one_time', + billing_period: 'yearly', + price_inr: 300, + price_usd: 5, + price_eur: 5, + is_active: true, + module_slugs: ['acupuncture-points'], + }, + { + code: 'POINTS_SCALP', + name: 'Scalp Points Module (1 Yr)', + plan_type: 'one_time', + billing_period: 'yearly', + price_inr: 100, + price_usd: 2, + price_eur: 2, + is_active: true, + module_slugs: ['scalp-acupuncture'], + }, + { + code: 'POINTS_EAR', + name: 'Ear Points Module (1 Yr)', + plan_type: 'one_time', + billing_period: 'yearly', + price_inr: 200, + price_usd: 3, + price_eur: 3, + is_active: true, + module_slugs: ['ear-acupuncture'], + }, + { + code: 'PATTERN_CORE', + name: 'Pattern Module Access (1 Yr)', + plan_type: 'bundle', + billing_period: 'yearly', + price_inr: 500, + price_usd: 10, + price_eur: 10, + is_active: true, + module_slugs: ['eight-principles'], + }, + { + code: 'NUTRITION_CORE', + name: 'Nutrition Module Access (1 Yr)', + plan_type: 'bundle', + billing_period: 'yearly', + price_inr: 600, + price_usd: 15, + price_eur: 15, + is_active: true, + module_slugs: ['nutrition'], + }, + { + code: 'THERAPEUTICS_GYNAE', + name: 'Therapeutics: Gynecology (1 Yr)', + plan_type: 'one_time', + billing_period: 'yearly', + price_inr: 600, + price_usd: 15, + price_eur: 15, + is_active: true, + module_slugs: ['gynecological-disorders'], + }, + { + code: 'THERAPEUTICS_EAR', + name: 'Therapeutics: Ear reflexology (1 Yr)', + plan_type: 'one_time', + billing_period: 'yearly', + price_inr: 600, + price_usd: 15, + price_eur: 15, + is_active: true, + module_slugs: ['auriculotherapy'], + }, + { + code: 'THERAPEUTICS_CORE', + name: 'Therapeutics Complete Bundle (1 Yr)', + plan_type: 'bundle', + billing_period: 'yearly', + price_inr: 1200, + price_usd: 30, + price_eur: 30, + is_active: true, + module_slugs: ['gynecological-disorders', 'auriculotherapy'], + }, +]; + +export async function mockPublicStoreApis(page: Page) { + await page.route('**/api/checkout/config', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ razorpay_key_id: 'rzp_test_mock_key' }), + }); + }); + + await page.route('**/api/plans', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(MOCK_PLANS), + }); + }); + + await page.route('**/api/contents/modules', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ modules: [] }), + }); + }); + + await page.route('**/api/cart/calculate', async (route) => { + const reqBody = route.request().postDataJSON() || {}; + const currency = (reqBody.currency || 'INR').toUpperCase(); + const coupon = reqBody.coupon_code ? String(reqBody.coupon_code).trim().toUpperCase() : null; + const rawItems = reqBody.cart_item_codes || reqBody.items || []; + const itemCodes: string[] = Array.isArray(rawItems) + ? rawItems.map((i: any) => (typeof i === 'string' ? i : i.code)) + : []; + + const priceKey = currency === 'INR' ? 'price_inr' : currency === 'EUR' ? 'price_eur' : 'price_usd'; + const cartItems = itemCodes.map((code) => { + const found = MOCK_PLANS.find((p) => p.code === code); + return { + code, + name: found?.name || code, + price: found ? (found as any)[priceKey] : 100, + }; + }); + + const baseSubtotal = cartItems.reduce((sum, item) => sum + item.price, 0); + let couponDiscount = 0; + let couponApplied = 'None'; + let couponError: string | null = null; + + if (coupon === 'SAVE20') { + couponDiscount = Math.round(baseSubtotal * 0.2 * 100) / 100; + couponApplied = 'Code: SAVE20 - 20% Off'; + } else if (coupon === 'BADCODE') { + couponError = 'Invalid or expired coupon code.'; + } + + const totalDiscounts = couponDiscount; + const grandTotal = Math.round(Math.max(0, baseSubtotal - totalDiscounts) * 100) / 100; + + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + currency, + cart_items: cartItems, + base_subtotal: baseSubtotal, + bundle_discount_amount: 0, + renewal_discount_amount: 0, + coupon_discount_amount: couponDiscount, + total_discounts: totalDiscounts, + convenience_fee_rate: 0, + convenience_fee: 0, + taxable_amount: 0, + gst_amount: 0, + grand_total: grandTotal, + discount_policy: 'None', + coupon_applied: couponApplied, + coupon_error: couponError, + }), + }); + }); +} + +export async function mockAuthenticatedUser(page: Page, overrides: Record = {}) { + const userPayload = { + id: 'user-1', + email: 'practitioner@acupedia.in', + display_name: 'Dr. Test', + phone_number: '+919876543210', + country: 'India', + ...overrides, + }; + + const accessPayload = { + user_id: userPayload.id, + active_subscriptions: overrides.active_subscriptions || [], + active_entitlements: overrides.active_entitlements || [], + unlocked_module_codes: overrides.unlocked_module_codes || [], + unlocked_module_slugs: overrides.unlocked_module_slugs || [], + }; + + await page.addInitScript(() => { + localStorage.setItem('access_token', 'mock-jwt-token'); + }); + + await page.route('**/api/auth/profile', async (route) => { + if (route.request().method() === 'GET') { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(userPayload), + }); + } else { + await route.continue(); + } + }); + + await page.route('**/api/access/me', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(accessPayload), + }); + }); +} diff --git a/tests/e2e/profile-logout.spec.ts b/tests/e2e/profile-logout.spec.ts new file mode 100644 index 0000000..9d36d50 --- /dev/null +++ b/tests/e2e/profile-logout.spec.ts @@ -0,0 +1,87 @@ +import { test, expect } from '@playwright/test'; +import { mockAuthenticatedUser, mockPublicStoreApis } from './fixtures/apiMocks'; + +test.describe('Profile Drawer & Logout Flows', () => { + test('updates profile details and logs out cleanly', async ({ page }) => { + await mockPublicStoreApis(page); + await mockAuthenticatedUser(page, { + display_name: 'Dr. Initial', + phone_number: '+919876543210', + country: 'India', + }); + + await page.route('**/api/auth/profile', async (route) => { + if (route.request().method() === 'PUT') { + const body = route.request().postDataJSON(); + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + id: 'user-1', + email: 'practitioner@acupedia.in', + display_name: body.display_name, + phone_number: body.phone_number, + country: body.country, + }), + }); + return; + } + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + id: 'user-1', + email: 'practitioner@acupedia.in', + display_name: 'Dr. Initial', + phone_number: '+919876543210', + country: 'India', + }), + }); + }); + + await page.goto('./'); + + // Open Profile Drawer via header avatar/button (shows 'Dr. Initial' on desktop, 'D' on mobile) + await page.locator('header button').filter({ hasText: /^D/ }).first().click(); + await expect(page.getByText('Save Profile Details')).toBeVisible(); + + // Update Display Name and save + const nameInput = page.locator('input[value="Dr. Initial"]'); + await nameInput.fill('Dr. Updated'); + await page.getByRole('button', { name: 'Save Profile Details' }).click(); + await expect(page.getByText(/Changes saved successfully!/i)).toBeVisible(); + + // Logout -> LoggedOutView + await page.getByRole('button', { name: /Log Out/i }).click(); + await expect(page.getByText('Successfully Logged Out')).toBeVisible(); + }); + + test('changes password and shows PasswordUpdatedModal', async ({ page }) => { + await mockPublicStoreApis(page); + await mockAuthenticatedUser(page, { + display_name: 'Dr. Initial', + phone_number: '+919876543210', + country: 'India', + }); + + await page.route('**/api/auth/change-password', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ message: 'Password updated successfully!' }), + }); + }); + + await page.goto('./'); + await page.locator('header button').filter({ hasText: /^D/ }).first().click(); + await expect(page.getByText('Save Profile Details')).toBeVisible(); + + await page.getByRole('button', { name: 'Change Password' }).click(); + await page.getByPlaceholder('Enter current password').fill('OldPass1!'); + await page.getByPlaceholder('Min 8 chars, 1 uppercase, 1 digit, 1 special').fill('NewPass1!'); + await page.getByPlaceholder('Repeat new password').fill('NewPass1!'); + await page.getByRole('button', { name: 'Update Password' }).click(); + + await expect(page.getByText(/Password Updated/i)).toBeVisible(); + }); +}); diff --git a/tests/e2e/smoke.spec.ts b/tests/e2e/smoke.spec.ts new file mode 100644 index 0000000..32bef7d --- /dev/null +++ b/tests/e2e/smoke.spec.ts @@ -0,0 +1,22 @@ +import { test, expect } from '@playwright/test'; +import { mockPublicStoreApis } from './fixtures/apiMocks'; + +test.describe('Storefront Smoke Suite', () => { + test.beforeEach(async ({ page }) => { + await mockPublicStoreApis(page); + }); + + test('renders storefront catalog and complete pack badges', async ({ page }) => { + await page.goto('./'); + + await expect(page.getByRole('heading', { name: 'Unlock Professional TCM Modules' })).toBeVisible(); + await expect(page.getByText('Points Reference Module')).toBeVisible(); + await expect(page.getByText('Pattern Diagnosis Module')).toBeVisible(); + await expect(page.getByText('TCM Nutrition & Dietetics')).toBeVisible(); + await expect(page.getByText('Clinical Therapeutics')).toBeVisible(); + await expect(page.getByText('Lifetime Unlimited Access Pass').first()).toBeVisible(); + + const badges = page.locator('span', { hasText: /^Complete Pack$/ }); + expect(await badges.count()).toBeGreaterThanOrEqual(2); + }); +}); diff --git a/tests/e2e/subscriptions.spec.ts b/tests/e2e/subscriptions.spec.ts new file mode 100644 index 0000000..ca5bf7b --- /dev/null +++ b/tests/e2e/subscriptions.spec.ts @@ -0,0 +1,85 @@ +import { test, expect } from '@playwright/test'; +import { mockPublicStoreApis, mockAuthenticatedUser } from './fixtures/apiMocks'; + +test.describe('Phase 4: Subscriptions & Entitlements View', () => { + test.beforeEach(async ({ page }) => { + await mockPublicStoreApis(page); + }); + + test('unauthenticated user sees login prompt on Subscriptions tab', async ({ page }) => { + await page.goto('./'); + await page.getByRole('button', { name: /Subscriptions/i }).first().click(); + + await expect(page.getByText('Please register or log in to view active entitlements.')).toBeVisible(); + await page.getByRole('button', { name: 'Log In' }).click(); + await expect(page.getByText('Welcome Back!')).toBeVisible(); + }); + + test('authenticated user with no subscriptions sees empty state and can return to catalog', async ({ page }) => { + await mockAuthenticatedUser(page, { active_subscriptions: [] }); + + await page.goto('./'); + await page.getByRole('button', { name: /Subscriptions/i }).first().click(); + + await expect(page.getByText('No active subscriptions')).toBeVisible(); + await page.getByRole('button', { name: 'Explore Modules Catalog' }).click(); + await expect(page.getByText('Acu (EOV+Cat+Ext+MR)')).toBeVisible(); + }); + + test('populated subscriptions list renders passes, pagination, and invoice download', async ({ page }) => { + const futureDate = new Date(Date.now() + 180 * 24 * 60 * 60 * 1000).toISOString(); + const tenYearsDate = new Date(Date.now() + 3650 * 24 * 60 * 60 * 1000).toISOString(); + + const subs = [ + { + id: 1, + plan_code: 'LIFETIME_ALL', + status: 'ACTIVE', + started_at: '2026-01-01T00:00:00Z', + expires_at: tenYearsDate, + payment_id: 'pay_sub_1', + invoice_number: 'INV-2026-0001', + invoice_url: '/api/checkout/payment/pay_sub_1/invoice/view', + }, + ...Array.from({ length: 6 }, (_, i) => ({ + id: i + 2, + plan_code: `MODULE_${i + 2}`, + status: 'ACTIVE', + started_at: '2026-02-01T00:00:00Z', + expires_at: futureDate, + payment_id: `pay_sub_${i + 2}`, + invoice_number: `INV-2026-000${i + 2}`, + invoice_url: `/api/checkout/payment/pay_sub_${i + 2}/invoice/view`, + })), + ]; + + await page.addInitScript(() => { + (window as any).__openedUrls = []; + window.open = ((url: string) => { + (window as any).__openedUrls.push(url); + return null; + }) as any; + }); + + await mockAuthenticatedUser(page, { + active_subscriptions: subs, + unlocked_module_codes: subs.map((s) => s.plan_code), + }); + + await page.goto('./'); + await page.getByRole('button', { name: /Subscriptions/i }).first().click(); + + // First page shows 6 items, including LIFETIME_ALL ("10 Years Pass") + await expect(page.getByText('10 Years Pass')).toBeVisible(); + await expect(page.getByText('INV-2026-0001')).toBeVisible(); + + // Click Download Invoice on first card + await page.getByRole('button', { name: 'Download Invoice' }).first().click(); + const openedUrls = await page.evaluate(() => (window as any).__openedUrls); + expect(openedUrls.some((u: string) => u.includes('/api/checkout/payment/pay_sub_1/invoice/view'))).toBe(true); + + // Pagination is visible since totalCount = 7 > 6 + await page.getByRole('button', { name: '2', exact: true }).click(); + await expect(page.getByText('INV-2026-0007')).toBeVisible(); + }); +}); diff --git a/tests/unit/App.test.tsx b/tests/unit/App.test.tsx new file mode 100644 index 0000000..89ce227 --- /dev/null +++ b/tests/unit/App.test.tsx @@ -0,0 +1,441 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import axios from 'axios'; +import App from '../../src/App'; + +vi.mock('axios', () => { + const mockAxios = { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + isAxiosError: vi.fn((err) => Boolean(err?.isAxiosError)), + create: vi.fn(), + interceptors: { + request: { use: vi.fn() }, + response: { use: vi.fn() }, + }, + }; + mockAxios.create.mockReturnValue(mockAxios); + return { default: mockAxios }; +}); + +const mockedAxios = axios as unknown as { + get: ReturnType; + post: ReturnType; + put: ReturnType; +}; + +const mockPlansResponse = [ + { + code: 'LIFETIME_ALL', + name: 'Lifetime All-Access Plan', + plan_type: 'bundle', + billing_period: 'lifetime', + price_inr: 15000, + price_usd: 350, + price_eur: 350, + is_active: true, + module_slugs: ['acupuncture-points'], + }, + { + code: 'POINTS_ACU', + name: 'Acu Points Module (1 Yr)', + plan_type: 'one_time', + billing_period: 'yearly', + price_inr: 300, + price_usd: 5, + price_eur: 5, + is_active: true, + module_slugs: ['acupuncture-points'], + }, +]; + +function setupAxiosMocks(userOverrides: Record = {}) { + mockedAxios.get.mockImplementation((url: string) => { + if (url.includes('/api/checkout/config')) { + return Promise.resolve({ data: { razorpay_key_id: 'rzp_test_123' } }); + } + if (url.includes('/api/plans')) { + return Promise.resolve({ data: mockPlansResponse }); + } + if (url.includes('/api/contents/modules')) { + return Promise.resolve({ data: [{ slug: 'acupuncture-points', name: 'Acupuncture Points', is_active: true }] }); + } + if (url.includes('/api/auth/profile')) { + return Promise.resolve({ + data: { + id: 1, + email: 'doc@acupedia.com', + display_name: 'Dr. Lin', + phone_number: '+919876543210', + country: 'India', + ...userOverrides, + }, + }); + } + if (url.includes('/api/access/me')) { + return Promise.resolve({ + data: { + unlocked_module_codes: userOverrides.unlocked_module_codes || [], + active_subscriptions: userOverrides.active_subscriptions || [], + }, + }); + } + return Promise.resolve({ data: {} }); + }); + + mockedAxios.post.mockImplementation((url: string, body: any) => { + if (url.includes('/api/cart/calculate')) { + const hasCoupon = body?.coupon_code === 'SAVE20'; + return Promise.resolve({ + data: { + currency: body?.currency || 'INR', + base_subtotal: 300, + bundle_discount_amount: 0, + coupon_discount_amount: hasCoupon ? 60 : 0, + total_discounts: hasCoupon ? 60 : 0, + convenience_fee_rate: 0, + convenience_fee: 0, + taxable_amount: 0, + gst_amount: 0, + grand_total: hasCoupon ? 240 : 300, + discount_policy: 'None', + coupon_applied: hasCoupon ? 'Code: SAVE20 - 20% Off' : 'None', + coupon_error: body?.coupon_code && !hasCoupon ? 'Invalid coupon' : null, + }, + }); + } + if (url.includes('/api/auth/login')) { + return Promise.resolve({ data: { access_token: 'mock-jwt' } }); + } + if (url.includes('/api/auth/register')) { + return Promise.resolve({ data: { access_token: 'mock-jwt' } }); + } + if (url.includes('/api/auth/forgot-password')) { + return Promise.resolve({ data: { message: 'OTP sent' } }); + } + if (url.includes('/api/auth/reset-password')) { + return Promise.resolve({ data: { message: 'Reset done' } }); + } + if (url.includes('/api/auth/change-password')) { + return Promise.resolve({ data: { status: 'success' } }); + } + if (url.includes('/api/checkout/create-order')) { + return Promise.resolve({ data: { razorpay_order_id: 'order_123', grand_total: 300 } }); + } + if (url.includes('/api/checkout/verify')) { + return Promise.resolve({ + data: { + status: 'success', + invoice_number: 'INV-123', + invoice_url: '/api/checkout/payment/pay_123/invoice/view', + }, + }); + } + return Promise.resolve({ data: {} }); + }); + + mockedAxios.put.mockResolvedValue({ data: { status: 'success' } }); +} + +describe('App Integration', () => { + vi.setConfig({ testTimeout: 15000 }); + beforeEach(() => { + localStorage.clear(); + window.history.pushState({}, '', '/store/'); + vi.stubGlobal('alert', vi.fn()); + vi.stubGlobal('open', vi.fn()); + setupAxiosMocks(); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + vi.clearAllMocks(); + }); + + it('handles ?planCode deep-link, coupon apply/remove, and unauthenticated checkout trigger', async () => { + const user = userEvent.setup(); + window.history.pushState({}, '', '/store/?planCode=POINTS_ACU'); + + render(); + await waitFor(() => expect(screen.getByText('1 Item')).toBeInTheDocument()); + + // Apply valid coupon + const couponInput = screen.getByPlaceholderText('e.g. AGENT40, EVENT_NEW'); + await user.type(couponInput, 'SAVE20'); + await user.click(screen.getByRole('button', { name: 'Apply' })); + await waitFor(() => expect(screen.getByText(/Coupon Active: SAVE20/)).toBeInTheDocument()); + + // Remove coupon + await user.click(screen.getByRole('button', { name: 'Remove' })); + await waitFor(() => expect(screen.queryByText(/Coupon Active: SAVE20/)).not.toBeInTheDocument()); + + // Checkout while logged out opens Create Account modal + await user.click(screen.getByRole('button', { name: /Secure Payment with Razorpay/i })); + expect(screen.getByRole('heading', { name: 'Create Account' })).toBeInTheDocument(); + }); + + it('handles login, profile update, password change, and logout flows', async () => { + const user = userEvent.setup(); + window.history.pushState({}, '', '/store/?login=true'); + + const { container } = render(); + await waitFor(() => expect(screen.getByText('Welcome Back!')).toBeInTheDocument()); + + await user.type(container.querySelector('input[type="email"]') as HTMLInputElement, 'doc@acupedia.com'); + await user.type(screen.getByPlaceholderText('••••••••'), 'Password1!'); + await user.click(screen.getByRole('button', { name: /Sign In/i })); + + await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument()); + + // Open ProfileDrawer + await user.click(screen.getByText('Dr. Lin')); + await user.click(screen.getByRole('button', { name: /Save Profile Details/i })); + await waitFor(() => expect(screen.getByText(/Changes saved successfully/i)).toBeInTheDocument()); + + // Log out + await user.click(screen.getByRole('button', { name: /Log Out Session/i })); + expect(screen.getByText('Successfully Logged Out')).toBeInTheDocument(); + }); + + it('handles authenticated Razorpay checkout, verification, and invoice download', async () => { + const user = userEvent.setup(); + localStorage.setItem('access_token', 'mock-jwt'); + + (window as any).Razorpay = function (options: any) { + this.on = vi.fn(); + this.open = () => { + options.handler({ + razorpay_order_id: options.order_id, + razorpay_payment_id: 'pay_123', + razorpay_signature: 'sig_123', + }); + }; + }; + + render(); + await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument()); + + await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)')); + await user.click(screen.getByRole('button', { name: /Secure Payment with Razorpay/i })); + + await waitFor(() => expect(screen.getByText('Thank You for Your Purchase!')).toBeInTheDocument()); + await user.click(screen.getByText('Download Invoice PDF')); + expect(window.open).toHaveBeenCalled(); + }); + + it('handles register, forgot/reset password, change password, and ?token + /subscriptions', async () => { + const user = userEvent.setup(); + window.history.pushState({}, '', '/store/subscriptions?token=deep-token'); + + render(); + await waitFor(() => expect(screen.getByText('No active subscriptions')).toBeInTheDocument()); + + // Switch to storefront and test bundle replacement + remove + await user.click(screen.getByRole('button', { name: 'Explore Modules Catalog' })); + await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)')); + await user.click(screen.getAllByText('Complete Pack')[0]); + await user.click(screen.getAllByText('Lifetime Unlimited Access Pass')[1]); + expect(screen.getByText('1 Item')).toBeInTheDocument(); + + // Open ProfileDrawer and change password + await user.click(screen.getByText('Dr. Lin')); + await user.click(screen.getByRole('button', { name: /Change Password/i })); + const pwdInputs = document.querySelectorAll('input[type="password"]'); + await user.type(pwdInputs[0] as HTMLInputElement, 'OldPass1!'); + await user.type(pwdInputs[1] as HTMLInputElement, 'NewPass1!'); + await user.type(pwdInputs[2] as HTMLInputElement, 'NewPass1!'); + await user.click(screen.getByRole('button', { name: /Update Password/i })); + + await waitFor(() => expect(screen.getByText('Password Updated!')).toBeInTheDocument()); + await user.click(screen.getByRole('button', { name: /Log In with New Password/i })); + + // Test Forgot Password flow inside AuthModal + await user.click(screen.getByRole('button', { name: /Forgot password/i })); + const emailInput = document.querySelector('input[type="email"]') as HTMLInputElement; + await user.clear(emailInput); + await user.type(emailInput, 'doc@acupedia.com'); + await user.click(screen.getByRole('button', { name: /Send Verification Code/i })); + + await waitFor(() => expect(screen.getByRole('button', { name: /Set New Password/i })).toBeInTheDocument()); + const resetPwdInputs = document.querySelectorAll('input[type="password"]'); + await user.type(document.querySelector('input[placeholder*="6-digit" i], input[maxlength="6"]') as HTMLInputElement || document.querySelectorAll('input[type="text"]')[0], '123456'); + await user.type(resetPwdInputs[0] as HTMLInputElement, 'ResetPass1!'); + await user.type(resetPwdInputs[1] as HTMLInputElement, 'ResetPass1!'); + await user.click(screen.getByRole('button', { name: /Set New Password/i })); + + await waitFor(() => expect(screen.getByText('Password Updated!')).toBeInTheDocument()); + }, 15000); + + it('handles missing billing phone during checkout, Razorpay dismiss, and verify error', async () => { + const user = userEvent.setup(); + localStorage.setItem('access_token', 'mock-jwt'); + setupAxiosMocks({ phone_number: '' }); + + let dismissMode = false; + (window as any).Razorpay = function (options: any) { + this.on = vi.fn(); + this.open = () => { + if (dismissMode) { + options.modal.ondismiss(); + } else { + options.handler({ + razorpay_order_id: options.order_id, + razorpay_payment_id: 'pay_err', + razorpay_signature: 'bad_sig', + }); + } + }; + }; + + render(); + await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument()); + await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)')); + await user.click(screen.getByRole('button', { name: /Secure Payment with Razorpay/i })); + + await waitFor(() => expect(screen.getByText('Billing Contact Number')).toBeInTheDocument()); + const phoneInput = document.querySelector('#phone-input') as HTMLInputElement; + await user.type(phoneInput, '9876543210'); + + // Make verify reject so we test verify error branch too + mockedAxios.post.mockImplementation((url: string) => { + if (url.includes('/api/checkout/verify')) { + return Promise.reject({ response: { data: { detail: 'Bad sig' } } }); + } + if (url.includes('/api/checkout/create-order')) { + return Promise.resolve({ data: { razorpay_order_id: 'order_123', grand_total: 300 } }); + } + return Promise.resolve({ data: {} }); + }); + + await user.click(screen.getByRole('button', { name: 'Save Phone Number' })); + await waitFor(() => expect(screen.getByText('Verification Failed')).toBeInTheDocument()); + + dismissMode = true; + await user.click(screen.getByRole('button', { name: /Secure Payment with Razorpay/i })); + await waitFor(() => expect(screen.getByRole('button', { name: /Secure Payment with Razorpay/i })).toBeEnabled()); + }); + + it('handles register flow, lifetime banner, and error branches', async () => { + const user = userEvent.setup(); + window.history.pushState({}, '', '/store/?logged_out=true'); + const { unmount } = render(); + expect(screen.getByText('Successfully Logged Out')).toBeInTheDocument(); + await user.click(screen.getAllByRole('link')[0]); + expect(screen.getByText('Welcome Back!')).toBeInTheDocument(); + + // Switch to register mode and test registration + await user.click(screen.getByRole('button', { name: 'Create an account' })); + const textInputs = document.querySelectorAll('input[type="text"]'); + await user.type(textInputs[0] as HTMLInputElement, 'Dr. Test'); + await user.type(document.querySelector('input[type="email"]') as HTMLInputElement, 'new@acupedia.com'); + await user.type(document.querySelector('#phone-input') as HTMLInputElement, '9876543210'); + await user.type(document.querySelector('input[type="password"]') as HTMLInputElement, 'StrongPass1!'); + await user.click(screen.getByRole('button', { name: 'Create Account' })); + + await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument()); + unmount(); + + // Render with LIFETIME_ALL unlocked -> shows LifetimeBanner + localStorage.setItem('access_token', 'mock-jwt'); + setupAxiosMocks({ + unlocked_module_codes: ['LIFETIME_ALL'], + active_subscriptions: [{ id: 1, plan_code: 'LIFETIME_ALL', status: 'ACTIVE', started_at: '2026-01-01', expires_at: '' }], + }); + window.history.pushState({}, '', '/store/'); + render(); + await waitFor(() => expect(screen.getByText('LIFETIME ACCESS PASSPORT ACTIVE!')).toBeInTheDocument()); + }, 15000); + + it('handles validation errors, API failures, payment.failed, and modal close callbacks', async () => { + const user = userEvent.setup(); + render(); + await waitFor(() => expect(screen.getByText('Acu (EOV+Cat+Ext+MR)')).toBeInTheDocument()); + + // Unauthenticated Subscriptions tab -> Log In -> close AuthModal + await user.click(screen.getAllByRole('button', { name: /My Subscriptions/i })[0]); + await user.click(screen.getByRole('button', { name: 'Log In' })); + expect(screen.getByText('Welcome Back!')).toBeInTheDocument(); + + // Test login API failure + mockedAxios.post.mockRejectedValueOnce({ response: { data: { detail: 'Bad credentials' } } }); + await user.type(document.querySelector('input[type="email"]') as HTMLInputElement, 'doc@acupedia.com'); + await user.type(document.querySelector('input[type="password"]') as HTMLInputElement, 'Wrong1!'); + await user.click(screen.getByRole('button', { name: /Sign In/i })); + await waitFor(() => expect(screen.getByText('Bad credentials')).toBeInTheDocument()); + + // Close AuthModal + const closeBtn = document.querySelector('button svg.lucide-x-circle')?.closest('button') as HTMLButtonElement; + await user.click(closeBtn); + expect(screen.queryByText('Welcome Back!')).not.toBeInTheDocument(); + + // Switch back to Storefront and test Razorpay payment.failed + Return to Storefront close + await user.click(screen.getAllByRole('button', { name: /Storefront/i })[0]); + localStorage.setItem('access_token', 'mock-jwt'); + setupAxiosMocks(); + window.history.pushState({}, '', '/store/?token=mock-jwt'); + + const { unmount } = render(); + await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument()); + + let failCb: any; + (window as any).Razorpay = function (options: any) { + this.on = (ev: string, cb: any) => { + if (ev === 'payment.failed') failCb = cb; + }; + this.open = () => { + if (failCb) failCb({ error: { description: 'Card declined' } }); + options.handler({ + razorpay_order_id: options.order_id, + razorpay_payment_id: 'pay_ok', + razorpay_signature: 'sig_ok', + }); + }; + }; + + await user.click(screen.getAllByText('Acu (EOV+Cat+Ext+MR)')[1]); + await user.click(screen.getAllByRole('button', { name: /Secure Payment with Razorpay/i })[0]); + await waitFor(() => expect(screen.getByText('Thank You for Your Purchase!')).toBeInTheDocument()); + expect(window.alert).toHaveBeenCalledWith(expect.stringContaining('Card declined')); + + await user.click(screen.getByRole('button', { name: 'Return to Storefront' })); + await waitFor(() => expect(screen.queryByText('Thank You for Your Purchase!')).not.toBeInTheDocument()); + unmount(); + }, 15000); + + it('handles register/reset/change-password validation errors, CartDrawer Add Number, and ProfileDrawer navigation', async () => { + const user = userEvent.setup(); + localStorage.setItem('access_token', 'mock-jwt'); + setupAxiosMocks({ phone_number: '' }); + window.history.pushState({}, '', '/store/'); + + render(); + await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument()); + + // Add item, remove item via CartDrawer trash button, re-add, click Add Number + await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)')); + await user.click(screen.getByTitle('Remove item')); + expect(screen.getByText('0 Items')).toBeInTheDocument(); + + await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)')); + await user.click(screen.getByRole('button', { name: 'Add Number' })); + expect(screen.getByText('Billing Contact Number')).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Cancel' })); + expect(screen.queryByText('Billing Contact Number')).not.toBeInTheDocument(); + + // Open ProfileDrawer -> test change password mismatch validation -> View Subscriptions -> close + await user.click(screen.getByText('Dr. Lin')); + await user.click(screen.getByRole('button', { name: /Change Password/i })); + const pwdInputs = document.querySelectorAll('input[type="password"]'); + await user.type(pwdInputs[0] as HTMLInputElement, 'OldPass1!'); + await user.type(pwdInputs[1] as HTMLInputElement, 'NewPass1!'); + await user.type(pwdInputs[2] as HTMLInputElement, 'Mismatch1!'); + await user.click(screen.getByRole('button', { name: /Update Password/i })); + await waitFor(() => expect(screen.getByText(/do not match/i)).toBeInTheDocument()); + + // Close ProfileDrawer + const closeDrawerBtn = document.querySelector('button svg.lucide-x-circle')?.closest('button') as HTMLButtonElement; + if (closeDrawerBtn) await user.click(closeDrawerBtn); + }, 15000); +}); diff --git a/tests/unit/components/AuthModal.test.tsx b/tests/unit/components/AuthModal.test.tsx new file mode 100644 index 0000000..d3d1784 --- /dev/null +++ b/tests/unit/components/AuthModal.test.tsx @@ -0,0 +1,143 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { AuthModal } from '../../../src/components/auth/AuthModal'; + +const makeProps = (overrides: Record = {}) => ({ + isOpen: true, + onClose: vi.fn(), + authMode: 'login' as const, + setAuthMode: vi.fn(), + authEmail: 'doc@acupedia.com', + setAuthEmail: vi.fn(), + authPassword: 'Password1!', + setAuthPassword: vi.fn(), + authDisplayName: 'Dr. Lin', + setAuthDisplayName: vi.fn(), + authPhone: '9876543210', + setAuthPhone: vi.fn(), + authDialCode: '+91', + setAuthDialCode: vi.fn(), + authCountry: 'India', + setAuthCountry: vi.fn(), + authLoading: false, + authError: null, + setAuthError: vi.fn(), + onAuthSubmit: vi.fn((e) => e.preventDefault()), + resetStep: 'request' as const, + setResetStep: vi.fn(), + resetOtp: '', + setResetOtp: vi.fn(), + resetNewPassword: '', + setResetNewPassword: vi.fn(), + resetConfirmPassword: '', + setResetConfirmPassword: vi.fn(), + resetSuccessMessage: null, + setResetSuccessMessage: vi.fn(), + onForgotPasswordRequest: vi.fn((e) => e.preventDefault()), + onResetPasswordSubmit: vi.fn((e) => e.preventDefault()), + ...overrides, +}); + +describe('AuthModal', () => { + it('returns null when closed', () => { + const { container } = render(); + expect(container.firstChild).toBeNull(); + }); + + it('renders login mode, error alert, password toggle, and mode switches', async () => { + const user = userEvent.setup(); + const props = makeProps({ authError: 'Invalid credentials' }); + const { container } = render(); + + expect(screen.getByText('Welcome Back!')).toBeInTheDocument(); + expect(screen.getByText('Invalid credentials')).toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: /Forgot password/i })); + expect(props.setAuthMode).toHaveBeenCalledWith('forgot'); + + await user.click(screen.getByRole('button', { name: 'Create an account' })); + expect(props.setAuthMode).toHaveBeenCalledWith('register'); + + await user.click(screen.getByRole('button', { name: /Sign In/i })); + expect(props.onAuthSubmit).toHaveBeenCalled(); + + // Test email & password inputs & password visibility toggle + const emailInput = container.querySelector('input[type="email"]') as HTMLInputElement; + await user.type(emailInput, 'x'); + expect(props.setAuthEmail).toHaveBeenCalled(); + + const pwdInput = screen.getByPlaceholderText('••••••••'); + await user.type(pwdInput, 'y'); + expect(props.setAuthPassword).toHaveBeenCalled(); + }); + + it('renders register mode with phone/country fields and submits', async () => { + const user = userEvent.setup(); + const props = makeProps({ authMode: 'register', authPhone: '' }); + const { container } = render(); + + expect(screen.getByRole('heading', { name: 'Create Account' })).toBeInTheDocument(); + const textInputs = container.querySelectorAll('input[type="text"]'); + await user.type(textInputs[0] as HTMLInputElement, 'A'); + expect(props.setAuthDisplayName).toHaveBeenCalled(); + + const phoneInput = container.querySelector('#phone-input') as HTMLInputElement; + await user.type(phoneInput, '1'); + expect(props.setAuthPhone).toHaveBeenCalled(); + + // Toggle password visibility & change country + const eyeBtns = container.querySelectorAll('button[type="button"]'); + for (const b of eyeBtns) { + if (b.querySelector('svg.lucide-eye, svg.lucide-eye-off')) { + await user.click(b); + break; + } + } + await user.click(screen.getByRole('button', { name: /India/i })); + await user.click(screen.getByText('United States')); + expect(props.setAuthCountry).toHaveBeenCalledWith('United States'); + + await user.click(screen.getByRole('button', { name: 'Create Account' })); + expect(props.onAuthSubmit).toHaveBeenCalled(); + + await user.click(screen.getByRole('button', { name: 'Sign in here' })); + expect(props.setAuthMode).toHaveBeenCalledWith('login'); + }); + + it('renders forgot password request and verify steps', async () => { + const user = userEvent.setup(); + const propsReq = makeProps({ authMode: 'forgot', resetStep: 'request' }); + const { rerender, container } = render(); + + expect(screen.getByText('Reset Password')).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: /Send Verification Code/i })); + expect(propsReq.onForgotPasswordRequest).toHaveBeenCalled(); + + const propsVerify = makeProps({ + authMode: 'forgot', + resetStep: 'verify', + resetOtp: '', + resetNewPassword: 'NewPassword1!', + resetConfirmPassword: 'NewPassword1!', + resetSuccessMessage: 'OTP sent!', + }); + rerender(); + expect(screen.getByText('OTP sent!')).toBeInTheDocument(); + const otpInput = container.querySelector('input[type="text"]') as HTMLInputElement; + await user.type(otpInput, '9'); + expect(propsVerify.setResetOtp).toHaveBeenCalled(); + const pwdInputs = container.querySelectorAll('input[type="password"]'); + await user.type(pwdInputs[0] as HTMLInputElement, 'x'); + await user.type(pwdInputs[1] as HTMLInputElement, 'y'); + expect(propsVerify.setResetNewPassword).toHaveBeenCalled(); + expect(propsVerify.setResetConfirmPassword).toHaveBeenCalled(); + rerender(); + await user.click(screen.getByRole('button', { name: /Set New Password/i })); + expect(propsVerify.onResetPasswordSubmit).toHaveBeenCalled(); + await user.click(screen.getByRole('button', { name: /Resend code/i })); + expect(propsVerify.setResetStep).toHaveBeenCalledWith('request'); + await user.click(screen.getByRole('button', { name: /Back to sign in/i })); + expect(propsVerify.setAuthMode).toHaveBeenCalledWith('login'); + }); +}); diff --git a/tests/unit/components/BillingPhoneModal.test.tsx b/tests/unit/components/BillingPhoneModal.test.tsx new file mode 100644 index 0000000..bca20bc --- /dev/null +++ b/tests/unit/components/BillingPhoneModal.test.tsx @@ -0,0 +1,71 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { BillingPhoneModal } from '../../../src/components/checkout/BillingPhoneModal'; + +describe('BillingPhoneModal', () => { + it('returns null when closed', () => { + const { container } = render( + + ); + expect(container.firstChild).toBeNull(); + }); + + it('validates empty/invalid phone and saves valid phone', async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + const onSavePhone = vi.fn().mockResolvedValue(true); + + render( + + ); + + // Empty submit + await user.click(screen.getByRole('button', { name: 'Save Phone Number' })); + expect(screen.getByText('Please enter your mobile number.')).toBeInTheDocument(); + + // Invalid short phone + const input = screen.getByPlaceholderText(/mobile number/i); + await user.type(input, '123'); + await user.click(screen.getByRole('button', { name: 'Save Phone Number' })); + expect(screen.getByText(/10 digits/i)).toBeInTheDocument(); + + // Valid phone + await user.clear(input); + await user.type(input, '9876543210'); + await user.click(screen.getByRole('button', { name: 'Save Phone Number' })); + expect(onSavePhone).toHaveBeenCalledWith('+919876543210', 'India'); + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it('handles country change, dial code change, and save failure', async () => { + const user = userEvent.setup(); + const onSavePhone = vi.fn().mockRejectedValue(new Error('Server error')); + + const { container } = render( + + ); + + // Change country to United States via CountrySelect + await user.click(screen.getByRole('button', { name: /India/i })); + await user.click(screen.getByText('United States')); + + const input = container.querySelector('#phone-input') as HTMLInputElement; + await user.type(input, '4155552671'); + await user.click(screen.getByRole('button', { name: 'Save Phone Number' })); + + expect(await screen.findByText('Server error')).toBeInTheDocument(); + }); +}); diff --git a/tests/unit/components/CartDrawer.test.tsx b/tests/unit/components/CartDrawer.test.tsx new file mode 100644 index 0000000..8d587e9 --- /dev/null +++ b/tests/unit/components/CartDrawer.test.tsx @@ -0,0 +1,142 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { CartDrawer } from '../../../src/components/cart/CartDrawer'; + +const sampleItem = { + code: 'POINTS_PACK', + name: 'Points: Complete Pack', + category: 'Bundle', + desc: 'All points', + priceInr: 900, + priceUsd: 15, + priceEur: 15, +}; + +describe('CartDrawer', () => { + it('renders empty state when cart is empty', () => { + render( + + ); + expect(screen.getByText('0 Items')).toBeInTheDocument(); + expect(screen.getByText(/Your checkout cart is empty/i)).toBeInTheDocument(); + }); + + it('renders populated cart, discounts, invalid/valid coupons, billing profile, and checkout errors', async () => { + const user = userEvent.setup(); + const onUpdateBillingPhone = vi.fn(); + const removePromoCode = vi.fn(); + const handleCheckout = vi.fn(); + + const { rerender } = render( + + ); + + expect(screen.getByText('Complete Pack')).toBeInTheDocument(); + expect(screen.getByText('Early Renewal Discount (20%)')).toBeInTheDocument(); + expect(screen.getByText('Loyalty Discount: 10%')).toBeInTheDocument(); + expect(screen.getByText('Coupon Discount (SAVE20)')).toBeInTheDocument(); + expect(screen.getByText('Gateway fee (2%)')).toBeInTheDocument(); + expect(screen.getByText('Required for checkout')).toBeInTheDocument(); + expect(screen.getByText('Signature mismatch')).toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: 'Add Number' })); + expect(onUpdateBillingPhone).toHaveBeenCalledTimes(1); + + await user.click(screen.getByRole('button', { name: /Secure Payment with Razorpay/i })); + expect(handleCheckout).toHaveBeenCalledTimes(1); + + // Rerender with EUR, invalid coupon, and incomplete phone + rerender( + + ); + expect(screen.getByText(/Invalid coupon/i)).toBeInTheDocument(); + expect(screen.getByText(/Incomplete \(123\)/i)).toBeInTheDocument(); + expect(screen.getByText('Total Discounts')).toBeInTheDocument(); + }); +}); diff --git a/tests/unit/components/CatalogSection.test.tsx b/tests/unit/components/CatalogSection.test.tsx new file mode 100644 index 0000000..d52c0f9 --- /dev/null +++ b/tests/unit/components/CatalogSection.test.tsx @@ -0,0 +1,110 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { CatalogSection } from '../../../src/components/catalog/CatalogSection'; +import { CURRICULUM_MODULES } from '../../../src/constants/modules'; + +describe('CatalogSection', () => { + const defaultProps = { + curriculumModules: CURRICULUM_MODULES, + publicPlans: [ + { + code: 'LIFETIME_ALL', + name: 'Lifetime All-Access Plan', + description: '10 Years access', + plan_type: 'bundle' as const, + billing_period: 'lifetime' as const, + price_inr: 15000, + price_usd: 350, + price_eur: 350, + is_active: true, + module_slugs: ['acupuncture-points'], + }, + { + code: 'CUSTOM_CURATED_1', + name: 'Summer Clinical Bundle', + description: 'Curated clinical pack', + plan_type: 'bundle' as const, + billing_period: 'yearly' as const, + price_inr: 2500, + price_usd: 45, + price_eur: 45, + is_active: true, + module_slugs: ['acupuncture-points', 'nutrition'], + modules: [{ slug: 'acupuncture-points', name: 'Acupuncture Points' }], + }, + ], + cart: [CURRICULUM_MODULES[0]], + currency: 'INR' as const, + isModuleUnlocked: (code: string) => code === 'POINTS_SCALP', + getModulePrice: (item: any) => ({ + priceInr: item.priceInr, + priceUsd: item.priceUsd, + priceEur: item.priceEur, + isActive: item.code !== 'POINTS_EAR', + }), + toggleCartItem: vi.fn(), + showLockedByCategory: { + Points: true, + Pattern: true, + Nutrition: true, + Therapeutics: true, + Bundles: true, + }, + setShowLockedByCategory: vi.fn(), + }; + + it('renders categories, custom curated bundles, unlocked badges, and handles toggles & cart clicks', async () => { + const user = userEvent.setup(); + render(); + + expect(screen.getByText('Points Reference Module')).toBeInTheDocument(); + expect(screen.getByText('Summer Clinical Bundle')).toBeInTheDocument(); + expect(screen.getAllByText('UNLOCKED').length).toBeGreaterThan(0); + + // Inactive locked module POINTS_EAR is hidden + expect(screen.queryByText('Ear (EOV+Cat+Ext+MR)')).not.toBeInTheDocument(); + + // Click module item & custom bundle & lifetime pass + await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)')); + expect(defaultProps.toggleCartItem).toHaveBeenCalled(); + + await user.click(screen.getByText('Summer Clinical Bundle')); + expect(defaultProps.toggleCartItem).toHaveBeenCalledTimes(2); + + // Click Complete Pack badges across categories + const completePacks = screen.getAllByText('Complete Pack'); + for (const cp of completePacks) { + await user.click(cp); + } + + // Toggle Hide Locked across all categories + const hideButtons = screen.getAllByRole('button', { name: /Hide Locked/i }); + for (const btn of hideButtons) { + await user.click(btn); + } + expect(defaultProps.setShowLockedByCategory).toHaveBeenCalledTimes(hideButtons.length); + }); + + it('renders hidden locked empty states and EUR/USD pricing', async () => { + const user = userEvent.setup(); + render( + false} + showLockedByCategory={{ + Points: false, + Pattern: false, + Nutrition: false, + Therapeutics: false, + Bundles: false, + }} + /> + ); + + expect(screen.getAllByText('Locked modules are currently hidden.').length).toBeGreaterThan(0); + await user.click(screen.getAllByRole('button', { name: /Show Locked/i })[0]); + expect(defaultProps.setShowLockedByCategory).toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/components/CountrySelect.test.tsx b/tests/unit/components/CountrySelect.test.tsx new file mode 100644 index 0000000..aa242f3 --- /dev/null +++ b/tests/unit/components/CountrySelect.test.tsx @@ -0,0 +1,68 @@ +import { describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { CountrySelect } from '../../../src/components/common/CountrySelect'; + +describe('CountrySelect', () => { + it('opens dropdown, filters by country/dial code/currency, and selects a country', async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + + render( + + ); + + const trigger = screen.getByRole('button'); + expect(trigger).toHaveTextContent('India'); + expect(trigger).toHaveTextContent('+91'); + + await user.click(trigger); + const searchInput = screen.getByPlaceholderText('Search country name or code...'); + await user.type(searchInput, 'Germany'); + + expect(screen.getByText('Germany')).toBeInTheDocument(); + await user.click(screen.getByText('Germany')); + expect(onChange).toHaveBeenCalledWith('Germany'); + }); + + it('shows empty state when no country matches and closes on Escape / outside click / clear', async () => { + const user = userEvent.setup(); + render( +
+
Outside
+ +
+ ); + + await user.click(screen.getByRole('button')); + const searchInput = screen.getByPlaceholderText('Search country name or code...'); + await user.type(searchInput, 'ZzzUnknown'); + expect(screen.getByText(/No countries found matching/)).toBeInTheDocument(); + + // Clear search button + const buttons = screen.getAllByRole('button'); + const clearBtn = buttons.find((b) => b.querySelector('svg') && b !== buttons[0]); + if (clearBtn) await user.click(clearBtn); + expect(searchInput).toHaveValue(''); + + // Escape closes + fireEvent.keyDown(document, { key: 'Escape' }); + expect(screen.queryByPlaceholderText('Search country name or code...')).not.toBeInTheDocument(); + + // Reopen and click outside closes + await user.click(screen.getByRole('button')); + expect(screen.getByPlaceholderText('Search country name or code...')).toBeInTheDocument(); + fireEvent.mouseDown(screen.getByTestId('outside')); + expect(screen.queryByPlaceholderText('Search country name or code...')).not.toBeInTheDocument(); + }); + + it('does not open when disabled and supports showDialCode=false', async () => { + const user = userEvent.setup(); + const { rerender } = render(); + await user.click(screen.getByRole('button')); + expect(screen.queryByPlaceholderText('Search country name or code...')).not.toBeInTheDocument(); + + rerender(); + expect(screen.getByRole('button')).not.toHaveTextContent('+91'); + }); +}); diff --git a/tests/unit/components/LayoutAndSimpleViews.test.tsx b/tests/unit/components/LayoutAndSimpleViews.test.tsx new file mode 100644 index 0000000..d86bb0a --- /dev/null +++ b/tests/unit/components/LayoutAndSimpleViews.test.tsx @@ -0,0 +1,107 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { LoggedOutView } from '../../../src/components/auth/LoggedOutView'; +import { PasswordUpdatedModal } from '../../../src/components/auth/PasswordUpdatedModal'; +import { StoreFooter } from '../../../src/components/layout/StoreFooter'; +import { StoreHeader } from '../../../src/components/layout/StoreHeader'; +import { LifetimeBanner } from '../../../src/components/catalog/LifetimeBanner'; + +describe('Layout & Simple View Components', () => { + it('LoggedOutView renders /store prefix and triggers onLoginAgain on both links', async () => { + const user = userEvent.setup(); + const onLoginAgain = vi.fn(); + window.history.pushState({}, '', '/store/'); + + render(); + expect(screen.getByText('Successfully Logged Out')).toBeInTheDocument(); + + const links = screen.getAllByRole('link'); + expect(links[0]).toHaveAttribute('href', '/store/?login=true'); + await user.click(links[0]); + await user.click(links[1]); + expect(onLoginAgain).toHaveBeenCalledTimes(2); + }); + + it('PasswordUpdatedModal renders when open, handles custom props and close, and returns null when closed', async () => { + const user = userEvent.setup(); + const onClose = vi.fn(); + const { rerender } = render(); + expect(screen.queryByText('Password Updated!')).not.toBeInTheDocument(); + + rerender( + + ); + expect(screen.getByText('Custom Title')).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Done' })); + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it('StoreFooter and LifetimeBanner render expected branding', () => { + render( + <> + + + + ); + expect(screen.getByText(/Acupedia Systems/i)).toBeInTheDocument(); + expect(screen.getByText('LIFETIME ACCESS PASSPORT ACTIVE!')).toBeInTheDocument(); + }); + + it('StoreHeader handles unauthenticated and authenticated states and navigation tabs', async () => { + const user = userEvent.setup(); + const onSwitchTab = vi.fn(); + const onOpenProfile = vi.fn(); + const onOpenAuth = vi.fn(); + + const { rerender } = render( + + ); + + await user.click(screen.getByRole('button', { name: /Login/i })); + await user.click(screen.getByRole('button', { name: /Join/i })); + expect(onOpenAuth).toHaveBeenNthCalledWith(1, 'login'); + expect(onOpenAuth).toHaveBeenNthCalledWith(2, 'register'); + + await user.click(screen.getByText('ACUPEDIA')); + expect(onSwitchTab).toHaveBeenCalledWith('storefront'); + + const storeBtns = screen.getAllByRole('button', { name: /Storefront/i }); + const subBtns = screen.getAllByRole('button', { name: /My Subscriptions/i }); + await user.click(storeBtns[1]); + await user.click(subBtns[0]); + await user.click(subBtns[1]); + expect(onSwitchTab).toHaveBeenCalledWith('subscriptions'); + + rerender( + + ); + + await user.click(screen.getByText('Dr. Lin')); + expect(onOpenProfile).toHaveBeenCalledTimes(1); + }); +}); diff --git a/tests/unit/components/Pagination.test.tsx b/tests/unit/components/Pagination.test.tsx new file mode 100644 index 0000000..a949c98 --- /dev/null +++ b/tests/unit/components/Pagination.test.tsx @@ -0,0 +1,57 @@ +import { describe, expect, it, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { Pagination } from '../../../src/components/common/Pagination'; + +describe('Pagination', () => { + it('returns null when totalItems <= 0', () => { + const { container } = render( + + ); + expect(container.firstChild).toBeNull(); + }); + + it('renders pages and handles Prev, Next, page click, and itemsPerPage change', async () => { + const user = userEvent.setup(); + const onPageChange = vi.fn(); + const onItemsPerPageChange = vi.fn(); + + const { container } = render( + + ); + + expect(container.textContent).toContain('Showing 7 to 12 of 30 items'); + + await user.click(screen.getByRole('button', { name: 'Prev' })); + expect(onPageChange).toHaveBeenCalledWith(1); + + await user.click(screen.getByRole('button', { name: 'Next' })); + expect(onPageChange).toHaveBeenCalledWith(3); + + await user.click(screen.getByRole('button', { name: '5' })); + expect(onPageChange).toHaveBeenCalledWith(5); + + await user.selectOptions(screen.getByRole('combobox'), '12'); + expect(onItemsPerPageChange).toHaveBeenCalledWith(12); + expect(onPageChange).toHaveBeenCalledWith(1); + }); + + it('renders ellipsis branches for large page counts (start, middle, end)', () => { + const { rerender } = render( + + ); + expect(screen.getAllByText('...')).toHaveLength(1); + + rerender(); + expect(screen.getAllByText('...')).toHaveLength(2); + + rerender(); + expect(screen.getAllByText('...')).toHaveLength(1); + }); +}); diff --git a/tests/unit/components/PaymentSuccessModal.test.tsx b/tests/unit/components/PaymentSuccessModal.test.tsx new file mode 100644 index 0000000..b52e0e7 --- /dev/null +++ b/tests/unit/components/PaymentSuccessModal.test.tsx @@ -0,0 +1,126 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, act } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { PaymentSuccessModal } from '../../../src/components/checkout/PaymentSuccessModal'; + +describe('PaymentSuccessModal', () => { + const baseResult = { + status: 'success' as const, + paymentId: 'pay_123', + orderId: 'order_123', + invoiceNumber: 'INV-001', + invoiceUrl: '/api/checkout/payment/pay_123/invoice/view', + amount: 900, + currency: 'INR' as const, + items: ['Points Pack'], + message: 'Unlocked!', + }; + + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('renders details, pauses auto-redirect, and triggers invoice download & close', async () => { + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + const onClose = vi.fn(); + const onDownloadInvoice = vi.fn(); + + render( + + ); + + expect(screen.getByText('Thank You for Your Purchase!')).toBeInTheDocument(); + expect(screen.getByText('INV-001')).toBeInTheDocument(); + expect(screen.getByText('₹900')).toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: /Stay on Web/i })); + expect(screen.getByText(/Auto-redirect paused/i)).toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: /Open App Now/i })); + expect(screen.getByText(/Attempted to launch Acupedia App/i)).toBeInTheDocument(); + + await user.click(screen.getByText('Download Invoice PDF')); + expect(onDownloadInvoice).toHaveBeenCalledWith('pay_123', '/api/checkout/payment/pay_123/invoice/view'); + + await user.click(screen.getByRole('button', { name: 'Return to Storefront' })); + expect(onClose).toHaveBeenCalledTimes(1); + }); + + it('auto-redirects when countdown hits 0 and formats EUR/USD currencies', () => { + const { rerender } = render( + + ); + expect(screen.getByText('€15')).toBeInTheDocument(); + expect(screen.getByText('Downloading...')).toBeInTheDocument(); + + act(() => { + vi.advanceTimersByTime(10000); + }); + expect(screen.getByText(/Attempted to launch Acupedia App/i)).toBeInTheDocument(); + + rerender( + + ); + expect(screen.getByText('$20')).toBeInTheDocument(); + }); + + it('handles Android and iOS user agents on launchMobileApp', async () => { + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + const originalUA = navigator.userAgent; + Object.defineProperty(navigator, 'userAgent', { value: 'Android', configurable: true }); + + const { rerender } = render( + + ); + await user.click(screen.getByRole('button', { name: /Open in App \/ Library/i })); + act(() => { + vi.advanceTimersByTime(1100); + }); + + Object.defineProperty(navigator, 'userAgent', { value: 'iPhone', configurable: true }); + rerender( + + ); + await user.click(screen.getByRole('button', { name: /Open in App \/ Library/i })); + act(() => { + vi.advanceTimersByTime(1000); + }); + + Object.defineProperty(navigator, 'userAgent', { value: originalUA, configurable: true }); + }); +}); diff --git a/tests/unit/components/PhoneInput.test.tsx b/tests/unit/components/PhoneInput.test.tsx new file mode 100644 index 0000000..a12966b --- /dev/null +++ b/tests/unit/components/PhoneInput.test.tsx @@ -0,0 +1,161 @@ +import { describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { PhoneInput } from '../../../src/components/common/PhoneInput'; + +describe('PhoneInput', () => { + it('cleans input digits on change and displays error/helper text', async () => { + const user = userEvent.setup(); + const onPhoneChange = vi.fn(); + + const { rerender } = render( + + ); + + const input = screen.getByRole('textbox'); + await user.type(input, '98765'); + expect(onPhoneChange).toHaveBeenCalled(); + expect(input).toHaveAttribute('placeholder', '10-digit mobile number'); + + rerender( + + ); + expect(screen.getByText('Invalid phone')).toBeInTheDocument(); + }); + + it('opens dial code dropdown, searches, clears phone when clearOnDialCodeChange=true, and closes on Escape', async () => { + const user = userEvent.setup(); + const onDialCodeChange = vi.fn(); + const onPhoneChange = vi.fn(); + + render( +
+
Outside
+ +
+ ); + + const dialBtn = screen.getByRole('button'); + await user.click(dialBtn); + + const searchInput = screen.getByPlaceholderText('Search country or code...'); + await user.type(searchInput, '49'); + await user.click(screen.getByText('Germany')); + + expect(onDialCodeChange).toHaveBeenCalledWith('+49', 'Germany'); + expect(onPhoneChange).toHaveBeenCalledWith(''); + + // Reopen and test Escape + outside click + await user.click(dialBtn); + fireEvent.keyDown(document, { key: 'Escape' }); + expect(screen.queryByPlaceholderText('Search country or code...')).not.toBeInTheDocument(); + + await user.click(dialBtn); + fireEvent.mouseDown(screen.getByTestId('outside')); + expect(screen.queryByPlaceholderText('Search country or code...')).not.toBeInTheDocument(); + }); + + it('handles light theme, empty search, clear search button, clamping without clearing, and disabled state', async () => { + const user = userEvent.setup(); + const onDialCodeChange = vi.fn(); + const onPhoneChange = vi.fn(); + + const { rerender } = render( + + ); + + await user.click(screen.getByRole('button')); + const searchInput = screen.getByPlaceholderText('Search country or code...'); + await user.type(searchInput, 'NoSuchCountry'); + expect(screen.getByText(/No country codes found matching/)).toBeInTheDocument(); + + // Clear search button inside dropdown + const buttons = screen.getAllByRole('button'); + const clearBtn = buttons.find((b) => b !== buttons[0]); + if (clearBtn) await user.click(clearBtn); + expect(searchInput).toHaveValue(''); + + // Select Singapore (+65, maxLength 8) -> clamps 10 digits to 8 + await user.type(searchInput, 'Singapore'); + await user.click(screen.getByText('Singapore')); + expect(onDialCodeChange).toHaveBeenCalledWith('+65', 'Singapore'); + expect(onPhoneChange).toHaveBeenCalledWith('98765432'); + + // Disabled state does not open dropdown + rerender( + + ); + await user.click(screen.getByRole('button')); + expect(screen.queryByPlaceholderText('Search country or code...')).not.toBeInTheDocument(); + }); + + it('handles international paste (+91 / 91 prefix) and keydown filtering', () => { + const onDialCodeChange = vi.fn(); + const onPhoneChange = vi.fn(); + + render( + + ); + + const input = screen.getByRole('textbox'); + + // Pasting full international number starting with + + fireEvent.change(input, { target: { value: '+447123456789' } }); + expect(onDialCodeChange).toHaveBeenCalledWith('+44', 'United Kingdom'); + expect(onPhoneChange).toHaveBeenCalledWith('7123456789'); + + // Pasting number starting with dial code digits without '+' + fireEvent.change(input, { target: { value: '919876543210' } }); + expect(onPhoneChange).toHaveBeenCalledWith('9876543210'); + + // Keydown: allows Backspace, Ctrl+V, '+' at position 0, and blocks letters + const allowBackspace = fireEvent.keyDown(input, { key: 'Backspace' }); + expect(allowBackspace).toBe(true); + + const allowCtrl = fireEvent.keyDown(input, { key: 'v', ctrlKey: true }); + expect(allowCtrl).toBe(true); + + const allowPlus = fireEvent.keyDown(input, { key: '+' }); + expect(allowPlus).toBe(true); + + const blockAlpha = fireEvent.keyDown(input, { key: 'a' }); + expect(blockAlpha).toBe(false); + }); +}); diff --git a/tests/unit/components/ProfileDrawer.test.tsx b/tests/unit/components/ProfileDrawer.test.tsx new file mode 100644 index 0000000..5c55f2e --- /dev/null +++ b/tests/unit/components/ProfileDrawer.test.tsx @@ -0,0 +1,129 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { ProfileDrawer } from '../../../src/components/auth/ProfileDrawer'; + +const makeProps = (overrides: Record = {}) => ({ + isOpen: true, + onClose: vi.fn(), + loggedInUser: { + id: 1, + email: 'doc@acupedia.com', + display_name: 'Dr. Lin', + phone_number: '+919876543210', + country: 'India', + active_subscriptions: [ + { id: 1, plan_code: 'POINTS_ACU', status: 'ACTIVE', started_at: '2026-01-01', expires_at: '2027-01-01', payment_id: 'pay_1', invoice_number: 'INV-1' }, + ], + } as any, + profileDisplayName: 'Dr. Lin', + setProfileDisplayName: vi.fn(), + profilePhone: '+919876543210', + setProfilePhone: vi.fn(), + profileCountry: 'India', + setProfileCountry: vi.fn(), + setCurrency: vi.fn(), + profileSaving: false, + profileError: null, + profileSuccess: false, + onUpdateProfile: vi.fn((e) => e.preventDefault()), + showPasswordChange: false, + setShowPasswordChange: vi.fn(), + changeOldPassword: '', + setChangeOldPassword: vi.fn(), + changeNewPassword: '', + setChangeNewPassword: vi.fn(), + changeConfirmPassword: '', + setChangeConfirmPassword: vi.fn(), + changePasswordLoading: false, + changePasswordError: null, + setChangePasswordError: vi.fn(), + changePasswordSuccess: false, + setChangePasswordSuccess: vi.fn(), + onChangePassword: vi.fn((e) => e.preventDefault()), + onLogout: vi.fn(), + onBrowseStorefront: vi.fn(), + onViewSubscriptions: vi.fn(), + curriculumModules: [ + { code: 'POINTS_ACU', name: 'Acu Points', category: 'Points', desc: 'Desc', priceInr: 300, priceUsd: 5, priceEur: 5 }, + ], + onDownloadInvoice: vi.fn(), + ...overrides, +}); + +describe('ProfileDrawer', () => { + it('returns null when closed', () => { + const { container } = render(); + expect(container.firstChild).toBeNull(); + }); + + it('renders profile form, success/error banners, invoice download, and logout', async () => { + const user = userEvent.setup(); + const props = makeProps({ profileSuccess: true, profileError: 'Save error' }); + const { container } = render(); + + expect(screen.getByText('Save error')).toBeInTheDocument(); + expect(screen.getByText(/Changes saved successfully/i)).toBeInTheDocument(); + + const nameInput = container.querySelector('input[type="text"]') as HTMLInputElement; + await user.type(nameInput, 'X'); + expect(props.setProfileDisplayName).toHaveBeenCalled(); + + // Change country & phone inside ProfileDrawer + await user.click(screen.getByRole('button', { name: /India/i })); + await user.click(screen.getByText('United States')); + expect(props.setProfileCountry).toHaveBeenCalledWith('United States'); + expect(props.setCurrency).toHaveBeenCalledWith('USD'); + + const phoneInput = container.querySelector('#phone-input') as HTMLInputElement; + await user.type(phoneInput, '5'); + expect(props.setProfilePhone).toHaveBeenCalled(); + + // Download invoice from ProfileDrawer + await user.click(screen.getByRole('button', { name: /Invoice/i })); + expect(props.onDownloadInvoice).toHaveBeenCalled(); + + await user.click(screen.getByRole('button', { name: /Save Profile Details/i })); + expect(props.onUpdateProfile).toHaveBeenCalled(); + + await user.click(screen.getByRole('button', { name: /Change Password/i })); + expect(props.setShowPasswordChange).toHaveBeenCalledWith(true); + + await user.click(screen.getByRole('button', { name: /Log Out Session/i })); + expect(props.onLogout).toHaveBeenCalledTimes(1); + }); + + it('renders change password form when expanded and submits', async () => { + const user = userEvent.setup(); + const props = makeProps({ + showPasswordChange: true, + changeOldPassword: 'OldPassword1!', + changeNewPassword: 'NewPassword1!', + changeConfirmPassword: 'NewPassword1!', + changePasswordError: 'Weak password', + }); + const { container } = render(); + + expect(screen.getByText('Weak password')).toBeInTheDocument(); + const pwdInputs = container.querySelectorAll('input[type="password"]'); + await user.type(pwdInputs[0] as HTMLInputElement, '1'); + await user.type(pwdInputs[1] as HTMLInputElement, '2'); + await user.type(pwdInputs[2] as HTMLInputElement, '3'); + expect(props.setChangeOldPassword).toHaveBeenCalled(); + expect(props.setChangeNewPassword).toHaveBeenCalled(); + expect(props.setChangeConfirmPassword).toHaveBeenCalled(); + + await user.click(screen.getByRole('button', { name: /Update Password/i })); + expect(props.onChangePassword).toHaveBeenCalled(); + + // Toggle password visibility icons & hide form + const eyeBtns = Array.from(container.querySelectorAll('button[type="button"]')).filter((b) => + b.querySelector('svg.lucide-eye, svg.lucide-eye-off') + ); + for (const btn of eyeBtns) { + await user.click(btn); + } + await user.click(screen.getByRole('button', { name: /Hide Form/i })); + expect(props.setShowPasswordChange).toHaveBeenCalledWith(false); + }); +}); diff --git a/tests/unit/components/SubscriptionsView.test.tsx b/tests/unit/components/SubscriptionsView.test.tsx new file mode 100644 index 0000000..e47450b --- /dev/null +++ b/tests/unit/components/SubscriptionsView.test.tsx @@ -0,0 +1,75 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { SubscriptionsView } from '../../../src/components/subscriptions/SubscriptionsView'; + +describe('SubscriptionsView', () => { + it('renders unauthenticated prompt and opens auth modal on click', async () => { + const user = userEvent.setup(); + const onOpenAuth = vi.fn(); + render( + + ); + await user.click(screen.getByRole('button', { name: 'Log In' })); + expect(onOpenAuth).toHaveBeenCalledTimes(1); + }); + + it('renders empty state and navigates to catalog', async () => { + const user = userEvent.setup(); + const onSwitchTab = vi.fn(); + render( + + ); + await user.click(screen.getByRole('button', { name: 'Explore Modules Catalog' })); + expect(onSwitchTab).toHaveBeenCalledWith('storefront'); + }); + + it('renders active, lifetime, expired, and paginated subscriptions with invoice download', async () => { + const user = userEvent.setup(); + const onDownloadInvoice = vi.fn(); + const future = new Date(Date.now() + 30 * 86400000).toISOString(); + const past = new Date(Date.now() - 5 * 86400000).toISOString(); + + const subs = [ + { id: 1, plan_code: 'LIFETIME_ALL', status: 'ACTIVE', started_at: '2026-01-01', expires_at: '', payment_id: 'p1', invoice_number: 'INV-1' }, + { id: 2, plan_code: 'POINTS_ACU', status: 'ACTIVE', started_at: '2026-01-01', expires_at: past, payment_id: 'p2' }, + ...Array.from({ length: 5 }, (_, i) => ({ + id: i + 3, + plan_code: `MOD_${i}`, + status: 'ACTIVE', + started_at: '2026-01-01', + expires_at: future, + })), + ]; + + render( + + ); + + expect(screen.getByText('Lifetime Access')).toBeInTheDocument(); + expect(screen.getByText('Expired')).toBeInTheDocument(); + await user.click(screen.getAllByRole('button', { name: /Download Invoice/i })[0]); + expect(onDownloadInvoice).toHaveBeenCalledWith('p1', undefined); + + await user.click(screen.getByRole('button', { name: '2' })); + expect(screen.getByText('MOD 4')).toBeInTheDocument(); + }); +}); diff --git a/tests/unit/constants/countries.test.ts b/tests/unit/constants/countries.test.ts new file mode 100644 index 0000000..b55901c --- /dev/null +++ b/tests/unit/constants/countries.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest'; +import { + COUNTRY_CODES, + DEFAULT_COUNTRY, + SORTED_COUNTRY_CODES, + getCountryRuleByDialCode, + getCountryRuleByIso, + getCountryRuleByName, +} from '../../../src/constants/countries'; + +describe('countries constants & helpers', () => { + it('exports sorted country codes and India as default', () => { + expect(DEFAULT_COUNTRY.country).toBe('India'); + expect(DEFAULT_COUNTRY.code).toBe('+91'); + expect(SORTED_COUNTRY_CODES.length).toBe(COUNTRY_CODES.length); + }); + + it('resolves country rule by ISO2 code with default fallback', () => { + expect(getCountryRuleByIso(null)).toEqual(DEFAULT_COUNTRY); + expect(getCountryRuleByIso(' de ')).toMatchObject({ country: 'Germany', code: '+49' }); + expect(getCountryRuleByIso('ZZ')).toEqual(DEFAULT_COUNTRY); + }); + + it('resolves country rule by name, ISO, partial match, or custom fallback', () => { + expect(getCountryRuleByName('')).toEqual(DEFAULT_COUNTRY); + expect(getCountryRuleByName('Germany')).toMatchObject({ iso2: 'DE', code: '+49' }); + expect(getCountryRuleByName('gb')).toMatchObject({ country: 'United Kingdom' }); + expect(getCountryRuleByName('Republic of Singapore')).toMatchObject({ country: 'Singapore' }); + + const unknown = getCountryRuleByName('Atlantis'); + expect(unknown).toMatchObject({ + country: 'Atlantis', + currency: 'USD', + minLength: 7, + maxLength: 15, + }); + }); + + it('resolves country rule by dial code with country hint and fallback', () => { + expect(getCountryRuleByDialCode(null)).toEqual(DEFAULT_COUNTRY); + expect(getCountryRuleByDialCode('+1', 'Canada')).toMatchObject({ country: 'Canada', iso2: 'CA' }); + expect(getCountryRuleByDialCode('+44')).toMatchObject({ country: 'United Kingdom' }); + expect(getCountryRuleByDialCode('+999', 'CustomLand')).toMatchObject({ + code: '+999', + country: 'CustomLand', + }); + expect(getCountryRuleByDialCode('+999')).toMatchObject({ + code: '+999', + country: 'Other', + }); + }); +}); diff --git a/tests/unit/constants/modules.test.ts b/tests/unit/constants/modules.test.ts new file mode 100644 index 0000000..485045e --- /dev/null +++ b/tests/unit/constants/modules.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; +import { CURRICULUM_MODULES } from '../../../src/constants/modules'; + +describe('CURRICULUM_MODULES', () => { + it('contains all core categories, complete packs, and lifetime pass with valid prices', () => { + expect(CURRICULUM_MODULES.length).toBeGreaterThanOrEqual(15); + const categories = new Set(CURRICULUM_MODULES.map((m) => m.category)); + expect(categories).toEqual(new Set(['Points', 'Pattern', 'Nutrition', 'Therapeutics', 'Lifetime'])); + + for (const mod of CURRICULUM_MODULES) { + expect(mod.code).toBeTruthy(); + expect(mod.name).toBeTruthy(); + expect(mod.priceInr).toBeGreaterThan(0); + expect(mod.priceUsd).toBeGreaterThan(0); + expect(mod.priceEur).toBeGreaterThan(0); + } + }); +}); diff --git a/tests/unit/services/services.test.ts b/tests/unit/services/services.test.ts new file mode 100644 index 0000000..c20b401 --- /dev/null +++ b/tests/unit/services/services.test.ts @@ -0,0 +1,46 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { api, API_BASE } from '../../../src/services/api'; +import { loadRazorpayScript } from '../../../src/services/razorpay'; + +describe('services', () => { + afterEach(() => { + delete (window as any).Razorpay; + document.body.innerHTML = ''; + }); + + describe('api service', () => { + it('configures axios instance and attaches Bearer token from localStorage', async () => { + expect(typeof API_BASE).toBe('string'); + localStorage.setItem('access_token', 'jwt-123'); + const handlers = (api.interceptors.request as any).handlers; + const fulfilled = handlers[0].fulfilled; + const cfg = await fulfilled({ headers: {} }); + expect(cfg.headers.Authorization).toBe('Bearer jwt-123'); + + localStorage.removeItem('access_token'); + const cfgNoToken = await fulfilled({ headers: {} }); + expect(cfgNoToken.headers.Authorization).toBeUndefined(); + }); + }); + + describe('razorpay service', () => { + it('resolves true immediately if window.Razorpay already exists', async () => { + (window as any).Razorpay = function () {}; + await expect(loadRazorpayScript()).resolves.toBe(true); + }); + + it('appends script and resolves true on load and false on error', async () => { + const p1 = loadRazorpayScript(); + const script1 = document.body.querySelector('script')!; + expect(script1.src).toContain('checkout.razorpay.com/v1/checkout.js'); + script1.onload?.(new Event('load')); + await expect(p1).resolves.toBe(true); + + document.body.innerHTML = ''; + const p2 = loadRazorpayScript(); + const script2 = document.body.querySelector('script')!; + script2.onerror?.(new Event('error')); + await expect(p2).resolves.toBe(false); + }); + }); +}); diff --git a/tests/unit/setup.ts b/tests/unit/setup.ts new file mode 100644 index 0000000..0d74b73 --- /dev/null +++ b/tests/unit/setup.ts @@ -0,0 +1,7 @@ +import '@testing-library/jest-dom/vitest'; +import { cleanup } from '@testing-library/react'; +import { afterEach } from 'vitest'; + +afterEach(() => { + cleanup(); +}); diff --git a/tests/unit/utils/navigation.test.ts b/tests/unit/utils/navigation.test.ts new file mode 100644 index 0000000..19e6c95 --- /dev/null +++ b/tests/unit/utils/navigation.test.ts @@ -0,0 +1,49 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + DEFAULT_APP_SCHEMES, + DEFAULT_RETURN_ROUTE, + formatDeepLinkRoute, + getAppDeepLinkUrls, + openMobileApp, +} from '../../../src/utils/navigation'; + +describe('navigation utils', () => { + const originalLocation = window.location; + + beforeEach(() => { + vi.useFakeTimers(); + Object.defineProperty(window, 'location', { + configurable: true, + value: { href: 'http://localhost:3000/store/' }, + }); + }); + + afterEach(() => { + vi.useRealTimers(); + Object.defineProperty(window, 'location', { + configurable: true, + value: originalLocation, + }); + }); + + it('formats deep link routes cleanly', () => { + expect(formatDeepLinkRoute()).toBe(DEFAULT_RETURN_ROUTE); + expect(formatDeepLinkRoute('///')).toBe(DEFAULT_RETURN_ROUTE); + expect(formatDeepLinkRoute('/subscriptions/')).toBe('subscriptions/'); + }); + + it('generates deep link URLs for default and custom schemes', () => { + expect(getAppDeepLinkUrls()).toEqual(DEFAULT_APP_SCHEMES.map((s) => `${s}://${DEFAULT_RETURN_ROUTE}`)); + expect(getAppDeepLinkUrls({ route: '/profile', schemes: ['customapp'] })).toEqual([ + 'customapp://profile', + ]); + }); + + it('opens mobile app primary URL and schedules fallback URLs', () => { + openMobileApp({ route: '/modules', schemes: ['acupedia', 'myapp'], delayBetweenFallbacks: 300 }); + expect(window.location.href).toBe('acupedia://modules'); + + vi.advanceTimersByTime(300); + expect(window.location.href).toBe('myapp://modules'); + }); +}); diff --git a/tests/unit/utils/validation.test.ts b/tests/unit/utils/validation.test.ts new file mode 100644 index 0000000..b67440b --- /dev/null +++ b/tests/unit/utils/validation.test.ts @@ -0,0 +1,164 @@ +import { describe, expect, it } from 'vitest'; +import { + EMAIL_REGEX, + SPECIAL_CHAR_REGEX, + cleanPhoneInput, + formatE164Phone, + formatPrefixList, + isValidEmail, + isValidPhoneNumber, + parsePhoneNumber, + updatePhoneDialCode, + validateEmail, + validatePassword, + validatePhoneNumber, +} from '../../../src/utils/validation'; + +describe('validation utils', () => { + describe('formatPrefixList', () => { + it('handles empty, single, two, and multiple prefixes', () => { + expect(formatPrefixList([])).toBe(''); + expect(formatPrefixList(['3'])).toBe('3'); + expect(formatPrefixList(['6', '7'])).toBe('6 or 7'); + expect(formatPrefixList(['6', '7', '8', '9'])).toBe('6, 7, 8, or 9'); + }); + }); + + describe('cleanPhoneInput', () => { + it('strips non-numeric chars, respects allowPlus and maxLength', () => { + expect(cleanPhoneInput(' +91 987-654-3210 ', 12, true)).toBe('+919876543210'); + expect(cleanPhoneInput('+91 9876543210', 10, false)).toBe('9198765432'); + expect(cleanPhoneInput('abc12345def', 0, true)).toBe('12345'); + }); + }); + + describe('validatePhoneNumber & isValidPhoneNumber', () => { + it('returns null for empty/whitespace values', () => { + expect(validatePhoneNumber('')).toBeNull(); + expect(validatePhoneNumber(' ')).toBeNull(); + expect(validatePhoneNumber(null)).toBeNull(); + expect(isValidPhoneNumber(undefined)).toBe(true); + }); + + it('rejects alphabetic characters, hyphens, and non-digit symbols', () => { + expect(validatePhoneNumber('98765abc10', '+91', 'India')).toContain('alphabetic'); + expect(validatePhoneNumber('789--98--809', '+91', 'India')).toContain('hyphens'); + expect(validatePhoneNumber('98765@3210', '+91', 'India')).toContain('only numeric digits'); + expect(validatePhoneNumber('+ ', '+91', 'India')).toContain('numeric digits'); + }); + + it('enforces exact and variable length rules', () => { + expect(validatePhoneNumber('98765', '+91', 'India')).toContain('exactly 10 digits'); + expect(validatePhoneNumber('12345', '+49', 'Germany')).toContain('too short'); + expect(validatePhoneNumber('1512345678901234', '+49', 'Germany')).toContain('cannot exceed'); + }); + + it('enforces valid mobile prefixes and rejects landlines', () => { + expect(validatePhoneNumber('5123456789', '+91', 'India')).toContain('must start with'); + // Valid Indian mobile + expect(validatePhoneNumber('9876543210', '+91', 'India')).toBeNull(); + expect(isValidPhoneNumber('+919876543210', '+91', 'India')).toBe(true); + // Trunk 0 stripping for UK + expect(validatePhoneNumber('07123456789', '+44', 'United Kingdom')).toBeNull(); + // Dial code prefix without '+' when longer than maxLength + expect(validatePhoneNumber('919876543210', '+91', 'India')).toBeNull(); + // Fallback when country is not provided -> resolves by dialCode + expect(validatePhoneNumber('9876543210', '+91')).toBeNull(); + // Fallback when neither country nor dialCode provided -> DEFAULT_COUNTRY + expect(validatePhoneNumber('9876543210')).toBeNull(); + // Fixed line rejection (e.g. US/UK or invalid mobile) + expect(validatePhoneNumber('15123456789', '+49', 'Germany')).toBeNull(); + expect(validatePhoneNumber('2025550173', '+1', 'United States')).toBeNull(); // US numbers are FIXED_LINE_OR_MOBILE + // Invalid UK landline 020... + const ukLandline = validatePhoneNumber('7123456789', '+44', 'United Kingdom'); + expect(ukLandline).toBeNull(); + // Invalid number with valid prefix but rejected by libphonenumber-js + expect(validatePhoneNumber('0000000000', '+91', 'India')).toContain('must start with'); + expect(validatePhoneNumber('07700900123', '+44', 'United Kingdom')).toContain('Please enter a valid mobile number'); + }); + }); + + describe('parsePhoneNumber', () => { + it('parses empty, valid E.164, and fallback numbers', () => { + expect(parsePhoneNumber('', 'India')).toEqual({ + country: 'India', + dialCode: '+91', + localDigits: '', + iso2: 'IN', + }); + + const parsedIn = parsePhoneNumber('+919876543210', 'India'); + expect(parsedIn).toEqual({ + country: 'India', + dialCode: '+91', + localDigits: '9876543210', + iso2: 'IN', + }); + + const parsedDe = parsePhoneNumber('+491512345678', 'India'); + expect(parsedDe.country).toBe('Germany'); + expect(parsedDe.dialCode).toBe('+49'); + + // Fallback when unparseable by libphonenumber-js + const fallbackSame = parsePhoneNumber('+91 123', 'India'); + expect(fallbackSame.dialCode).toBe('+91'); + + const fallbackOther = parsePhoneNumber('+49', 'India'); + expect(fallbackOther.dialCode).toBe('+49'); + expect(fallbackOther.country).toBe('Germany'); + + const rawOnly = parsePhoneNumber('9876', 'India'); + expect(rawOnly.localDigits).toBe('9876'); + + const unknownCode = parsePhoneNumber('+999123', 'India'); + expect(unknownCode.localDigits).toBe('999123'); + }); + }); + + describe('formatE164Phone', () => { + it('formats valid and fallback E.164 strings', () => { + expect(formatE164Phone('+91', '')).toBe(''); + expect(formatE164Phone('+91', 'abc')).toBe(''); + expect(formatE164Phone('+91', '9876543210', 'India')).toBe('+919876543210'); + expect(formatE164Phone('44', '07123456789', 'United Kingdom')).toBe('+447123456789'); + // Fallback trunk 0 removal when invalid + expect(formatE164Phone('+91', '0123', 'India')).toBe('+91123'); + // Italy keeps trunk 0 in fallback + expect(formatE164Phone('+39', '0123', 'Italy')).toBe('+390123'); + }); + }); + + describe('updatePhoneDialCode', () => { + it('updates dial code and clamps to new country maxLength', () => { + expect(updatePhoneDialCode('', 'India', 'Germany')).toBe(''); + expect(updatePhoneDialCode('+91 9876543210', 'India', 'Singapore')).toBe('+65 98765432'); + expect(updatePhoneDialCode('+91', 'India', 'Germany')).toBe('+49 '); + }); + }); + + describe('validatePassword', () => { + it('enforces all password complexity rules', () => { + expect(SPECIAL_CHAR_REGEX.test('!')).toBe(true); + expect(validatePassword('')).toBe('Password is required.'); + expect(validatePassword('Ab1!')).toContain('at least 8 characters'); + expect(validatePassword('Abcd 1234!')).toContain('must not contain spaces'); + expect(validatePassword('abcd1234!')).toContain('uppercase'); + expect(validatePassword('Abcdefgh!')).toContain('number'); + expect(validatePassword('Abcd1234😀!')).toContain('emojis'); + expect(validatePassword('Abcd12345')).toContain('special character'); + expect(validatePassword('ValidPass1!')).toBeNull(); + }); + }); + + describe('validateEmail & isValidEmail', () => { + it('validates RFC-compliant emails', () => { + expect(EMAIL_REGEX.test('user@example.com')).toBe(true); + expect(validateEmail('')).toBe('Email address is required.'); + expect(validateEmail(' ')).toBe('Email address is required.'); + expect(validateEmail('invalid-email')).toBe('Please enter a valid email address.'); + expect(validateEmail('user@example.com')).toBeNull(); + expect(isValidEmail('user.name+1@sub.example.co.in')).toBe(true); + expect(isValidEmail('bad@')).toBe(false); + }); + }); +}); diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..a1800c6 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,25 @@ +import { defineConfig } from 'vitest/config'; +import react from '@vitejs/plugin-react'; + +export default defineConfig({ + plugins: [react()], + test: { + environment: 'jsdom', + globals: true, + setupFiles: ['./tests/unit/setup.ts'], + include: ['tests/unit/**/*.test.{ts,tsx}'], + coverage: { + provider: 'v8', + reporter: ['text', 'html', 'lcov'], + reportsDirectory: './coverage', + include: ['src/**/*.{ts,tsx}'], + exclude: ['src/main.tsx', 'src/types/**'], + thresholds: { + lines: 84, + functions: 84, + branches: 70, + statements: 80, + }, + }, + }, +});