import sinon from 'sinon' ; import { throttle } from '../src/utils' ; describe ( 'src/utils.ts - throttle' , ( ) => { let clock ; beforeEach ( ( ) => { clock = sinon . useFakeTimers ( new Date ( ) ) ; } ) ; afterEach ( ( ) => { clock . restore ( ) ; } ) ; it ( 'should throttle' , ( ) => { const func = jest . fn ( ) ; const throttledFunc = throttle ( func , 1000 ) ; throttledFunc ( ) ; throttledFunc . cancel ( ) ; expect ( func ) . toHaveBeenCalledTimes ( 1 ) ; for ( let i = 0 ; i < 20 ; i ++ ) { clock . tick ( 100 ) ; throttledFunc ( ) ; } expect ( func ) . toHaveBeenCalledTimes ( 3 ) ; clock . tick ( 2500 ) ; expect ( func ) . toHaveBeenCalledTimes ( 4 ) ; throttledFunc ( ) ; clock . tick ( 100 ) ; throttledFunc ( ) ; throttledFunc . cancel ( ) ; clock . tick ( 1500 ) ; expect ( func ) . toHaveBeenCalledTimes ( 5 ) ; } ) ; } ) ;