Skip to content

Commit

Permalink
fix: stopped onChange throwing undefined (#18452)
Browse files Browse the repository at this point in the history
* fix: restricted onchange calls

* fix: added new story and reverted default story

* test: added tests to check for undefined

* test removal

* chore: format fix
  • Loading branch information
Gururajj77 authored Feb 11, 2025
1 parent 9cf96c5 commit 6a145c0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
34 changes: 34 additions & 0 deletions packages/react/src/components/ComboBox/ComboBox-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,40 @@ describe('ComboBox', () => {
'cds--list-box__menu-item--highlighted'
);
});

it('should pass defined selectedItem to onChange when item is selected', async () => {
render(<ComboBox {...mockProps} />);

expect(mockProps.onChange).not.toHaveBeenCalled();

await openMenu();
await userEvent.click(screen.getAllByRole('option')[0]);

expect(mockProps.onChange).toHaveBeenCalledTimes(1);
expect(mockProps.onChange).toHaveBeenCalledWith(
expect.objectContaining({
selectedItem: expect.anything(),
})
);

const call = mockProps.onChange.mock.calls[0][0];
expect(call.selectedItem).toBeDefined();
expect(call.selectedItem).toEqual(mockProps.items[0]);
});

it('should never pass undefined as selectedItem to onChange', async () => {
render(<ComboBox {...mockProps} />);

for (let i = 0; i < mockProps.items.length; i++) {
await openMenu();
await userEvent.click(screen.getAllByRole('option')[i]);

const call = mockProps.onChange.mock.calls[i][0];
expect(call.selectedItem).toBeDefined();
expect(call.selectedItem).not.toBeUndefined();
expect(call.selectedItem).toEqual(mockProps.items[i]);
}
});
});

describe('ComboBox autocomplete', () => {
Expand Down
5 changes: 3 additions & 2 deletions packages/react/src/components/ComboBox/ComboBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -783,8 +783,9 @@ const ComboBox = forwardRef(
onChange({ selectedItem: newSelectedItem });
}
if (
type === useCombobox.stateChangeTypes.FunctionSelectItem ||
type === useCombobox.stateChangeTypes.InputKeyDownEnter
(type === useCombobox.stateChangeTypes.FunctionSelectItem ||
type === useCombobox.stateChangeTypes.InputKeyDownEnter) &&
!isEqual(selectedItemProp, newSelectedItem) // Only fire if there's an actual change
) {
onChange({ selectedItem: newSelectedItem });
}
Expand Down

0 comments on commit 6a145c0

Please sign in to comment.