import React from 'react'; import { render, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import type { Option } from './option'; import { Select } from './'; import { FormField } from '../FormField'; import { GrapesProvider } from '../GrapesProvider'; import { LOCALES } from '../GrapesProvider/exampleLocales'; const options: Option[] = [ { key: '1', label: 'option 1' }, { key: '2', label: 'option 2' }, ]; describe('Select', () => { describe('given some option groups', () => { const options = [ { key: '1', label: 'option 1' }, { key: 'group', label: 'Group', options: [{ key: '2', label: 'option 2' }], }, { key: '3', label: 'option 3' }, ]; it('allows user to select an option in a group', async () => { const handleSelect = vi.fn(); const Wrapper = () => { return ( ); }; render( , ); await userEvent.click(screen.getByRole('combobox', { name: /Choose/ })); await userEvent.click( await screen.findByRole('option', { name: 'option 1' }), ); // Wait for the menu to be removed await waitFor(() => expect(screen.queryByRole('option')).not.toBeInTheDocument(), ); expect(screen.getByRole('combobox', { name: /Choose/ })).toHaveValue( 'option 1', ); }); it('supports a custom render function', async () => { const renderOption = (option: Option) => `custom function ${option.label}`; render( ); }; render( , ); expect(handleFocus).not.toHaveBeenCalled(); await userEvent.click(screen.getByRole('combobox', { name: /Choose/ })); expect(handleFocus).toHaveBeenCalled(); expect(handleBlur).not.toHaveBeenCalled(); await userEvent.click( await screen.findByRole('option', { name: 'option 1' }), ); // Wait for the menu to be removed await waitFor(() => expect(screen.queryByRole('option')).not.toBeInTheDocument(), ); await userEvent.click(screen.getByRole('button', { name: 'Loose focus' })); expect(handleBlur).toHaveBeenCalled(); }); it('disables input when isDisabled is true', async () => { render( , ); expect(screen.getByRole('button', { name: 'Show options' })).toBeVisible(); }); it('sets props name, placeholder and id to the input', () => { const name = 'select'; const placeholder = 'select an option'; render( , ); await userEvent.click(screen.getByRole('combobox', { name: /Choose/ })); await userEvent.click( await screen.findByRole('option', { name: 'option 3' }), ); expect(onSelect).not.toHaveBeenCalled(); expect(screen.getByRole('combobox', { name: /Choose/ })).toHaveValue( 'option 1', ); }); }); describe('Given a search bar has search bar in dropdown enabeld', () => { it('shows a dropdown search bar and focuses it on open', async () => { const Wrapper = () => { const [selected, setSelected] = React.useState