This repository has been archived by the owner on Jul 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.js
64 lines (55 loc) · 2.14 KB
/
test.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import test from 'ava';
import fn from './';
const sleep = time => new Promise(resolve => setTimeout(resolve, time));
const noop = () => {};
const getCircuitBreaker = (command, props) => fn(command, props);
const failureCommand = () => Promise.reject(new Error('Failed Command'));
const successAfterNumFail = num => {
let failCount = num;
return function () {
return new Promise((resolve, reject) => {
if (failCount > 0) {
failCount -= 1;
reject(new Error('Failed Command'));
}
resolve('success');
});
};
};
test('Works with defaults', async t => {
const ckt = getCircuitBreaker(failureCommand);
return ckt.fire().catch(err => t.is(err.message, 'Failed Command'));
});
test('Get closed after repeated failed attempts', async t => {
const ckt = getCircuitBreaker(failureCommand, { maxError: 5, maxTime: 10000 });
await Promise.all(
[1, 2, 3, 4, 5].map(val => ckt.fire(val).catch(noop))
);
return ckt
.fire()
.catch(err => t.is(err.message, 'Service Currently unavailable'));
});
test('Should Retry', async t => {
const ckt = getCircuitBreaker(failureCommand, { maxError: 5, maxTime: 10000, retry: 1000 });
t.plan(2);
await Promise.all([1, 2, 3, 4, 5].map(val => ckt.fire(val).catch(noop)));
await ckt.fire().catch(err => t.is(err.message, 'Service Currently unavailable'));
await sleep(2000);
return ckt.fire().catch(err => t.is(err.message, 'Failed Command'));
});
test('Should timeout', async t => {
const ckt = getCircuitBreaker(sleep, { maxError: 5, maxTime: 10000, retry: 1000, timeout: 1000 });
return ckt.fire(2000).catch(err => t.is(err.message, 'Service Timed Out'));
});
test('Should reopen', async t => {
t.plan(3);
const ckt = getCircuitBreaker(successAfterNumFail(5), { maxError: 5, maxTime: 10000, retry: 1000, timeout: 1000 });
await Promise.all([1, 2, 3, 4, 5].map(val => ckt.fire(val).catch(noop)));
await ckt.fire().catch(err => t.is(err.message, 'Service Currently unavailable'));
await sleep(1000);
await ckt.fire().then(val => t.is(val, 'success'));
return await ckt.fire().then(val => t.is(val, 'success'));
});
test('should fail when no command is passed', t => {
t.throws(() => getCircuitBreaker());
});