Skip to content

Commit

Permalink
Added dropdown component test
Browse files Browse the repository at this point in the history
  • Loading branch information
belousovjr committed Nov 15, 2023
1 parent bd2300b commit eb5e409
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
41 changes: 41 additions & 0 deletions src/__tests__/components/dropdown.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import React from "react";
import { fireEvent } from "@testing-library/react";
import Dropdown from "../../components/Dropdown";
import { vitest } from "vitest";
import { renderWithProvider } from "../../testHelpers";

describe("Dropdown", () => {
const items = [
{ value: 1, title: "Item 1" },
{ value: 2, title: "Item 2" },
{ value: 3, title: "Item 3" },
];
const value = 1;
const onChange = vitest.fn();

it("should render the dropdown with correct items and tabIndexes", () => {
const { getByTestId, getAllByText, getByText } = renderWithProvider(
<Dropdown items={items} value={value} onChange={onChange} />
);

const dropdownItemsList = getByTestId("dropdown-items");

const selectedItem = getAllByText(items[0].title)[1];
const nonSelectedItem = getByText(items[1].title);

expect(dropdownItemsList.children.length).toEqual(items.length);
expect(selectedItem.tabIndex).toEqual(-1);
expect(nonSelectedItem.tabIndex).not.toEqual(-1);
});

it("should call onChange function when an item is selected", () => {
const { getByText } = renderWithProvider(<Dropdown items={items} value={value} onChange={onChange} />);

const nonSelectedItem = getByText(items[1].title);

fireEvent.click(nonSelectedItem);

expect(onChange).toHaveBeenCalledTimes(1);
expect(onChange).toHaveBeenCalledWith(items[1].value);
});
});
3 changes: 2 additions & 1 deletion src/components/Dropdown/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export default function Dropdown({ items, value, onChange }: IDropdownProps) {
<ArrowDownIcon size={"16px"} />
</DropdownActivatorWrapper>

<Grid maxHeight={200} overflowY={"auto"} gridGap={"4px"} pt={"6px"}>
<Grid maxHeight={200} overflowY={"auto"} gridGap={"4px"} pt={"6px"} data-testid={"dropdown-items"}>
{items.map((item) => (
<DropdownItemWrapper
key={item.value}
Expand All @@ -70,6 +70,7 @@ export default function Dropdown({ items, value, onChange }: IDropdownProps) {
setOpened(false);
}}
active={item.value === value}
tabIndex={item.value === value ? -1 : undefined}
>
{item.title || item.value}
</DropdownItemWrapper>
Expand Down

0 comments on commit eb5e409

Please sign in to comment.