@@ -342,3 +342,62 @@ describe('timeoutPromise()', () => {
342342 } ) ;
343343 } ) ;
344344} ) ;
345+
346+ describe ( 'BetterSetInterval' , ( ) => {
347+ it ( 'works with normal function' , async ( ) => {
348+ const fn = jest . fn ( ) ;
349+
350+ const interval = utils . betterSetInterval ( fn , 200 ) ;
351+
352+ // 3 x 200ms + some leeway
353+ await utils . delayPromise ( 700 ) ;
354+ utils . betterClearInterval ( interval ) ;
355+
356+ // 1st call is immediate, 3 more after 1, 2 and 3 intervals
357+ expect ( fn ) . toHaveBeenCalledTimes ( 4 ) ;
358+
359+ // No more calls after clearing the interval
360+ await utils . delayPromise ( 500 ) ;
361+ expect ( fn ) . toHaveBeenCalledTimes ( 4 ) ;
362+ } ) ;
363+
364+ it ( 'works with async function' , async ( ) => {
365+ const fn = jest . fn ( ) ;
366+
367+ const interval = utils . betterSetInterval ( async ( ) => {
368+ fn ( ) ;
369+ await utils . delayPromise ( 100 ) ;
370+ } , 200 ) ;
371+
372+ // 3 x (200 + 100)ms + some leeway
373+ await utils . delayPromise ( 1000 ) ;
374+ utils . betterClearInterval ( interval ) ;
375+
376+ // 1st call is immediate, 3 more after 1, 2 and 3 intervals
377+ expect ( fn ) . toHaveBeenCalledTimes ( 4 ) ;
378+
379+ // No more calls after clearing the interval
380+ await utils . delayPromise ( 500 ) ;
381+ expect ( fn ) . toHaveBeenCalledTimes ( 4 ) ;
382+ } ) ;
383+
384+ it ( 'works with function that accepts a callback (legacy)' , async ( ) => {
385+ const fn = jest . fn ( ) ;
386+
387+ const interval = utils . betterSetInterval ( ( cb : ( ) => void ) => {
388+ fn ( ) ;
389+ cb ( ) ;
390+ } , 200 ) ;
391+
392+ // 3 x 200ms + some leeway
393+ await utils . delayPromise ( 700 ) ;
394+ utils . betterClearInterval ( interval ) ;
395+
396+ // 1st call is immediate, 3 more after 1, 2 and 3 intervals
397+ expect ( fn ) . toHaveBeenCalledTimes ( 4 ) ;
398+
399+ // No more calls after clearing the interval
400+ await utils . delayPromise ( 500 ) ;
401+ expect ( fn ) . toHaveBeenCalledTimes ( 4 ) ;
402+ } ) ;
403+ } ) ;
0 commit comments