-
-
Notifications
You must be signed in to change notification settings - Fork 245
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
94 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
import { throttle } from '../../../src/util/throttle'; | ||
|
||
const sleep = (wait: number) => new Promise((r) => setTimeout(r, wait)); | ||
|
||
describe('throttle', () => { | ||
it('should throttle calls', async () => { | ||
const wait = 100; | ||
const fn = jest.fn(); | ||
const throttled = throttle(fn, wait); | ||
|
||
throttled('a'); | ||
sleep(wait - 5) | ||
throttled('b'); | ||
sleep(wait - 10) | ||
throttled('c'); | ||
|
||
await sleep(wait); | ||
|
||
expect(fn).toBeCalledTimes(1); | ||
expect(fn).toBeCalledWith(['c']); | ||
}); | ||
|
||
it('should execute the first call', async () => { | ||
const wait = 100; | ||
const fn = jest.fn(); | ||
const throttled = throttle(fn, wait); | ||
|
||
throttled(); | ||
|
||
await sleep(wait); | ||
|
||
expect(fn).toBeCalledTimes(1); | ||
}); | ||
|
||
it('should call at trailing edge of the timeout', async () => { | ||
const wait = 100; | ||
const fn = jest.fn(); | ||
const throttled = throttle(fn, wait); | ||
|
||
throttled(); | ||
|
||
expect(fn).toBeCalledTimes(0); | ||
|
||
await sleep(wait); | ||
|
||
expect(fn).toBeCalledTimes(1); | ||
}); | ||
|
||
it('should call after the timer', async () => { | ||
const wait = 100; | ||
const fn = jest.fn(); | ||
const throttled = throttle(fn, wait); | ||
|
||
throttled(); | ||
await sleep(wait); | ||
|
||
expect(fn).toBeCalledTimes(1); | ||
|
||
throttled(); | ||
await sleep(wait); | ||
|
||
expect(fn).toBeCalledTimes(2); | ||
|
||
throttled(); | ||
await sleep(wait); | ||
|
||
expect(fn).toBeCalledTimes(3); | ||
}); | ||
}); |