1
|
|
|
import { randomUUID } from 'crypto'; |
2
|
|
|
import { Cached } from '@/cache/decorators/Cached'; |
3
|
|
|
import { registeredBeans, registeredMethods } from '@/core'; |
4
|
|
|
|
5
|
|
|
jest.mock('@/core', () => ({ |
6
|
|
|
registeredBeans: new Map(), |
7
|
|
|
registeredMethods: new Map(), |
8
|
|
|
logger: { |
9
|
|
|
info: jest.fn(), |
10
|
|
|
debug: jest.fn(), |
11
|
|
|
error: jest.fn(), |
12
|
|
|
}, |
13
|
|
|
})); |
14
|
|
|
|
15
|
|
|
describe('Cached.ts', () => { |
16
|
|
|
beforeEach(() => { |
17
|
|
|
jest.resetAllMocks(); |
18
|
|
|
registeredMethods.clear(); |
19
|
|
|
registeredBeans.clear(); |
20
|
|
|
}); |
21
|
|
|
|
22
|
|
|
it('execute a cached function', async () => { |
23
|
|
|
// GIVEN |
24
|
|
|
class Class { |
25
|
|
|
@Cached() |
26
|
|
|
getUUIDCached() { |
27
|
|
|
return randomUUID(); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
getUUID() { |
31
|
|
|
return randomUUID(); |
32
|
|
|
} |
33
|
|
|
} |
34
|
|
|
const bean = new Class(); |
35
|
|
|
registeredMethods.set(bean.getUUID, bean as any); |
36
|
|
|
registeredMethods.set(bean.getUUIDCached, bean as any); |
37
|
|
|
registeredBeans.set('Class', bean as any); |
38
|
|
|
|
39
|
|
|
// WHEN |
40
|
|
|
const resultNoCache = bean.getUUID(); |
41
|
|
|
const resultCache = bean.getUUIDCached(); |
42
|
|
|
|
43
|
|
|
// THEN |
44
|
|
|
expect(bean.getUUID()).not.toBe(resultNoCache); |
45
|
|
|
expect(bean.getUUIDCached()).toBe(resultCache); |
46
|
|
|
}); |
47
|
|
|
|
48
|
|
|
it('caches a function by its arguments', async () => { |
49
|
|
|
// GIVEN |
50
|
|
|
class Class { |
51
|
|
|
@Cached() |
52
|
|
|
getUUIDCached(anArgument: string) { |
53
|
|
|
return `${randomUUID()}/${anArgument}`; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
const bean = new Class(); |
57
|
|
|
registeredMethods.set(bean.getUUIDCached, bean as any); |
58
|
|
|
registeredBeans.set('Class', bean as any); |
59
|
|
|
|
60
|
|
|
// WHEN |
61
|
|
|
const resultCache = bean.getUUIDCached('first'); |
62
|
|
|
|
63
|
|
|
// THEN |
64
|
|
|
expect(bean.getUUIDCached('second')).not.toBe(resultCache); |
65
|
|
|
expect(bean.getUUIDCached('first')).toBe(resultCache); |
66
|
|
|
}); |
67
|
|
|
|
68
|
|
|
it('invalidates a cache when expired', async () => { |
69
|
|
|
// GIVEN |
70
|
|
|
class Class { |
71
|
|
|
@Cached() |
72
|
|
|
getUUIDCached() { |
73
|
|
|
return randomUUID(); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
const bean = new Class(); |
77
|
|
|
registeredMethods.set(bean.getUUIDCached, bean as any); |
78
|
|
|
registeredBeans.set('Class', bean as any); |
79
|
|
|
|
80
|
|
|
// WHEN |
81
|
|
|
const resultCache = bean.getUUIDCached(); |
82
|
|
|
expect(bean.getUUIDCached()).toBe(resultCache); |
83
|
|
|
jest.useFakeTimers().setSystemTime(Date.now() + 60_001); |
84
|
|
|
|
85
|
|
|
// THEN |
86
|
|
|
expect(bean.getUUIDCached()).not.toBe(resultCache); |
87
|
|
|
}); |
88
|
|
|
}); |
89
|
|
|
|