1- import { render , fireEvent } from '@testing-library/react' ;
1+ import { render , fireEvent , act } from '@testing-library/react' ;
22import Select from '../index' ;
33
44const { Option, OptGroup } = Select ;
@@ -7,6 +7,14 @@ const { Option, OptGroup } = Select;
77const getOptions = ( ) => document . querySelectorAll ( '.ty-select-option' ) ;
88
99describe ( '<Select />' , ( ) => {
10+ beforeEach ( ( ) => {
11+ jest . useFakeTimers ( ) ;
12+ } ) ;
13+
14+ afterEach ( ( ) => {
15+ jest . useRealTimers ( ) ;
16+ } ) ;
17+
1018 it ( 'should match the snapshot' , ( ) => {
1119 const { asFragment } = render (
1220 < Select >
@@ -349,6 +357,55 @@ describe('<Select />', () => {
349357 expect ( onSelect ) . toHaveBeenCalledWith ( 'a' ) ;
350358 } ) ;
351359
360+ // scrollToSelected
361+ it ( 'should set scrollTop when dropdown opens with a selected value' , ( ) => {
362+ const options = Array . from ( { length : 50 } , ( _ , i ) => ( {
363+ value : `opt-${ i } ` ,
364+ label : `Option ${ i } ` ,
365+ } ) ) ;
366+
367+ const { container } = render ( < Select options = { options } defaultValue = "opt-40" /> ) ;
368+ const selector = container . querySelector ( '.ty-select__selector' ) as HTMLElement ;
369+
370+ // Mock offsetTop on selected option before opening
371+ const origDescriptor = Object . getOwnPropertyDescriptor ( HTMLElement . prototype , 'offsetTop' ) ;
372+ Object . defineProperty ( HTMLElement . prototype , 'offsetTop' , {
373+ configurable : true ,
374+ get ( ) {
375+ if ( this . getAttribute ?.( 'aria-selected' ) === 'true' ) return 400 ;
376+ return 0 ;
377+ } ,
378+ } ) ;
379+
380+ fireEvent . click ( selector ) ;
381+ jest . runAllTimers ( ) ;
382+
383+ const dropdown = document . querySelector ( '.ty-select__dropdown' ) as HTMLElement ;
384+ expect ( dropdown . scrollTop ) . toBe ( 400 ) ;
385+
386+ if ( origDescriptor ) {
387+ Object . defineProperty ( HTMLElement . prototype , 'offsetTop' , origDescriptor ) ;
388+ }
389+ } ) ;
390+
391+ it ( 'should not scroll when scrollToSelected is false' , ( ) => {
392+ const options = Array . from ( { length : 50 } , ( _ , i ) => ( {
393+ value : `opt-${ i } ` ,
394+ label : `Option ${ i } ` ,
395+ } ) ) ;
396+
397+ const { container } = render (
398+ < Select options = { options } defaultValue = "opt-40" scrollToSelected = { false } />
399+ ) ;
400+ const selector = container . querySelector ( '.ty-select__selector' ) as HTMLElement ;
401+ fireEvent . click ( selector ) ;
402+
403+ jest . runAllTimers ( ) ;
404+
405+ const dropdown = document . querySelector ( '.ty-select__dropdown' ) as HTMLElement ;
406+ expect ( dropdown . scrollTop ) . toBe ( 0 ) ;
407+ } ) ;
408+
352409 // Custom filter function
353410 it ( 'should support custom filterOption function' , ( ) => {
354411 const { container } = render (
0 commit comments