1 |
|
2 |
|
3 | import assert from 'assert';
|
4 |
|
5 | import sinon from 'sinon';
|
6 | import throttle from '../src/throttle';
|
7 |
|
8 | describe('throttle', () => {
|
9 | it("doesn't invoke a function more than once in a given interval", () => {
|
10 | let spy = sinon.spy();
|
11 | let throttled = throttle(spy, 100);
|
12 |
|
13 | throttled(1);
|
14 | throttled(2);
|
15 | throttled(3);
|
16 |
|
17 | assert(spy.calledOnceWithExactly(1));
|
18 | });
|
19 |
|
20 | it('calls the underlying function again once the interval has passed', () => {
|
21 | let time = sinon.useFakeTimers();
|
22 | let spy = sinon.spy();
|
23 | let throttled = throttle(spy, 100);
|
24 |
|
25 | throttled(1);
|
26 | throttled(2);
|
27 | throttled(3);
|
28 |
|
29 | time.tick(100);
|
30 | throttled(4);
|
31 | assert.deepEqual(spy.args, [[1], [4]]);
|
32 |
|
33 | time.restore();
|
34 | });
|
35 |
|
36 | it('preserves the `this` when throttled functions are invoked', () => {
|
37 | let result;
|
38 | let throttled = throttle(function() {
|
39 | result = this.bar;
|
40 | }, 100);
|
41 |
|
42 | throttled.call({bar: 'baz'});
|
43 | assert(result === 'baz');
|
44 | });
|
45 | });
|