import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import axios from 'axios'; import App from '../../src/App'; vi.mock('axios', () => { const mockAxios = { get: vi.fn(), post: vi.fn(), put: vi.fn(), isAxiosError: vi.fn((err) => Boolean(err?.isAxiosError)), create: vi.fn(), interceptors: { request: { use: vi.fn() }, response: { use: vi.fn() }, }, }; mockAxios.create.mockReturnValue(mockAxios); return { default: mockAxios }; }); const mockedAxios = axios as unknown as { get: ReturnType; post: ReturnType; put: ReturnType; }; const mockPlansResponse = [ { code: 'LIFETIME_ALL', name: 'Lifetime All-Access Plan', plan_type: 'bundle', billing_period: 'lifetime', price_inr: 15000, price_usd: 350, price_eur: 350, is_active: true, module_slugs: ['acupuncture-points'], }, { code: 'POINTS_ACU', name: 'Acu Points Module (1 Yr)', plan_type: 'one_time', billing_period: 'yearly', price_inr: 300, price_usd: 5, price_eur: 5, is_active: true, module_slugs: ['acupuncture-points'], }, { 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: 'THERAPEUTICS_CORE', name: 'Therapeutics Complete Bundle (1 Yr)', plan_type: 'bundle', billing_period: 'yearly', price_inr: 0, price_usd: 30, price_eur: 30, is_active: true, module_slugs: ['auriculotherapy', 'gynecological-disorders'], }, ]; function setupAxiosMocks(userOverrides: Record = {}) { mockedAxios.get.mockImplementation((url: string) => { if (url.includes('/api/checkout/config')) { return Promise.resolve({ data: { razorpay_key_id: 'rzp_test_123' } }); } if (url.includes('/api/plans')) { return Promise.resolve({ data: mockPlansResponse }); } if (url.includes('/api/contents/modules')) { return Promise.resolve({ data: [{ slug: 'acupuncture-points', name: 'Acupuncture Points', is_active: true }] }); } if (url.includes('/api/auth/profile')) { return Promise.resolve({ data: { id: 1, email: 'doc@acupedia.com', display_name: 'Dr. Lin', phone_number: '+919876543210', country: 'India', ...userOverrides, }, }); } if (url.includes('/api/access/me')) { return Promise.resolve({ data: { unlocked_module_codes: userOverrides.unlocked_module_codes || [], active_subscriptions: userOverrides.active_subscriptions || [], }, }); } return Promise.resolve({ data: {} }); }); mockedAxios.post.mockImplementation((url: string, body: any) => { if (url.includes('/api/cart/calculate')) { const hasCoupon = body?.coupon_code === 'SAVE20'; return Promise.resolve({ data: { currency: body?.currency || 'INR', base_subtotal: 300, bundle_discount_amount: 0, coupon_discount_amount: hasCoupon ? 60 : 0, total_discounts: hasCoupon ? 60 : 0, convenience_fee_rate: 0, convenience_fee: 0, taxable_amount: 0, gst_amount: 0, grand_total: hasCoupon ? 240 : 300, discount_policy: 'None', coupon_applied: hasCoupon ? 'Code: SAVE20 - 20% Off' : 'None', coupon_error: body?.coupon_code && !hasCoupon ? 'Invalid coupon' : null, }, }); } if (url.includes('/api/auth/login')) { return Promise.resolve({ data: { access_token: 'mock-jwt' } }); } if (url.includes('/api/auth/register')) { return Promise.resolve({ data: { access_token: 'mock-jwt' } }); } if (url.includes('/api/auth/forgot-password')) { return Promise.resolve({ data: { message: 'OTP sent' } }); } if (url.includes('/api/auth/reset-password')) { return Promise.resolve({ data: { message: 'Reset done' } }); } if (url.includes('/api/auth/change-password')) { return Promise.resolve({ data: { status: 'success' } }); } if (url.includes('/api/checkout/create-order')) { return Promise.resolve({ data: { razorpay_order_id: 'order_123', grand_total: 300 } }); } if (url.includes('/api/checkout/verify')) { return Promise.resolve({ data: { status: 'success', invoice_number: 'INV-123', invoice_url: '/api/checkout/payment/pay_123/invoice/view', }, }); } return Promise.resolve({ data: {} }); }); mockedAxios.put.mockResolvedValue({ data: { status: 'success' } }); } describe('App Integration', () => { vi.setConfig({ testTimeout: 15000 }); beforeEach(() => { localStorage.clear(); window.history.pushState({}, '', '/store/'); vi.stubGlobal('alert', vi.fn()); vi.stubGlobal('open', vi.fn()); setupAxiosMocks(); }); afterEach(() => { vi.unstubAllGlobals(); vi.clearAllMocks(); }); it('handles ?planCode deep-link, coupon apply/remove, and unauthenticated checkout trigger', async () => { const user = userEvent.setup(); window.history.pushState({}, '', '/store/?planCode=POINTS_ACU'); render(); await waitFor(() => expect(screen.getByText('1 Item')).toBeInTheDocument()); // Apply valid coupon const couponInput = screen.getByPlaceholderText('e.g. AGENT40, EVENT_NEW'); await user.type(couponInput, 'SAVE20'); await user.click(screen.getByRole('button', { name: 'Apply' })); await waitFor(() => expect(screen.getByText(/Coupon Active: SAVE20/)).toBeInTheDocument()); // Remove coupon await user.click(screen.getByRole('button', { name: 'Remove' })); await waitFor(() => expect(screen.queryByText(/Coupon Active: SAVE20/)).not.toBeInTheDocument()); // Checkout while logged out opens Create Account modal await user.click(screen.getByRole('button', { name: /Secure Payment with Razorpay/i })); expect(screen.getByRole('heading', { name: 'Create Account' })).toBeInTheDocument(); }); it('handles login, profile update, password change, and logout flows', async () => { const user = userEvent.setup(); window.history.pushState({}, '', '/store/?login=true'); const { container } = render(); await waitFor(() => expect(screen.getByText('Welcome Back!')).toBeInTheDocument()); await user.type(container.querySelector('input[type="email"]') as HTMLInputElement, 'doc@acupedia.com'); await user.type(screen.getByPlaceholderText('••••••••'), 'Password1!'); await user.click(screen.getByRole('button', { name: /Sign In/i })); await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument()); // Open ProfileDrawer await user.click(screen.getByText('Dr. Lin')); await user.click(screen.getByRole('button', { name: /Save Profile Details/i })); await waitFor(() => expect(screen.getByText(/Changes saved successfully/i)).toBeInTheDocument()); // Log out await user.click(screen.getByRole('button', { name: /Log Out Session/i })); expect(screen.getByText('Successfully Logged Out')).toBeInTheDocument(); }); it('handles authenticated Razorpay checkout, verification, and invoice download', async () => { const user = userEvent.setup(); localStorage.setItem('access_token', 'mock-jwt'); (window as any).Razorpay = function (options: any) { this.on = vi.fn(); this.open = () => { options.handler({ razorpay_order_id: options.order_id, razorpay_payment_id: 'pay_123', razorpay_signature: 'sig_123', }); }; }; render(); await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument()); await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)')); await user.click(screen.getByRole('button', { name: /Secure Payment with Razorpay/i })); await waitFor(() => expect(screen.getByText('Thank You for Your Purchase!')).toBeInTheDocument()); await user.click(screen.getByText('Download Invoice PDF')); expect(window.open).toHaveBeenCalled(); }); it('handles register, forgot/reset password, change password, and ?token + /subscriptions', async () => { const user = userEvent.setup(); window.history.pushState({}, '', '/store/subscriptions?token=deep-token'); render(); await waitFor(() => expect(screen.getByText('No active subscriptions')).toBeInTheDocument()); // Switch to storefront and test bundle replacement + remove await user.click(screen.getByRole('button', { name: 'Explore Modules Catalog' })); await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)')); await user.click(screen.getAllByText('Complete Pack')[0]); await user.click(screen.getAllByText('Lifetime Unlimited Access Pass')[1]); expect(screen.getByText('1 Item')).toBeInTheDocument(); // Open ProfileDrawer and change password await user.click(screen.getByText('Dr. Lin')); await user.click(screen.getByRole('button', { name: /Change Password/i })); const pwdInputs = document.querySelectorAll('input[type="password"]'); await user.type(pwdInputs[0] as HTMLInputElement, 'OldPass1!'); await user.type(pwdInputs[1] as HTMLInputElement, 'NewPass1!'); await user.type(pwdInputs[2] as HTMLInputElement, 'NewPass1!'); await user.click(screen.getByRole('button', { name: /Update Password/i })); await waitFor(() => expect(screen.getByText('Password Updated!')).toBeInTheDocument()); await user.click(screen.getByRole('button', { name: /Log In with New Password/i })); // Test Forgot Password flow inside AuthModal await user.click(screen.getByRole('button', { name: /Forgot password/i })); const emailInput = document.querySelector('input[type="email"]') as HTMLInputElement; await user.clear(emailInput); await user.type(emailInput, 'doc@acupedia.com'); await user.click(screen.getByRole('button', { name: /Send Verification Code/i })); await waitFor(() => expect(screen.getByRole('button', { name: /Set New Password/i })).toBeInTheDocument()); const resetPwdInputs = document.querySelectorAll('input[type="password"]'); await user.type(document.querySelector('input[placeholder*="6-digit" i], input[maxlength="6"]') as HTMLInputElement || document.querySelectorAll('input[type="text"]')[0], '123456'); await user.type(resetPwdInputs[0] as HTMLInputElement, 'ResetPass1!'); await user.type(resetPwdInputs[1] as HTMLInputElement, 'ResetPass1!'); await user.click(screen.getByRole('button', { name: /Set New Password/i })); await waitFor(() => expect(screen.getByText('Password Updated!')).toBeInTheDocument()); }, 15000); it('handles missing billing phone during checkout, Razorpay dismiss, and verify error', async () => { const user = userEvent.setup(); localStorage.setItem('access_token', 'mock-jwt'); setupAxiosMocks({ phone_number: '' }); let dismissMode = false; (window as any).Razorpay = function (options: any) { this.on = vi.fn(); this.open = () => { if (dismissMode) { options.modal.ondismiss(); } else { options.handler({ razorpay_order_id: options.order_id, razorpay_payment_id: 'pay_err', razorpay_signature: 'bad_sig', }); } }; }; render(); await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument()); await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)')); await user.click(screen.getByRole('button', { name: /Secure Payment with Razorpay/i })); await waitFor(() => expect(screen.getByText('Billing Contact Number')).toBeInTheDocument()); const phoneInput = document.querySelector('#phone-input') as HTMLInputElement; await user.type(phoneInput, '9876543210'); // Make verify reject so we test verify error branch too mockedAxios.post.mockImplementation((url: string) => { if (url.includes('/api/checkout/verify')) { return Promise.reject({ response: { data: { detail: 'Bad sig' } } }); } if (url.includes('/api/checkout/create-order')) { return Promise.resolve({ data: { razorpay_order_id: 'order_123', grand_total: 300 } }); } return Promise.resolve({ data: {} }); }); await user.click(screen.getByRole('button', { name: 'Save Phone Number' })); await waitFor(() => expect(screen.getByText('Verification Failed')).toBeInTheDocument()); dismissMode = true; await user.click(screen.getByRole('button', { name: /Secure Payment with Razorpay/i })); await waitFor(() => expect(screen.getByRole('button', { name: /Secure Payment with Razorpay/i })).toBeEnabled()); }); it('handles register flow, lifetime banner, and error branches', async () => { const user = userEvent.setup(); window.history.pushState({}, '', '/store/?logged_out=true'); const { unmount } = render(); expect(screen.getByText('Successfully Logged Out')).toBeInTheDocument(); await user.click(screen.getAllByRole('link')[0]); expect(screen.getByText('Welcome Back!')).toBeInTheDocument(); // Switch to register mode and test registration await user.click(screen.getByRole('button', { name: 'Create an account' })); const textInputs = document.querySelectorAll('input[type="text"]'); await user.type(textInputs[0] as HTMLInputElement, 'Dr. Test'); await user.type(document.querySelector('input[type="email"]') as HTMLInputElement, 'new@acupedia.com'); await user.type(document.querySelector('#phone-input') as HTMLInputElement, '9876543210'); await user.type(document.querySelector('input[type="password"]') as HTMLInputElement, 'StrongPass1!'); await user.click(screen.getByRole('button', { name: 'Create Account' })); await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument()); unmount(); // Render with LIFETIME_ALL unlocked -> shows LifetimeBanner localStorage.setItem('access_token', 'mock-jwt'); setupAxiosMocks({ unlocked_module_codes: ['LIFETIME_ALL'], active_subscriptions: [{ id: 1, plan_code: 'LIFETIME_ALL', status: 'ACTIVE', started_at: '2026-01-01', expires_at: '' }], }); window.history.pushState({}, '', '/store/'); render(); await waitFor(() => expect(screen.getByText('LIFETIME ACCESS PASSPORT ACTIVE!')).toBeInTheDocument()); }, 15000); it('handles validation errors, API failures, payment.failed, and modal close callbacks', async () => { const user = userEvent.setup(); render(); await waitFor(() => expect(screen.getByText('Acu (EOV+Cat+Ext+MR)')).toBeInTheDocument()); // Unauthenticated Subscriptions tab -> Log In -> close AuthModal await user.click(screen.getAllByRole('button', { name: /My Subscriptions/i })[0]); await user.click(screen.getByRole('button', { name: 'Log In' })); expect(screen.getByText('Welcome Back!')).toBeInTheDocument(); // Test login API failure mockedAxios.post.mockRejectedValueOnce({ response: { data: { detail: 'Bad credentials' } } }); await user.type(document.querySelector('input[type="email"]') as HTMLInputElement, 'doc@acupedia.com'); await user.type(document.querySelector('input[type="password"]') as HTMLInputElement, 'Wrong1!'); await user.click(screen.getByRole('button', { name: /Sign In/i })); await waitFor(() => expect(screen.getByText('Bad credentials')).toBeInTheDocument()); // Close AuthModal const closeBtn = document.querySelector('button svg.lucide-x-circle')?.closest('button') as HTMLButtonElement; await user.click(closeBtn); expect(screen.queryByText('Welcome Back!')).not.toBeInTheDocument(); // Switch back to Storefront and test Razorpay payment.failed + Return to Storefront close await user.click(screen.getAllByRole('button', { name: /Storefront/i })[0]); localStorage.setItem('access_token', 'mock-jwt'); setupAxiosMocks(); window.history.pushState({}, '', '/store/?token=mock-jwt'); const { unmount } = render(); await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument()); let failCb: any; (window as any).Razorpay = function (options: any) { this.on = (ev: string, cb: any) => { if (ev === 'payment.failed') failCb = cb; }; this.open = () => { if (failCb) failCb({ error: { description: 'Card declined' } }); options.handler({ razorpay_order_id: options.order_id, razorpay_payment_id: 'pay_ok', razorpay_signature: 'sig_ok', }); }; }; await user.click(screen.getAllByText('Acu (EOV+Cat+Ext+MR)')[1]); await user.click(screen.getAllByRole('button', { name: /Secure Payment with Razorpay/i })[0]); await waitFor(() => expect(screen.getByText('Thank You for Your Purchase!')).toBeInTheDocument()); expect(window.alert).toHaveBeenCalledWith(expect.stringContaining('Card declined')); await user.click(screen.getByRole('button', { name: 'Return to Storefront' })); await waitFor(() => expect(screen.queryByText('Thank You for Your Purchase!')).not.toBeInTheDocument()); unmount(); }, 15000); it('handles register/reset/change-password validation errors, CartDrawer Add Number, and ProfileDrawer navigation', async () => { const user = userEvent.setup(); localStorage.setItem('access_token', 'mock-jwt'); setupAxiosMocks({ phone_number: '' }); window.history.pushState({}, '', '/store/'); render(); await waitFor(() => expect(screen.getByText('Dr. Lin')).toBeInTheDocument()); // Add item, remove item via CartDrawer trash button, re-add, click Add Number await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)')); await user.click(screen.getByTitle('Remove item')); expect(screen.getByText('0 Items')).toBeInTheDocument(); await user.click(screen.getByText('Acu (EOV+Cat+Ext+MR)')); await user.click(screen.getByRole('button', { name: 'Add Number' })); expect(screen.getByText('Billing Contact Number')).toBeInTheDocument(); await user.click(screen.getByRole('button', { name: 'Cancel' })); expect(screen.queryByText('Billing Contact Number')).not.toBeInTheDocument(); // Open ProfileDrawer -> test change password mismatch validation -> View Subscriptions -> close await user.click(screen.getByText('Dr. Lin')); await user.click(screen.getByRole('button', { name: /Change Password/i })); const pwdInputs = document.querySelectorAll('input[type="password"]'); await user.type(pwdInputs[0] as HTMLInputElement, 'OldPass1!'); await user.type(pwdInputs[1] as HTMLInputElement, 'NewPass1!'); await user.type(pwdInputs[2] as HTMLInputElement, 'Mismatch1!'); await user.click(screen.getByRole('button', { name: /Update Password/i })); await waitFor(() => expect(screen.getByText(/do not match/i)).toBeInTheDocument()); // Close ProfileDrawer const closeDrawerBtn = document.querySelector('button svg.lucide-x-circle')?.closest('button') as HTMLButtonElement; if (closeDrawerBtn) await user.click(closeDrawerBtn); }, 15000); it('hides plans absent from /api/plans (POINTS_TUNG) or unpriced in billing currency (THERAPEUTICS_CORE) and prunes them from cart', async () => { window.history.pushState({}, '', '/store/?planCode=POINTS_TUNG'); render(); // Wait for /api/plans to load and prune POINTS_TUNG from deep-linked cart & hide both unavailable plans await waitFor(() => { expect(screen.getByText('Acu (EOV+Cat+Ext+MR)')).toBeInTheDocument(); expect(screen.getByText('0 Items')).toBeInTheDocument(); }); expect(screen.queryByText('Master Tung')).not.toBeInTheDocument(); expect(screen.queryByText('₹0')).not.toBeInTheDocument(); }); it('keeps storefront visible and clears stale token silently when initial profile fetch fails', async () => { localStorage.setItem('access_token', 'stale-expired-jwt'); window.history.pushState({}, '', '/store/'); mockedAxios.get.mockImplementation((url: string) => { if (url.includes('/api/auth/profile')) { return Promise.reject({ response: { status: 401, data: { detail: 'Token expired' } } }); } 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/modules/categories')) return Promise.resolve({ data: [] }); return Promise.resolve({ data: {} }); }); render(); await waitFor(() => { expect(screen.getByText('Unlock Professional TCM Modules')).toBeInTheDocument(); expect(localStorage.getItem('access_token')).toBeNull(); }); expect(screen.queryByText('Successfully Logged Out')).not.toBeInTheDocument(); expect(window.location.pathname).toBe('/store/'); }); });