import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { CountrySelect } from '../../../src/components/common/CountrySelect';
describe('CountrySelect', () => {
it('opens dropdown, filters by country/dial code/currency, and selects a country', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
);
const trigger = screen.getByRole('button');
expect(trigger).toHaveTextContent('India');
expect(trigger).toHaveTextContent('+91');
await user.click(trigger);
const searchInput = screen.getByPlaceholderText('Search country name or code...');
await user.type(searchInput, 'Germany');
expect(screen.getByText('Germany')).toBeInTheDocument();
await user.click(screen.getByText('Germany'));
expect(onChange).toHaveBeenCalledWith('Germany');
});
it('shows empty state when no country matches and closes on Escape / outside click / clear', async () => {
const user = userEvent.setup();
render(
);
await user.click(screen.getByRole('button'));
const searchInput = screen.getByPlaceholderText('Search country name or code...');
await user.type(searchInput, 'ZzzUnknown');
expect(screen.getByText(/No countries found matching/)).toBeInTheDocument();
// Clear search button
const buttons = screen.getAllByRole('button');
const clearBtn = buttons.find((b) => b.querySelector('svg') && b !== buttons[0]);
if (clearBtn) await user.click(clearBtn);
expect(searchInput).toHaveValue('');
// Escape closes
fireEvent.keyDown(document, { key: 'Escape' });
expect(screen.queryByPlaceholderText('Search country name or code...')).not.toBeInTheDocument();
// Reopen and click outside closes
await user.click(screen.getByRole('button'));
expect(screen.getByPlaceholderText('Search country name or code...')).toBeInTheDocument();
fireEvent.mouseDown(screen.getByTestId('outside'));
expect(screen.queryByPlaceholderText('Search country name or code...')).not.toBeInTheDocument();
});
it('does not open when disabled and supports showDialCode=false', async () => {
const user = userEvent.setup();
const { rerender } = render();
await user.click(screen.getByRole('button'));
expect(screen.queryByPlaceholderText('Search country name or code...')).not.toBeInTheDocument();
rerender();
expect(screen.getByRole('button')).not.toHaveTextContent('+91');
});
});