UNPKG

1.87 kBJavaScriptView Raw
1const LRU = require('lru-cache');
2const Koa = require('koa');
3const request = require('supertest');
4const test = require('ava');
5
6const cash = require('..');
7
8const createApp = function(c, opts) {
9 const app = new Koa();
10 app.use(
11 cash(
12 opts || {
13 get(key) {
14 return c.get(key);
15 },
16 set(key, value) {
17 return c.set(key, value);
18 }
19 }
20 )
21 );
22 return app;
23};
24
25const c = new LRU();
26const date = Math.round(Date.now() / 1000);
27
28test.before.cb(t => {
29 const app = createApp(c);
30 app.use(async function(ctx) {
31 if (await ctx.cashed()) return;
32 ctx.body = 'lol';
33 ctx.etag = 'lol';
34 ctx.type = 'text/lol; charset=utf-8';
35 ctx.lastModified = new Date(date * 1000);
36 });
37
38 request(app.listen())
39 .get('/')
40 .expect(200, t.end);
41});
42
43test.cb('when cached when the method is GET it should serve from cache', t => {
44 const app = createApp(c);
45 app.use(async function(ctx) {
46 if (await ctx.cashed()) return;
47 throw new Error('wtf');
48 });
49
50 request(app.listen())
51 .get('/')
52 .expect(200)
53 .expect('Content-Type', 'text/lol; charset=utf-8')
54 .expect('Content-Encoding', 'identity')
55 .expect('ETag', '"lol"')
56 .expect('lol', t.end);
57});
58
59test.cb(
60 'when cached when the method is POST it should not serve from cache',
61 t => {
62 const app = createApp(c);
63 app.use(async function(ctx) {
64 if (await ctx.cashed()) throw new Error('wtf');
65 ctx.body = 'lol';
66 });
67
68 request(app.listen())
69 .post('/')
70 .expect(200, t.end);
71 }
72);
73
74test.cb('when cached when the response is fresh it should 304', t => {
75 const app = createApp(c);
76 app.use(async function(ctx) {
77 if (await ctx.cashed()) return;
78 throw new Error('wtf');
79 });
80
81 request(app.listen())
82 .get('/')
83 .set('If-None-Match', '"lol"')
84 .expect(304, t.end);
85});