|
| 1 | +import { fireEvent, render, screen } from '@testing-library/react'; |
| 2 | +import React from 'react'; |
| 3 | +import Dropdown from '..'; |
| 4 | +import type { DropdownItem } from '../../../../types'; |
| 5 | + |
| 6 | +describe('Dropdown component', () => { |
| 7 | + const items: DropdownItem[] = [ |
| 8 | + { label: 'item1', title: 'Item 1', active: false, onClick: jest.fn() }, |
| 9 | + { label: 'item2', title: 'Item 2', active: true, onClick: jest.fn() }, |
| 10 | + { label: 'item3', title: 'Item 3', active: false, onClick: jest.fn() }, |
| 11 | + ]; |
| 12 | + |
| 13 | + it('should render the items and apply active styles', () => { |
| 14 | + render(<Dropdown items={items} shouldShow={true} styles={{}} />); |
| 15 | + |
| 16 | + items.forEach(item => { |
| 17 | + const button = screen.getByText(item.title); |
| 18 | + expect(button).toBeInTheDocument(); |
| 19 | + |
| 20 | + if (item.active) { |
| 21 | + expect(button).toHaveStyle('font-weight: bold'); |
| 22 | + } else { |
| 23 | + expect(button).not.toHaveStyle('font-weight: bold'); |
| 24 | + } |
| 25 | + }); |
| 26 | + }); |
| 27 | + |
| 28 | + it('should call the onClick function when an item is clicked', () => { |
| 29 | + render(<Dropdown items={items} shouldShow={true} styles={{}} />); |
| 30 | + const button = screen.getByText(items[2].title); |
| 31 | + fireEvent.click(button); |
| 32 | + expect(items[2].onClick).toHaveBeenCalledTimes(1); |
| 33 | + }); |
| 34 | + |
| 35 | + it('should call the onClick function when Enter or Space is pressed', () => { |
| 36 | + render(<Dropdown items={items} shouldShow={true} styles={{}} />); |
| 37 | + const button = screen.getByText(items[1].title); |
| 38 | + fireEvent.keyDown(button, { key: 'Enter', code: 'Enter' }); |
| 39 | + fireEvent.keyDown(button, { key: ' ', code: 'Space' }); |
| 40 | + expect(items[1].onClick).toHaveBeenCalledTimes(2); |
| 41 | + }); |
| 42 | + |
| 43 | + it('should not render the items when shouldShow prop is false', () => { |
| 44 | + render(<Dropdown items={items} shouldShow={false} styles={{}} />); |
| 45 | + items.forEach(item => { |
| 46 | + const button = screen.queryByText(item.title); |
| 47 | + expect(button).not.toBeVisible(); |
| 48 | + }); |
| 49 | + }); |
| 50 | + |
| 51 | + it('should apply styles passed in the styles prop', () => { |
| 52 | + const customStyles: React.CSSProperties = { |
| 53 | + backgroundColor: 'green', |
| 54 | + padding: '10px', |
| 55 | + borderRadius: '5px', |
| 56 | + }; |
| 57 | + render(<Dropdown items={items} shouldShow={true} styles={customStyles} />); |
| 58 | + |
| 59 | + const dropdownList = screen.getByRole('list'); |
| 60 | + expect(dropdownList).toHaveStyle('background-color: green'); |
| 61 | + expect(dropdownList).toHaveStyle('padding: 10px'); |
| 62 | + expect(dropdownList).toHaveStyle('border-radius: 5px'); |
| 63 | + }); |
| 64 | +}); |
0 commit comments