Migrated TagsModeDropdown test to react testing library

This commit is contained in:
Alejandro Celaya 2022-07-07 19:01:17 +02:00
parent 28b15e4a85
commit 935b12763b

View file

@ -1,42 +1,37 @@
import { shallow, ShallowWrapper } from 'enzyme'; import { render, screen } from '@testing-library/react';
import { DropdownItem } from 'reactstrap'; import userEvent from '@testing-library/user-event';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faBars as listIcon, faThLarge as cardsIcon } from '@fortawesome/free-solid-svg-icons';
import { TagsModeDropdown } from '../../src/tags/TagsModeDropdown'; import { TagsModeDropdown } from '../../src/tags/TagsModeDropdown';
import { DropdownBtn } from '../../src/utils/DropdownBtn'; import { TagsMode } from '../../src/settings/reducers/settings';
describe('<TagsModeDropdown />', () => { describe('<TagsModeDropdown />', () => {
const onChange = jest.fn(); const onChange = jest.fn();
let wrapper: ShallowWrapper; const setUp = (mode: TagsMode) => ({
user: userEvent.setup(),
beforeEach(() => { ...render(<TagsModeDropdown mode={mode} onChange={onChange} />),
wrapper = shallow(<TagsModeDropdown mode="list" onChange={onChange} />);
}); });
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);
afterEach(() => wrapper?.unmount());
it('renders expected items', () => { it.each([
const btn = wrapper.find(DropdownBtn); ['cards' as TagsMode],
const items = wrapper.find(DropdownItem); ['list' as TagsMode],
const icons = wrapper.find(FontAwesomeIcon); ])('renders expected initial value', (mode) => {
setUp(mode);
expect(btn).toHaveLength(1); expect(screen.getByRole('button')).toHaveTextContent(`Display mode: ${mode}`);
expect(btn.prop('text')).toEqual('Display mode: list');
expect(items).toHaveLength(2);
expect(icons).toHaveLength(2);
expect(icons.first().prop('icon')).toEqual(cardsIcon);
expect(icons.last().prop('icon')).toEqual(listIcon);
}); });
it('changes active element on click', () => { it('changes active element on click', async () => {
const items = wrapper.find(DropdownItem); const { user } = setUp('list');
const clickItem = async (index: 0 | 1) => {
await user.click(screen.getByRole('button'));
await user.click(screen.getAllByRole('menuitem')[index]);
};
expect(onChange).not.toHaveBeenCalled(); expect(onChange).not.toHaveBeenCalled();
items.first().simulate('click'); await clickItem(0);
expect(onChange).toHaveBeenCalledWith('cards'); expect(onChange).toHaveBeenCalledWith('cards');
items.last().simulate('click'); await clickItem(1);
expect(onChange).toHaveBeenCalledWith('list'); expect(onChange).toHaveBeenCalledWith('list');
}); });
}); });