Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions country-explorer/src/components/CountryCard.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import type { Country } from '../types/country';
import { mockCountries } from '../test/fixtures';
import CountryCard from './CountryCard';

const [country] = mockCountries;

const emptyCountry: Country = {
code: 'XXX',
name: '',
capital: '',
region: '',
subregion: '',
population: null,
area: null,
flagUrl: '',
currencies: [],
languages: [],
};

function renderCard(overrides: Partial<Country> = {}) {
return render(
<CountryCard
country={{ ...country, ...overrides }}
isFavorite={false}
onToggleFavorite={vi.fn()}
/>,
);
}

describe('CountryCard', () => {
it('renders the country name', () => {
renderCard();

expect(screen.getByRole('heading', { name: country.name })).toBeInTheDocument();
});

it('renders the flag with its alt text', () => {
renderCard();

const flag = screen.getByRole('img', { name: `Flag of ${country.name}` });
expect(flag).toHaveAttribute('src', country.flagUrl);
});

it('shows a placeholder when the flag URL is missing', () => {
render(<CountryCard country={emptyCountry} isFavorite={false} onToggleFavorite={vi.fn()} />);

expect(screen.queryByRole('img')).not.toBeInTheDocument();
expect(screen.getByText('Flag not available')).toBeInTheDocument();
});

it('renders capital, region and population', () => {
renderCard();

expect(screen.getByText(country.capital)).toBeInTheDocument();
expect(screen.getByText(country.region)).toBeInTheDocument();
expect(screen.getByText('5,379,475')).toBeInTheDocument();
});

it('formats population and area with thousands separators', () => {
renderCard({ population: 1234567, area: 323802 });

expect(screen.getByText('1,234,567')).toBeInTheDocument();
expect(screen.getByText('323,802 km²')).toBeInTheDocument();
});

it('falls back to placeholders for missing optional fields without crashing', () => {
render(<CountryCard country={emptyCountry} isFavorite={false} onToggleFavorite={vi.fn()} />);

expect(screen.getByRole('heading', { name: 'Unknown country' })).toBeInTheDocument();
expect(screen.getAllByText('Not available')).toHaveLength(6);
});
});