/[sudobot]/trunk/tests/utils/cache.test.ts
ViewVC logotype

Contents of /trunk/tests/utils/cache.test.ts

Parent Directory Parent Directory | Revision Log Revision Log


Revision 575 - (show annotations)
Mon Jul 29 17:59:26 2024 UTC (8 months ago) by rakinar2
File MIME type: application/typescript
File size: 2316 byte(s)
chore: add trunk
1 import { cache, resetCache } from "@/utils/cache";
2 import { beforeEach, describe, expect, it, vi } from "vitest";
3
4 describe("caching utilities", () => {
5 beforeEach(() => {
6 resetCache();
7 });
8
9 it("should cache a value", () => {
10 const callback = vi.fn(() => Math.random());
11 const cached = cache("callback", callback);
12 expect(cached()).toBe(cached());
13 expect(callback.mock.calls.length).toBe(1);
14 });
15
16 it("should cache a value with a TTL", { repeats: 10 }, async () => {
17 const callback = vi.fn(() => Math.random());
18 const cached = cache("callback", callback, { ttl: 100 });
19 expect(cached()).toBe(cached());
20 expect(callback.mock.calls.length).toBe(1);
21 await new Promise(resolve => setTimeout(resolve, 110));
22 expect(cached()).toBe(cached());
23 expect(callback.mock.calls.length).toBe(2);
24 });
25
26 it("should cache a value with an onHit callback", () => {
27 const callback = vi.fn(() => Math.random());
28 const onHit = vi.fn();
29 const cached = cache("callback", callback, { onHit });
30 expect(cached()).toBe(cached());
31 expect(onHit.mock.calls.length).toBe(1);
32 });
33
34 it("should cache a value with an onHit callback and a TTL", { repeats: 10 }, async () => {
35 const callback = vi.fn(() => Math.random());
36 const onHit = vi.fn();
37 const cached = cache("callback", callback, { ttl: 100, onHit });
38 expect(cached()).toBe(cached());
39 expect(onHit.mock.calls.length).toBe(1);
40 await new Promise(resolve => setTimeout(resolve, 110));
41 expect(cached()).toBe(cached());
42 expect(onHit.mock.calls.length).toBe(2);
43 });
44
45 it("it should cache a value with an invoke option", () => {
46 const callback = vi.fn(() => Math.random());
47 const cached = cache("callback", callback, { invoke: true });
48 expect(cached).toBe(cached);
49 expect(callback.mock.calls.length).toBe(1);
50 });
51
52 it("it can clear the cache", () => {
53 const callback = vi.fn(() => Math.random());
54 const cached = cache("callback", callback);
55 expect(cached()).toBe(cached());
56 resetCache();
57 expect(cached()).toBe(cached());
58 expect(callback.mock.calls.length).toBe(2);
59 });
60 });

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26