|
| 1 | +import { render, screen, fireEvent } from '@testing-library/react'; |
| 2 | +import { Button } from './index'; |
| 3 | + |
| 4 | +describe('Button', () => { |
| 5 | + const onClickMock = jest.fn(); |
| 6 | + const defaultProps = { |
| 7 | + label: 'Button', |
| 8 | + onClick: onClickMock, |
| 9 | + }; |
| 10 | + it('renders without errors and matches snapshot', () => { |
| 11 | + const { |
| 12 | + container: { firstChild }, |
| 13 | + } = render(<Button {...defaultProps} />); |
| 14 | + |
| 15 | + expect(firstChild).toMatchSnapshot(); |
| 16 | + }); |
| 17 | + |
| 18 | + it('should display label', () => { |
| 19 | + render(<Button {...defaultProps} />); |
| 20 | + screen.getByText('Button'); |
| 21 | + }); |
| 22 | + |
| 23 | + it('should handle click events', () => { |
| 24 | + const onClickMock = jest.fn(); |
| 25 | + const { |
| 26 | + container: { firstChild }, |
| 27 | + } = render(<Button {...defaultProps} onClick={onClickMock} />); |
| 28 | + |
| 29 | + firstChild && fireEvent.click(firstChild); |
| 30 | + |
| 31 | + expect(onClickMock).toBeCalled(); |
| 32 | + }); |
| 33 | + |
| 34 | + describe('Disabled Button', () => { |
| 35 | + test('should display text', () => { |
| 36 | + render(<Button {...defaultProps} disabled={true} />); |
| 37 | + screen.getByText('Button'); |
| 38 | + }); |
| 39 | + |
| 40 | + it('should be disabled', () => { |
| 41 | + const { |
| 42 | + container: { firstChild }, |
| 43 | + } = render(<Button {...defaultProps} disabled={true} />); |
| 44 | + |
| 45 | + expect(firstChild).toHaveAttribute('disabled'); |
| 46 | + }); |
| 47 | + |
| 48 | + it('should not handle click events', () => { |
| 49 | + const { |
| 50 | + container: { firstChild }, |
| 51 | + } = render(<Button {...defaultProps} disabled />); |
| 52 | + |
| 53 | + firstChild && fireEvent.click(firstChild); |
| 54 | + |
| 55 | + expect(onClickMock).not.toBeCalled(); |
| 56 | + }); |
| 57 | + }); |
| 58 | + |
| 59 | + it('should play sound on click', () => { |
| 60 | + const sound = new Audio() as HTMLAudioElement; |
| 61 | + const playMock = jest.fn(); |
| 62 | + Object.defineProperty(global.window.HTMLMediaElement.prototype, 'play', { |
| 63 | + configurable: true, |
| 64 | + get() { |
| 65 | + return playMock; |
| 66 | + }, |
| 67 | + }); |
| 68 | + const { |
| 69 | + container: { firstChild }, |
| 70 | + } = render(<Button {...defaultProps} buttonSound={sound} />); |
| 71 | + |
| 72 | + firstChild && fireEvent.click(firstChild); |
| 73 | + |
| 74 | + expect(playMock).toBeCalled(); |
| 75 | + }); |
| 76 | +}); |
0 commit comments