Merge pull request 'test/storefront-e2e-setup' (#120) from test/storefront-e2e-setup into main

Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-store-ui/pulls/120
Reviewed-by: Amit Salunke <amit@noreply.localhost>
This commit is contained in:
Amit Salunke 2026-12-01 04:37:44 +00:00
commit 49a5ccbf54
33 changed files with 4444 additions and 9 deletions

5
.gitignore vendored
View File

@ -31,3 +31,8 @@ dist-ssr
# Generated Git Info
.git_*_info
# Playwright & Coverage
playwright-report/
test-results/
coverage/

53
TESTING.md Normal file
View File

@ -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
```

1039
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -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"
}
}

32
playwright.config.ts Normal file
View File

@ -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,
},
});

View File

@ -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();
});
});

View File

@ -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();
});
});

91
tests/e2e/catalog.spec.ts Normal file
View File

@ -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();
});
});

View File

@ -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();
});
});

View File

@ -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();
}
});
});

View File

@ -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<string, any> = {}) {
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),
});
});
}

View File

@ -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();
});
});

22
tests/e2e/smoke.spec.ts Normal file
View File

@ -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);
});
});

View File

@ -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();
});
});

441
tests/unit/App.test.tsx Normal file
View File

@ -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<typeof vi.fn>;
post: ReturnType<typeof vi.fn>;
put: ReturnType<typeof vi.fn>;
};
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<string, any> = {}) {
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(<App />);
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(<App />);
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(<App />);
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(<App />);
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(<App />);
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(<App />);
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(<App />);
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(<App />);
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(<App />);
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(<App />);
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);
});

View File

@ -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<string, any> = {}) => ({
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(<AuthModal {...makeProps({ isOpen: false })} />);
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(<AuthModal {...props} />);
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(<AuthModal {...props} />);
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(<AuthModal {...propsReq} />);
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(<AuthModal {...propsVerify} />);
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(<AuthModal {...makeProps({ authMode: 'forgot', resetStep: 'verify', resetOtp: '123456', resetNewPassword: 'NewPassword1!', resetConfirmPassword: 'NewPassword1!', onResetPasswordSubmit: propsVerify.onResetPasswordSubmit, setResetStep: propsVerify.setResetStep, setAuthMode: propsVerify.setAuthMode })} />);
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');
});
});

View File

@ -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(
<BillingPhoneModal isOpen={false} onClose={vi.fn()} onSavePhone={vi.fn()} />
);
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(
<BillingPhoneModal
isOpen={true}
onClose={onClose}
currentPhone=""
currentCountry="India"
onSavePhone={onSavePhone}
/>
);
// 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(
<BillingPhoneModal
isOpen={true}
onClose={vi.fn()}
currentPhone="+919876543210"
currentCountry="India"
onSavePhone={onSavePhone}
/>
);
// 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();
});
});

View File

@ -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(
<CartDrawer
cart={[]}
currency="INR"
toggleCartItem={vi.fn()}
couponCode=""
setCouponCode={vi.fn()}
appliedCoupon={null}
applyPromoCode={vi.fn()}
removePromoCode={vi.fn()}
pricingCalc={null}
loadingPricing={false}
loggedInUser={null}
onUpdateBillingPhone={vi.fn()}
verificationResult={null}
checkoutLoading={false}
handleCheckout={vi.fn()}
/>
);
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(
<CartDrawer
cart={[sampleItem]}
currency="INR"
toggleCartItem={vi.fn()}
couponCode="SAVE20"
setCouponCode={vi.fn()}
appliedCoupon="SAVE20"
applyPromoCode={vi.fn()}
removePromoCode={removePromoCode}
pricingCalc={{
currency: 'INR',
base_subtotal: 900,
renewal_discount_amount: 100,
bundle_discount_amount: 50,
coupon_discount_amount: 180,
total_discounts: 330,
convenience_fee_rate: 2,
convenience_fee: 10,
taxable_amount: 570,
gst_amount: 0,
grand_total: 580,
discount_policy: 'Staggered Buy: 10%',
coupon_applied: 'Code: SAVE20 - 20% Off',
coupon_error: null,
}}
loadingPricing={false}
loggedInUser={{
id: 1,
email: 'doc@acupedia.com',
country: 'India',
phone_number: '',
} as any}
onUpdateBillingPhone={onUpdateBillingPhone}
verificationResult={{ status: 'error', message: 'Signature mismatch' }}
checkoutLoading={false}
handleCheckout={handleCheckout}
/>
);
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(
<CartDrawer
cart={[sampleItem]}
currency="EUR"
toggleCartItem={vi.fn()}
couponCode="BAD"
setCouponCode={vi.fn()}
appliedCoupon="BAD"
applyPromoCode={vi.fn()}
removePromoCode={removePromoCode}
pricingCalc={{
currency: 'EUR',
base_subtotal: 15,
coupon_discount_amount: 0,
total_discounts: 3,
convenience_fee_rate: 0,
convenience_fee: 0,
taxable_amount: 0,
gst_amount: 0,
grand_total: 12,
coupon_applied: 'None',
coupon_error: 'Invalid coupon',
}}
loadingPricing={true}
loggedInUser={{
id: 1,
email: 'doc@acupedia.com',
country: 'Germany',
phone_number: '123',
} as any}
onUpdateBillingPhone={onUpdateBillingPhone}
verificationResult={null}
checkoutLoading={true}
handleCheckout={handleCheckout}
/>
);
expect(screen.getByText(/Invalid coupon/i)).toBeInTheDocument();
expect(screen.getByText(/Incomplete \(123\)/i)).toBeInTheDocument();
expect(screen.getByText('Total Discounts')).toBeInTheDocument();
});
});

View File

@ -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(<CatalogSection {...defaultProps} />);
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(
<CatalogSection
{...defaultProps}
currency="EUR"
isModuleUnlocked={() => 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();
});
});

View File

@ -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(
<CountrySelect value="India" onChange={onChange} showCurrency showDialCode theme="dark" size="sm" />
);
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(
<div>
<div data-testid="outside">Outside</div>
<CountrySelect value="India" onChange={vi.fn()} theme="light" />
</div>
);
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(<CountrySelect value="India" onChange={vi.fn()} disabled />);
await user.click(screen.getByRole('button'));
expect(screen.queryByPlaceholderText('Search country name or code...')).not.toBeInTheDocument();
rerender(<CountrySelect value="India" onChange={vi.fn()} showDialCode={false} showCurrency={false} />);
expect(screen.getByRole('button')).not.toHaveTextContent('+91');
});
});

View File

@ -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(<LoggedOutView onLoginAgain={onLoginAgain} />);
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(<PasswordUpdatedModal isOpen={false} onClose={onClose} />);
expect(screen.queryByText('Password Updated!')).not.toBeInTheDocument();
rerender(
<PasswordUpdatedModal
isOpen={true}
onClose={onClose}
title="Custom Title"
description="Custom Desc"
buttonText="Done"
/>
);
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(
<>
<StoreFooter />
<LifetimeBanner />
</>
);
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(
<StoreHeader
activeTab="storefront"
onSwitchTab={onSwitchTab}
loggedInUser={null}
onOpenProfile={onOpenProfile}
onOpenAuth={onOpenAuth}
/>
);
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(
<StoreHeader
activeTab="subscriptions"
onSwitchTab={onSwitchTab}
loggedInUser={{
id: 1,
email: 'doc@acupedia.com',
display_name: 'Dr. Lin',
country: 'India',
active_subscriptions: [{ id: 1, plan_code: 'POINTS_ACU', status: 'ACTIVE', started_at: '', expires_at: '' }],
} as any}
onOpenProfile={onOpenProfile}
onOpenAuth={onOpenAuth}
/>
);
await user.click(screen.getByText('Dr. Lin'));
expect(onOpenProfile).toHaveBeenCalledTimes(1);
});
});

View File

@ -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(
<Pagination currentPage={1} totalItems={0} itemsPerPage={6} onPageChange={vi.fn()} />
);
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(
<Pagination
currentPage={2}
totalItems={30}
itemsPerPage={6}
onPageChange={onPageChange}
onItemsPerPageChange={onItemsPerPageChange}
/>
);
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(
<Pagination currentPage={2} totalItems={120} itemsPerPage={10} onPageChange={vi.fn()} />
);
expect(screen.getAllByText('...')).toHaveLength(1);
rerender(<Pagination currentPage={6} totalItems={120} itemsPerPage={10} onPageChange={vi.fn()} />);
expect(screen.getAllByText('...')).toHaveLength(2);
rerender(<Pagination currentPage={11} totalItems={120} itemsPerPage={10} onPageChange={vi.fn()} />);
expect(screen.getAllByText('...')).toHaveLength(1);
});
});

View File

@ -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(
<PaymentSuccessModal
verificationResult={baseResult}
onClose={onClose}
loggedInUser={{ email: 'doc@acupedia.com' } as any}
onDownloadInvoice={onDownloadInvoice}
downloadingInvoice={false}
/>
);
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(
<PaymentSuccessModal
verificationResult={{ ...baseResult, currency: 'EUR', amount: 15 }}
onClose={vi.fn()}
loggedInUser={null}
onDownloadInvoice={vi.fn()}
downloadingInvoice={true}
/>
);
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(
<PaymentSuccessModal
verificationResult={{ ...baseResult, currency: 'USD', amount: 20 }}
onClose={vi.fn()}
loggedInUser={null}
onDownloadInvoice={vi.fn()}
downloadingInvoice={false}
/>
);
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(
<PaymentSuccessModal
verificationResult={baseResult}
onClose={vi.fn()}
loggedInUser={null}
onDownloadInvoice={vi.fn()}
downloadingInvoice={false}
/>
);
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(
<PaymentSuccessModal
verificationResult={{ ...baseResult, currency: 'USD' }}
onClose={vi.fn()}
loggedInUser={null}
onDownloadInvoice={vi.fn()}
downloadingInvoice={false}
/>
);
await user.click(screen.getByRole('button', { name: /Open in App \/ Library/i }));
act(() => {
vi.advanceTimersByTime(1000);
});
Object.defineProperty(navigator, 'userAgent', { value: originalUA, configurable: true });
});
});

View File

@ -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(
<PhoneInput
dialCode="+91"
phone=""
country="India"
onPhoneChange={onPhoneChange}
theme="light"
/>
);
const input = screen.getByRole('textbox');
await user.type(input, '98765');
expect(onPhoneChange).toHaveBeenCalled();
expect(input).toHaveAttribute('placeholder', '10-digit mobile number');
rerender(
<PhoneInput
dialCode="+49"
phone="151"
country="Germany"
onPhoneChange={onPhoneChange}
error="Invalid phone"
theme="dark"
/>
);
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(
<div>
<div data-testid="outside">Outside</div>
<PhoneInput
dialCode="+91"
phone="9876543210"
country="India"
onDialCodeChange={onDialCodeChange}
onPhoneChange={onPhoneChange}
clearOnDialCodeChange
/>
</div>
);
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(
<PhoneInput
dialCode="+91"
phone="9876543210"
onDialCodeChange={onDialCodeChange}
onPhoneChange={onPhoneChange}
theme="light"
/>
);
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(
<PhoneInput
dialCode="+91"
phone=""
onPhoneChange={onPhoneChange}
disabled
/>
);
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(
<PhoneInput
dialCode="+91"
phone=""
country="India"
onDialCodeChange={onDialCodeChange}
onPhoneChange={onPhoneChange}
/>
);
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);
});
});

View File

@ -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<string, any> = {}) => ({
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(<ProfileDrawer {...makeProps({ isOpen: false })} />);
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(<ProfileDrawer {...props} />);
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(<ProfileDrawer {...props} />);
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);
});
});

View File

@ -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(
<SubscriptionsView
loggedInUser={null}
onOpenAuth={onOpenAuth}
onSwitchTab={vi.fn()}
curriculumModules={[]}
/>
);
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(
<SubscriptionsView
loggedInUser={{ active_subscriptions: [] } as any}
onOpenAuth={vi.fn()}
onSwitchTab={onSwitchTab}
curriculumModules={[]}
/>
);
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(
<SubscriptionsView
loggedInUser={{ active_subscriptions: subs } as any}
onOpenAuth={vi.fn()}
onSwitchTab={vi.fn()}
curriculumModules={[
{ code: 'POINTS_ACU', name: 'Acu Points', category: 'Points', desc: 'Acu desc', priceInr: 300, priceUsd: 5, priceEur: 5 },
]}
onDownloadInvoice={onDownloadInvoice}
/>
);
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();
});
});

View File

@ -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',
});
});
});

View File

@ -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);
}
});
});

View File

@ -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);
});
});
});

7
tests/unit/setup.ts Normal file
View File

@ -0,0 +1,7 @@
import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterEach } from 'vitest';
afterEach(() => {
cleanup();
});

View File

@ -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');
});
});

View File

@ -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);
});
});
});

25
vitest.config.ts Normal file
View File

@ -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,
},
},
},
});