Skip to content

Commit

Permalink
test(SelectSingle): updated to use a controller wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
shindigira committed Apr 2, 2024
1 parent df067d4 commit 1b06f5e
Showing 1 changed file with 35 additions and 22 deletions.
57 changes: 35 additions & 22 deletions src/components/Select/Select.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,48 @@ import { jest } from '@storybook/jest';
import '@testing-library/jest-dom';
import { act, render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Select } from './Select';
import { useState } from 'react';
import { Select, SelectOption } from './Select';
import { MultipleSelectOptions, SingleSelectOptions } from './testUtils';

const SingleSelectWrapper = (): JSX.Element => {
const [selectedValue, setSelectedValue] = useState<string>(
SingleSelectOptions[0].value
);

const onHandleChange = (
newValue: SelectOption | SelectOption[] | undefined
): void => {
// Just to resolve TypeScript since we are using Select in single format
if (Array.isArray(newValue)) return;
setSelectedValue(newValue?.value ?? '');
};

return (
<Select
id='single'
options={SingleSelectOptions}
onChange={onHandleChange}
value={selectedValue}
/>
);
};

describe('<SelectSingle />', () => {
it('renders Single select with default value', () => {
render(<Select id='single' options={SingleSelectOptions} />);
expect(screen.getByRole('combobox')).toHaveValue('option1');
expect(screen.getByRole('option', { name: 'Option 1' }).selected).toBe(
true
);
// render(<Select id='single' options={SingleSelectOptions} />);
render(<SingleSelectWrapper />);

const selectElement = screen.getByRole('combobox');
expect(selectElement).toHaveValue('option1');
});

it('Handles Single selection change', async () => {
const user = userEvent.setup();
const onChange = jest.fn();

render(
<Select
id='single-change'
label='Single Select'
options={SingleSelectOptions}
defaultValue='option1'
onChange={onChange}
/>
);
render(<SingleSelectWrapper />);
const selectElement = screen.getByRole('combobox');

await user.selectOptions(screen.getByRole('combobox'), 'option3');
await userEvent.selectOptions(selectElement, 'option3');
expect(screen.getByRole('combobox')).toHaveValue('option3');
expect(onChange).toHaveBeenCalledWith(SingleSelectOptions[2]);
});
});

Expand Down Expand Up @@ -73,8 +86,8 @@ describe('<SelectMulti />', () => {

// Change handler is called with the expected content
expect(onChange).toHaveBeenCalledWith([
{ ...MultipleSelectOptions[0], selected: true },
{ ...MultipleSelectOptions[3], selected: true }
{ ...MultipleSelectOptions[1], selected: true },
{ ...MultipleSelectOptions[4], selected: true }
]);

// Tags are rendered for the selected options
Expand Down

0 comments on commit 1b06f5e

Please sign in to comment.