|
| 1 | +import React from 'react'; |
| 2 | +import { render, fireEvent } from '@testing-library/react'; |
| 3 | +import Mentions, { UnstableContext } from '../src'; |
| 4 | +import { expectMeasuring } from './util'; |
| 5 | + |
| 6 | +describe('DropdownMenu', () => { |
| 7 | + // Generate 20 options for testing scrolling behavior |
| 8 | + const generateOptions = Array.from({ length: 20 }).map((_, index) => ({ |
| 9 | + value: `item-${index}`, |
| 10 | + label: `item-${index}`, |
| 11 | + })); |
| 12 | + |
| 13 | + // Setup component with UnstableContext for testing dropdown behavior |
| 14 | + const { container } = render( |
| 15 | + <UnstableContext.Provider value={{ open: true }}> |
| 16 | + <Mentions defaultValue="@" options={generateOptions} /> |
| 17 | + </UnstableContext.Provider>, |
| 18 | + ); |
| 19 | + |
| 20 | + it('should scroll into view when navigating with keyboard', () => { |
| 21 | + // Mock scrollIntoView since it's not implemented in JSDOM |
| 22 | + const scrollIntoViewMock = jest |
| 23 | + .spyOn(HTMLElement.prototype, 'scrollIntoView') |
| 24 | + .mockImplementation(jest.fn()); |
| 25 | + |
| 26 | + // Press ArrowDown multiple times to make options overflow the visible area |
| 27 | + for (let i = 0; i < 10; i++) { |
| 28 | + fireEvent.keyDown(document.activeElement!, { key: 'ArrowDown' }); |
| 29 | + } |
| 30 | + |
| 31 | + // Verify if scrollIntoView was called |
| 32 | + expect(scrollIntoViewMock).toHaveBeenCalledWith({ |
| 33 | + block: 'nearest', |
| 34 | + inline: 'nearest', |
| 35 | + }); |
| 36 | + |
| 37 | + // Press ArrowUp to verify scrolling up |
| 38 | + for (let i = 0; i < 5; i++) { |
| 39 | + fireEvent.keyDown(document.activeElement!, { key: 'ArrowUp' }); |
| 40 | + } |
| 41 | + |
| 42 | + // Verify if scrollIntoView was called again |
| 43 | + expect(scrollIntoViewMock).toHaveBeenCalledWith({ |
| 44 | + block: 'nearest', |
| 45 | + inline: 'nearest', |
| 46 | + }); |
| 47 | + |
| 48 | + expectMeasuring(container); |
| 49 | + |
| 50 | + scrollIntoViewMock.mockRestore(); |
| 51 | + }); |
| 52 | +}); |
0 commit comments