import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Select } from './Select';
describe('Select', () => {
const options = [
{ value: 'foo', label: 'Foo' },
{ value: 'bar', label: 'Bar' },
{ value: 'baz', label: 'Baz', disabled: true }
];
it('renders correctly', () => {
const { container } = render(
);
expect(container.innerHTML).toEqual(
'
'
);
});
it('expands when clicked', async () => {
const { container } = render(
);
const button = screen.getByRole('button', { name: /Sort by/ });
await userEvent.click(button);
expect(container.innerHTML).toEqual(
''
);
});
it('does not expand on click when disabled', async () => {
const { container } = render(
);
const button = screen.getByRole('button', { name: /Sort by/ });
await userEvent.click(button);
expect(container.innerHTML).toEqual(
''
);
});
it('calls onChange when selecting an option', async () => {
const onChange = jest.fn();
render(
);
const button = screen.getByRole('button', { name: /Sort by/ });
await userEvent.click(button);
const option = screen.getByRole('option', { name: 'Bar' });
await userEvent.click(option);
expect(onChange).toHaveBeenCalledWith('bar');
});
it('does not call onChange when selecting a disabled option', async () => {
const onChange = jest.fn();
render(
);
const button = screen.getByRole('button', { name: /Sort by/ });
await userEvent.click(button);
const option = screen.getByRole('option', { name: 'Baz' });
await userEvent.click(option);
expect(onChange).not.toHaveBeenCalled();
});
it('renders correctly with ":" between label and value if value is not undefined', async () => {
const { container } = render(
);
const button = screen.getByRole('button', { name: /Sort by/ });
await userEvent.click(button);
const option = screen.getByRole('option', { name: 'Bar' });
await userEvent.click(option);
expect(container.innerHTML).toEqual(
''
);
});
it('closes dropdown and returns focus to button when Escape is pressed', async () => {
render();
const button = screen.getByRole('button', { name: /Sort by/ });
await userEvent.click(button);
expect(button).toHaveAttribute('aria-expanded', 'true');
expect(screen.getByRole('listbox')).toBeInTheDocument();
await userEvent.keyboard('{Escape}');
expect(button).toHaveAttribute('aria-expanded', 'false');
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
expect(button).toHaveFocus();
});
it('renders correctly when there is no label', async () => {
const { container } = render();
const button = screen.getByRole('button', { name: 'Select an option' });
await userEvent.click(button);
const option = screen.getByRole('option', { name: 'Bar' });
await userEvent.click(option);
expect(container.innerHTML).toEqual(
''
);
});
});