-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcaching_helpers.test.ts
More file actions
84 lines (65 loc) · 2.11 KB
/
caching_helpers.test.ts
File metadata and controls
84 lines (65 loc) · 2.11 KB
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
import { describe, expect, it } from 'vitest';
import { asyncMemo, memo, once, setAsyncMemo } from './caching_helpers';
describe('Cache helpers', () => {
it('caches results', () => {
// Arrange
let calls = 0;
const key = 'store';
const result = 42;
const results = [];
const operation = () => (calls++, result);
// Act
results.push(memo(key, operation));
results.push(memo(key, operation));
results.push(memo(key, operation));
// Assert
expect(calls).toBe(1);
results.forEach((actualResult) => expect(actualResult).toEqual(result));
});
it('caches async results', async () => {
// Arrange
let calls = 0;
const key = 'store';
const result = 42;
const operation = () => (calls++, Promise.resolve(result));
// Act
const results = await Promise.all([
asyncMemo(key, operation),
asyncMemo(key, operation),
asyncMemo(key, operation),
]);
// Assert
expect(calls).toBe(1);
results.forEach((actualResult) => expect(actualResult).toEqual(result));
});
it('sets cached async results', async () => {
// Arrange
let calls = 0;
const key = 'store';
const lazyResult = 42;
const eagerResult = 23;
const operation = () => (calls++, Promise.resolve(lazyResult));
// Act
setAsyncMemo(key, eagerResult);
const results = await Promise.all([
asyncMemo(key, operation),
asyncMemo(key, operation),
asyncMemo(key, operation),
]);
// Assert
expect(calls).toBe(0);
results.forEach((actualResult) => expect(actualResult).toEqual(eagerResult));
});
it('caches results using once', () => {
// Arrange.
let count = 0;
const counter = () => count++;
const cachedCounter = once(counter);
// Act.
cachedCounter();
cachedCounter();
cachedCounter();
// Assert.
expect(count).toEqual(1);
});
});