import React from 'react'; import { render, screen, waitForElementToBeRemoved, } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { type CountryCode, getCountryCallingCode } from 'libphonenumber-js'; import { PhoneInput } from './'; import { COUNTRIES } from './stories/country'; const SUBSET_COUNTRIES = ['US', 'FR', 'UK'].map((key) => ({ key, label: COUNTRIES[key], })); describe('PhoneInput component', () => { it('allows user to enter a phone number value', async () => { const Wrapper = () => { const [value, setValue] = React.useState(null); const handleChange = (newValue: string) => { setValue(newValue); }; return ( value ? value.replace(`+33 `, '') : '' } /> ); }; render(); expect(screen.getByAltText(`FR-flag`)).toBeVisible(); await userEvent.type(screen.getByRole('textbox'), '622222222'); expect(screen.getByRole('textbox')).toHaveValue('622222222'); }); it('allows user to select a country', async () => { const Wrapper = () => { const [value, setValue] = React.useState(null); const [country, setCountry] = React.useState('FR'); const handleChange = (newValue: string) => { setValue(newValue); }; return ( { setCountry(selectedCountry.key); }} formatPhoneNumber={vi.fn()} /> ); }; render(); // Open menu await userEvent.click(screen.getByRole('combobox')); await userEvent.click( await screen.findByRole('option', { name: COUNTRIES['US'] }), ); await waitForElementToBeRemoved(screen.getByText(COUNTRIES['US'])); expect(screen.getByAltText(`US-flag`)).toBeVisible(); expect(screen.getByText(`(+${getCountryCallingCode('US')})`)).toBeVisible(); expect(screen.queryByAltText(`FR-flag`)).not.toBeInTheDocument(); }); it('supports onBlur and onFocus callback', async () => { const handleBlur = vi.fn(); const handleFocus = vi.fn(); render(

Escape focus

value ? value.replace(`+33 `, '') : '' } />
, ); expect(handleFocus).not.toHaveBeenCalled(); await userEvent.type(screen.getByRole('textbox'), '22'); expect(handleFocus).toHaveBeenCalled(); expect(handleBlur).not.toHaveBeenCalled(); await userEvent.click(screen.getByText('Escape focus')); expect(handleBlur).toHaveBeenCalled(); }); });