|
| 1 | +import { render, fireEvent, waitFor } from '@testing-library/react' |
| 2 | +import ScrollToTop from 'components/ScrollToTop' |
| 3 | + |
| 4 | +describe('ScrollToTop component test', () => { |
| 5 | + beforeEach(() => { |
| 6 | + window.scrollTo = jest.fn() |
| 7 | + Object.defineProperty(window, 'scrollY', { value: 0, writable: true }) |
| 8 | + Object.defineProperty(window, 'innerHeight', { value: 1000, writable: true }) |
| 9 | + }) |
| 10 | + |
| 11 | + afterEach(() => { |
| 12 | + jest.clearAllMocks() |
| 13 | + }) |
| 14 | + |
| 15 | + test('Initially, the button should be hidden', () => { |
| 16 | + const { getByLabelText } = render(<ScrollToTop />) |
| 17 | + const button = getByLabelText(/scroll to top/i) |
| 18 | + |
| 19 | + expect(button).toHaveClass('opacity-0') |
| 20 | + expect(button).toHaveClass('pointer-events-none') |
| 21 | + }) |
| 22 | + |
| 23 | + test('The button should become visible after scrolling past the threshold', async () => { |
| 24 | + const { getByLabelText } = render(<ScrollToTop />) |
| 25 | + const button = getByLabelText(/scroll to top/i) |
| 26 | + |
| 27 | + Object.defineProperty(window, 'scrollY', { value: 400, writable: true }) |
| 28 | + window.dispatchEvent(new Event('scroll')) |
| 29 | + |
| 30 | + await waitFor(() => { |
| 31 | + expect(button).toHaveClass('opacity-100') |
| 32 | + expect(button).toHaveClass('pointer-events-auto') |
| 33 | + }) |
| 34 | + }) |
| 35 | + |
| 36 | + test('Clicking the button should call window.scrollTo with smooth behavior', async () => { |
| 37 | + const { getByLabelText } = render(<ScrollToTop />) |
| 38 | + const button = getByLabelText(/scroll to top/i) |
| 39 | + |
| 40 | + Object.defineProperty(window, 'scrollY', { value: 400, writable: true }) |
| 41 | + window.dispatchEvent(new Event('scroll')) |
| 42 | + |
| 43 | + await waitFor(() => { |
| 44 | + expect(button).toHaveClass('opacity-100') |
| 45 | + }) |
| 46 | + |
| 47 | + fireEvent.click(button) |
| 48 | + expect(window.scrollTo).toHaveBeenCalledWith({ top: 0, behavior: 'smooth' }) |
| 49 | + }) |
| 50 | +}) |
0 commit comments