1 | 'use strict';
|
2 |
|
3 | var expect = require('chai').expect;
|
4 | var cache = require('../lib/cache');
|
5 | var Promise = require('bluebird');
|
6 |
|
7 | describe('cache', function(){
|
8 | var ns = 'ns', key = 'key', ttl = 1000, ct = 0, value = 'value';
|
9 | function getter() {
|
10 | ct++; return 'value';
|
11 | }
|
12 | function asyncGetter(){
|
13 | ct++;
|
14 | return Promise.resolve(value);
|
15 | }
|
16 | beforeEach(function(){
|
17 | cache.enable();
|
18 | cache.clear();
|
19 | ct = 0;
|
20 | });
|
21 |
|
22 | it('should only call getter with the first call', function(){
|
23 | return cache.get(ns, key, ttl, getter)
|
24 | .then(function(){
|
25 | return cache.get(ns, key, ttl, getter);
|
26 | }).then(function(val){
|
27 | expect(val).to.eql(value);
|
28 | expect(ct).to.eql(1);
|
29 | });
|
30 | });
|
31 |
|
32 | it('should only call async getter with the first call', function(){
|
33 | return cache.get(ns, key, ttl, asyncGetter)
|
34 | .then(function(){
|
35 | return cache.get(ns, key, ttl, asyncGetter);
|
36 | }).then(function(val){
|
37 | expect(val).to.eql(value);
|
38 | expect(ct).to.eql(1);
|
39 | });
|
40 | });
|
41 |
|
42 | it('should call getter again after ttl', function(){
|
43 | return cache.get(ns, key, ttl, asyncGetter)
|
44 | .then(function(){
|
45 | return Promise.delay(ttl + 100);
|
46 | }).then(function(){
|
47 | return cache.get(ns, key, ttl, asyncGetter);
|
48 | }).then(function(val){
|
49 | expect(val).to.eql(value);
|
50 | expect(ct).to.eql(2);
|
51 | });
|
52 | });
|
53 |
|
54 | it('can clear cache after disabling', function(){
|
55 | cache.disable();
|
56 | cache.clear();
|
57 | });
|
58 | });
|