-
Notifications
You must be signed in to change notification settings - Fork 7
/
token-cache.test.js
112 lines (99 loc) · 2.9 KB
/
token-cache.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const Promise = require('bluebird');
const tokenCache = require('./token-cache');
describe('cache', () => {
test('should use the maxAge setting', () => {
const getToken = jest
.fn()
.mockReturnValueOnce(Promise.resolve('token1'))
.mockReturnValueOnce(Promise.resolve('token2'));
const cache = tokenCache(getToken, {
maxAge: 100
});
return cache()
.then((token) => {
expect(token).toEqual('token1');
})
.then(() => Promise.delay(50))
.then(() => cache())
.then((token) => {
expect(token).toEqual('token1');
})
.then(() => Promise.delay(100))
.then(() => cache())
.then((token) => {
expect(token).toEqual('token2');
});
});
test('should use the getMaxAge setting', () => {
const getToken = jest
.fn()
.mockReturnValueOnce(
Promise.resolve({ access_token: 'token1', expires_in: 2 })
)
.mockReturnValueOnce(
Promise.resolve({ access_token: 'token2', expires_in: 5 })
);
const cache = tokenCache(getToken, {
getMaxAge: (token) => token.expires_in * 1000
});
return cache()
.then((token) => {
expect(token.access_token).toEqual('token1');
})
.then(() => Promise.delay(1000))
.then(() => cache())
.then((token) => {
expect(token.access_token).toEqual('token1');
})
.then(() => Promise.delay(2000))
.then(() => cache())
.then((token) => {
expect(token.access_token).toEqual('token2');
});
});
test('should support reset', () => {
const getToken = jest
.fn()
.mockReturnValueOnce(
Promise.resolve({ access_token: 'token1', expires_in: 5 })
)
.mockReturnValueOnce(
Promise.resolve({ access_token: 'token2', expires_in: 10 })
);
const cache = tokenCache(getToken, {
getMaxAge: (token) => token.expires_in * 1000
});
return cache()
.then((config) => {
expect(config.access_token).toEqual('token1');
cache.reset();
})
.then(() => cache())
.then((config) => {
expect(config.access_token).toEqual('token2');
});
});
test('should not make concurrent calls for a cache miss', () => {
const getToken = jest
.fn()
.mockReturnValueOnce(
Promise.delay(50).then(() => Promise.resolve('token1'))
);
const cache = tokenCache(getToken, {
maxAge: 100
});
return Promise.all([cache(), cache()]).spread((token1, token2) => {
expect(token1).toEqual('token1');
expect(token2).toEqual('token1');
});
});
test('should handle errors correctly', () => {
const getToken = () => Promise.reject(new Error('unable to fetch token'));
const cache = tokenCache(getToken, {
maxAge: 100
});
return cache().catch((err) => {
expect(err.message).toEqual('unable to fetch token');
});
});
});