Skip to content

Commit

Permalink
test: add unit tests for ComboBox component
Browse files Browse the repository at this point in the history
  • Loading branch information
AlanFnz committed Dec 27, 2024
1 parent bc3a36c commit 3e26993
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
57 changes: 57 additions & 0 deletions src/components/experimental/ComboBox/ComboBox.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { ComboBox } from './ComboBox';
import { ListBoxItem } from '../ListBox/ListBox';

const mockItems = [
{ id: '1', name: 'Luke Skywalker' },
{ id: '2', name: 'Darth Vader' },
{ id: '3', name: 'Leia Organa' }
];

describe('ComboBox', () => {
it('renders with label and placeholder', () => {
render(
<ComboBox label="Star Wars Character" placeholder="Select a character" items={mockItems}>
{item => <ListBoxItem>{item.name}</ListBoxItem>}
</ComboBox>
);

expect(screen.getByText('Star Wars Character')).toBeInTheDocument();
expect(screen.getByPlaceholderText('Select a character')).toBeInTheDocument();
});

it('opens dropdown on type', async () => {
render(
<ComboBox label="Star Wars Character" items={mockItems}>
{item => <ListBoxItem>{item.name}</ListBoxItem>}
</ComboBox>
);

const input = screen.getByRole('combobox');
fireEvent.click(input);
fireEvent.change(input, { target: { value: 'Luke' } });

await waitFor(() => {
expect(screen.getByText('Luke Skywalker')).toBeInTheDocument();
expect(screen.getByText('Darth Vader')).toBeInTheDocument();
expect(screen.getByText('Leia Organa')).toBeInTheDocument();
});
});

it('calls onSelectionChange when an item is selected', async () => {
const onSelectionChange = jest.fn();
render(
<ComboBox label="Star Wars Character" items={mockItems} onSelectionChange={onSelectionChange}>
{item => <ListBoxItem>{item.name}</ListBoxItem>}
</ComboBox>
);

const input = screen.getByRole('combobox');
fireEvent.click(input);
fireEvent.change(input, { target: { value: 'Luke' } });
fireEvent.click(screen.getByText('Luke Skywalker'));

await waitFor(() => expect(onSelectionChange).toHaveBeenCalledWith('1'));
});
});
2 changes: 1 addition & 1 deletion src/components/experimental/ComboBox/ComboBox.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { forwardRef, ReactElement, Ref, RefObject, useState } from 'react';
import React, { forwardRef, ReactElement, Ref, useState } from 'react';
import {
ComboBox as BaseComboBox,
ComboBoxProps as BaseComboBoxProps,
Expand Down

0 comments on commit 3e26993

Please sign in to comment.