1- import { render , cleanup } from '@testing-library/react' ;
1+ import { render , cleanup , act } from '@testing-library/react' ;
22import InfiniteScroll from '../index' ;
3+ import { MockIntersectionObserver } from './setup/intersectionObserverMock' ;
34
45describe ( 'React Infinite Scroll Component' , ( ) => {
56 const originalConsoleError = console . error ;
67
8+ beforeEach ( ( ) => {
9+ MockIntersectionObserver . instances = [ ] ;
10+ } ) ;
11+
712 afterEach ( ( ) => {
813 cleanup ( ) ;
914 console . error = originalConsoleError ;
@@ -82,6 +87,7 @@ describe('React Infinite Scroll Component', () => {
8287 expect ( setTimeoutSpy ) . toHaveBeenCalled ( ) ;
8388 expect ( onScrollMock ) . toHaveBeenCalled ( ) ;
8489 setTimeoutSpy . mockRestore ( ) ;
90+ jest . useRealTimers ( ) ;
8591 } ) ;
8692
8793 describe ( 'When missing the dataLength prop' , ( ) => {
@@ -101,7 +107,7 @@ describe('React Infinite Scroll Component', () => {
101107
102108 describe ( 'When user scrolls to the bottom' , ( ) => {
103109 it ( 'does not show loader if hasMore is false' , ( ) => {
104- const { container , queryByText } = render (
110+ const { queryByText } = render (
105111 < InfiniteScroll
106112 dataLength = { 4 }
107113 loader = { 'Loading...' }
@@ -112,17 +118,12 @@ describe('React Infinite Scroll Component', () => {
112118 < div />
113119 </ InfiniteScroll >
114120 ) ;
115-
116- const scrollEvent = new Event ( 'scroll' ) ;
117- const node = container . querySelector (
118- '.infinite-scroll-component'
119- ) as HTMLElement ;
120- node . dispatchEvent ( scrollEvent ) ;
121+ // No IO observer created, loader never shown
121122 expect ( queryByText ( 'Loading...' ) ) . toBeFalsy ( ) ;
122123 } ) ;
123124
124- it ( 'shows loader if hasMore is true' , ( ) => {
125- const { container , getByText } = render (
125+ it ( 'shows loader if hasMore is true after IO fires ' , ( ) => {
126+ const { getByText } = render (
126127 < InfiniteScroll
127128 dataLength = { 4 }
128129 loader = { 'Loading...' }
@@ -135,11 +136,10 @@ describe('React Infinite Scroll Component', () => {
135136 </ InfiniteScroll >
136137 ) ;
137138
138- const scrollEvent = new Event ( 'scroll' ) ;
139- const node = container . querySelector (
140- '.infinite-scroll-component'
141- ) as HTMLElement ;
142- node . dispatchEvent ( scrollEvent ) ;
139+ act ( ( ) => {
140+ MockIntersectionObserver . instances [ 0 ] . triggerIntersect ( ) ;
141+ } ) ;
142+
143143 expect ( getByText ( 'Loading...' ) ) . toBeTruthy ( ) ;
144144 } ) ;
145145 } ) ;
0 commit comments