import { describe, expect, it, vi } from 'vitest'; import { render, screen } from '@testing-library/svelte'; import userEvent from '@testing-library/user-event'; import PreventHandler from './prevent-handler.spec.svelte'; describe('preventHandler', () => { it('Emits the click event', async () => { const onClick = vi.fn(); render(PreventHandler, { events: { click: onClick } }); const button = screen.getByRole('button', { name: /prevented/iu }); await userEvent.click(button); expect(onClick).toHaveBeenCalledOnce(); }); it('Does not emit the change event when prevent is true', async () => { const onClick = vi.fn(); render(PreventHandler, { props: { prevent: true }, events: { click: onClick }, }); const button = screen.getByRole('button', { name: /prevented/iu }); await userEvent.click(button); expect(onClick).toHaveBeenCalledTimes(0); }); it('Emits the click event if prevent is false', async () => { const onClick = vi.fn(); render(PreventHandler, { props: { prevent: false }, events: { click: onClick }, }); const button = screen.getByRole('button', { name: /prevented/iu }); await userEvent.click(button); expect(onClick).toHaveBeenCalledOnce(); }); it('Emits the keydown event', async () => { const onKeydown = vi.fn(); render(PreventHandler, { events: { keydown: onKeydown } }); const button = screen.getByRole('button', { name: /prevented/iu, }); button.focus(); await userEvent.keyboard('[Enter]'); expect(onKeydown).toHaveBeenCalledOnce(); }); it('Does not emit the keydown event when prevent is true', async () => { const onKeydown = vi.fn(); render(PreventHandler, { props: { prevent: true }, events: { keydown: onKeydown }, }); const button = screen.getByRole('button', { name: /prevented/iu, }); button.focus(); await userEvent.keyboard('[Enter]'); expect(onKeydown).toHaveBeenCalledTimes(0); }); it('Emits the keydown event if the prevent was toggled', async () => { const onKeydown = vi.fn(); render(PreventHandler, { props: { prevent: false }, events: { keydown: onKeydown }, }); const button = screen.getByRole('button', { name: /prevented/iu, }); button.focus(); await userEvent.keyboard('[Enter]'); expect(onKeydown).toHaveBeenCalledOnce(); }); it('Emit the keydown event when prevent is true if code is tab', async () => { const onKeydown = vi.fn(); render(PreventHandler, { events: { keydown: onKeydown } }); const button = screen.getByRole('button', { name: /prevented/iu, }); button.focus(); await userEvent.keyboard('[Tab]'); expect(onKeydown).toHaveBeenCalledOnce(); }); it('Emits the keydown event when prevent is true if code is in allowedCodes', async () => { const onKeydown = vi.fn(); render(PreventHandler, { props: { prevent: true, allowedCodes: ['Space'] }, events: { keydown: onKeydown }, }); const button = screen.getByRole('button', { name: /prevented/iu, }); button.focus(); await userEvent.keyboard('[Space]'); expect(onKeydown).toHaveBeenCalledOnce(); }); });