-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtest.js
68 lines (60 loc) · 1.54 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
65
66
67
68
'use strict'
const { setTimeout } = require('timers/promises')
const test = require('ava')
const memoizeToken = require('.')
test('successive calls', async t => {
const cache = new Map()
const key = 'test'
let value = -1
const values = ['foo', 'bar']
const fn = () => values[++value]
const getToken = memoizeToken(fn, { max: 2, cache, key })
t.is(await getToken(), 'foo')
t.is(await getToken(), 'foo')
t.is(cache.get(key).value, 'foo')
t.is(cache.get(key).count, 2)
t.is(await getToken(), 'bar')
t.is(await getToken(), 'bar')
})
test('token refresh', async t => {
const cache = new Map()
const key = 'test'
let value = -1
const values = ['foo', 'bar']
const fn = memoizeToken(() => values[++value], { max: 2, cache, key })
await fn()
await fn()
t.is(cache.get(key).value, 'foo')
t.is(cache.get(key).count, 2)
await fn()
await fn()
t.is(cache.get(key).value, 'bar')
t.is(cache.get(key).count, 2)
})
test('expire time', async t => {
const cache = new Map()
const key = 'test'
let value = -1
const values = ['foo', 'bar', 'baz']
const fn = memoizeToken(() => values[++value], {
max: 2,
cache,
key,
expire: 100
})
await fn()
t.is(cache.get(key).value, 'foo')
t.is(cache.get(key).count, 1)
await fn()
t.is(cache.get(key).value, 'foo')
t.is(cache.get(key).count, 2)
await setTimeout(100)
await fn()
t.is(cache.get(key).value, 'bar')
t.is(cache.get(key).count, 1)
await fn()
await fn()
await fn()
t.is(cache.get(key).value, 'baz')
t.is(cache.get(key).count, 2)
})