test(storefront): phase 1 unit & component test suite with 99% line coverage

This commit is contained in:
Urvish Prajapati 2026-11-27 15:14:35 +05:30
parent 25594ec512
commit 4356f8321f
13 changed files with 1700 additions and 8 deletions

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

993
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -8,6 +8,9 @@
"build": "tsc -b && vite build",
"lint": "eslint .",
"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",
@ -24,19 +27,25 @@
"@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"
}
}

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

29
vitest.config.ts Normal file
View File

@ -0,0 +1,29 @@
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/utils/**/*.{ts,tsx}',
'src/services/**/*.{ts,tsx}',
'src/constants/**/*.{ts,tsx}',
'src/components/common/**/*.{ts,tsx}',
],
thresholds: {
lines: 95,
functions: 95,
branches: 90,
statements: 95,
},
},
},
});