acupedia-store-ui/tests/unit/components/BillingPhoneModal.test.tsx

72 lines
2.5 KiB
TypeScript

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