import * as React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { Switch } from '../Switch'; const props = { onChange: jest.fn(), isChecked: false }; describe('Switch', () => { test('switch label for attribute equals input id attribute', () => { render(); const switchElement = screen.getByLabelText('Switch label'); expect(switchElement).toHaveAttribute('id', 'foo'); expect(switchElement.parentElement).toHaveAttribute('for', 'foo'); }); test('switch label id is auto generated', () => { render(); expect(screen.getByLabelText('Switch label')).toHaveAttribute('id'); }); test('switch is checked', () => { const { asFragment } = render( ); expect(asFragment()).toMatchSnapshot(); }); test('switch is not checked', () => { const { asFragment } = render( ); expect(asFragment()).toMatchSnapshot(); }); test('switch with only label is checked', () => { const { asFragment } = render(); expect(asFragment()).toMatchSnapshot(); }); test('switch with only label is not checked', () => { const { asFragment } = render(); expect(asFragment()).toMatchSnapshot(); }); test('no label switch is checked', () => { const { asFragment } = render(); expect(asFragment()).toMatchSnapshot(); }); test('no label switch is not checked', () => { const { asFragment } = render( ); expect(asFragment()).toMatchSnapshot(); }); test('switch is checked and disabled', () => { const { asFragment } = render( ); expect(asFragment()).toMatchSnapshot(); }); test('switch is not checked and disabled', () => { const { asFragment } = render( ); expect(asFragment()).toMatchSnapshot(); }); test('switch passes value and event to onChange handler', async () => { const user = userEvent.setup(); render(); await user.click(screen.getByLabelText('Switch label')); expect(props.onChange).toHaveBeenCalledWith(expect.any(Object), true); }); test('should throw console error when no aria-label or label is given', () => { const myMock = jest.fn(); global.console = { ...global.console, error: myMock }; render(); expect(myMock).toHaveBeenCalled(); }); test('should not throw console error when label is given but no aria-label', () => { const myMock = jest.fn(); global.console = { ...global.console, error: myMock }; render(); expect(myMock).not.toHaveBeenCalled(); }); test('should not throw console error when aria-label is given but no label', () => { const myMock = jest.fn(); global.console = { ...global.console, error: myMock }; render(); expect(myMock).not.toHaveBeenCalled(); }); test('should apply reversed modifier', () => { render(); expect(screen.getByLabelText('Switch label').parentElement).toHaveClass('pf-m-reverse'); }); });