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', () => {
62
62
describe ( 'debounce' , ( ) => {
63
63
jest . useFakeTimers ( )
64
64
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 ( )
72
66
73
67
test ( 'execute just once' , ( ) => {
68
+ const debouncedFunc = debounce ( func , 1000 )
74
69
for ( let i = 0 ; i < 100 ; i += 1 ) {
75
70
debouncedFunc ( )
76
71
}
77
72
78
- // Fast-forward time
73
+ expect ( func ) . not . toHaveBeenCalled ( )
74
+
79
75
jest . runAllTimers ( )
80
76
81
77
expect ( func ) . toBeCalledTimes ( 1 )
82
78
} )
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
+ } )
83
109
} )
Original file line number Diff line number Diff line change @@ -22,7 +22,7 @@ const debounce = <T, A extends any[]>(
22
22
23
23
if ( immediate && ! timeout ) {
24
24
/**
25
- * there's not need to clear the timeout
25
+ * there's no need to clear the timeout
26
26
* since we expect it to resolve and set `timeout = null`
27
27
*/
28
28
func . apply ( this , args )
@@ -38,9 +38,11 @@ const debounce = <T, A extends any[]>(
38
38
}
39
39
40
40
debounced . cancel = ( ) => {
41
+ /* c8 ignore start */
41
42
if ( ! timeout ) {
42
43
return
43
44
}
45
+ /* c8 ignore end */
44
46
clearTimeout ( timeout )
45
47
timeout = null
46
48
}
You can’t perform that action at this time.
0 commit comments