-
-
Notifications
You must be signed in to change notification settings - Fork 621
/
utils.throttle.js
42 lines (36 loc) · 1.48 KB
/
utils.throttle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import requestLib from 'got';
import throttled from '../lib/utils/throttle.js';
import sinon from 'sinon';
import { assert } from 'chai';
describe('Throttle tests', function () {
this.timeout(6000);
let server;
// Create a fake http server to emulate http call and responses.
before(function () {
server = sinon.fakeServer.create();
});
// Remove any server responses added in current test suite.
after(function () {
server.restore();
});
const url = 'https://yesno.wtf/api'; // Fake url used in this test, it could be anything.
it('Should make three requests with 2000ms interval. (Throttle function)', function () {
// If we don't want to rely on the availability of a particular api we can use mocks.
// The fake server intercept http calls and return specified objects if it mach the same method/url.
server.respondWith('GET', url, JSON.stringify({ test: 'this works' }));
const req = throttled(requestLib, {
limit: 1,
interval: 2000
});
return Promise.all([req({ url }), req({ url }), req({ url })])
.then((response) => response.map(req => new Date(req.headers.date).getTime()))
.then((dates) => {
const firstAndSecondReq = dates[1] - dates[0];
const secondAndThirdReq = dates[2] - dates[1];
assert.isAtLeast(firstAndSecondReq, 1000);
assert.isAtMost(firstAndSecondReq, 3000);
assert.isAtLeast(secondAndThirdReq, 1000);
assert.isAtMost(secondAndThirdReq, 3000);
});
});
});