Created
June 9, 2018 20:14
-
-
Save deptno/bc486be03daf04e5f29984e200515030 to your computer and use it in GitHub Desktop.
throttle-does-not-guarantee-latest-call
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
import {throttle, debounce} from 'lodash' | |
const delay = () => new Promise(r => setTimeout(r, 100)) | |
describe('throttle vs debouce', () => { | |
beforeEach(() => { | |
console.log = jest.fn() | |
}) | |
it('throttle does not guarantee about execute latest call', async (done) => { | |
const i = throttle(x => console.log(x), 300) | |
let count = 0 | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
await delay() | |
expect(count).toEqual(10) | |
expect(console.log).not.toHaveBeenLastCalledWith(10) | |
done() | |
}) | |
it('debounce guarantee about execute latest call', async (done) => { | |
const i = debounce(x => console.log(x), 200) | |
let count = 0 | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
i(++count) | |
await delay() | |
await delay() | |
await delay() | |
expect(count).toEqual(9) | |
// expect(console.log).toHaveBeenCalledTimes(1) | |
expect(console.log).toHaveBeenLastCalledWith(9) | |
done() | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment