File tree Expand file tree Collapse file tree 2 files changed +37
-9
lines changed
Expand file tree Collapse file tree 2 files changed +37
-9
lines changed Original file line number Diff line number Diff line change @@ -62,22 +62,48 @@ describe('compute positions', () => {
6262describe ( 'debounce' , ( ) => {
6363 jest . useFakeTimers ( )
6464
65- let func
66- let debouncedFunc
67-
68- beforeEach ( ( timeout = 1000 ) => {
69- func = jest . fn ( )
70- debouncedFunc = debounce ( func , timeout )
71- } )
65+ const func = jest . fn ( )
7266
7367 test ( 'execute just once' , ( ) => {
68+ const debouncedFunc = debounce ( func , 1000 )
7469 for ( let i = 0 ; i < 100 ; i += 1 ) {
7570 debouncedFunc ( )
7671 }
7772
78- // Fast-forward time
73+ expect ( func ) . not . toHaveBeenCalled ( )
74+
7975 jest . runAllTimers ( )
8076
8177 expect ( func ) . toBeCalledTimes ( 1 )
8278 } )
79+
80+ test ( 'execute immediately just once' , ( ) => {
81+ const debouncedFunc = debounce ( func , 1000 , true )
82+
83+ debouncedFunc ( )
84+ expect ( func ) . toBeCalledTimes ( 1 )
85+
86+ for ( let i = 0 ; i < 100 ; i += 1 ) {
87+ debouncedFunc ( )
88+ }
89+
90+ jest . runAllTimers ( )
91+
92+ expect ( func ) . toHaveBeenCalledTimes ( 1 )
93+ } )
94+
95+ test ( 'does not execute after cancel' , ( ) => {
96+ const debouncedFunc = debounce ( func , 1000 )
97+
98+ debouncedFunc ( )
99+
100+ expect ( func ) . not . toHaveBeenCalled ( )
101+
102+ debouncedFunc . cancel ( )
103+
104+ jest . runAllTimers ( )
105+
106+ expect ( func ) . not . toHaveBeenCalled ( )
107+ } )
108+ } )
83109} )
Original file line number Diff line number Diff line change @@ -22,7 +22,7 @@ const debounce = <T, A extends any[]>(
2222
2323 if ( immediate && ! timeout ) {
2424 /**
25- * there's not need to clear the timeout
25+ * there's no need to clear the timeout
2626 * since we expect it to resolve and set `timeout = null`
2727 */
2828 func . apply ( this , args )
@@ -38,9 +38,11 @@ const debounce = <T, A extends any[]>(
3838 }
3939
4040 debounced . cancel = ( ) => {
41+ /* c8 ignore start */
4142 if ( ! timeout ) {
4243 return
4344 }
45+ /* c8 ignore end */
4446 clearTimeout ( timeout )
4547 timeout = null
4648 }
You can’t perform that action at this time.
0 commit comments