cache.test.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { afterEach } from "node:test";
  2. import { beforeEach, describe, expect, it, vi } from "vitest";
  3. import { cache } from "#/utils/cache";
  4. describe("Cache", () => {
  5. const testKey = "key";
  6. const testData = { message: "Hello, world!" };
  7. const testTTL = 1000; // 1 second
  8. beforeEach(() => {
  9. localStorage.clear();
  10. vi.useFakeTimers();
  11. });
  12. afterEach(() => {
  13. vi.useRealTimers();
  14. });
  15. it("sets data in localStorage with expiration", () => {
  16. cache.set(testKey, testData, testTTL);
  17. const cachedEntry = JSON.parse(
  18. localStorage.getItem(`app_cache_${testKey}`) || "",
  19. );
  20. expect(cachedEntry.data).toEqual(testData);
  21. expect(cachedEntry.expiration).toBeGreaterThan(Date.now());
  22. });
  23. it("gets data from localStorage if not expired", () => {
  24. cache.set(testKey, testData, testTTL);
  25. expect(cache.get(testKey)).toEqual(testData);
  26. });
  27. it("should expire after 5 minutes by default", () => {
  28. cache.set(testKey, testData);
  29. expect(cache.get(testKey)).not.toBeNull();
  30. vi.advanceTimersByTime(5 * 60 * 1000 + 1);
  31. expect(cache.get(testKey)).toBeNull();
  32. expect(localStorage.getItem(`app_cache_${testKey}`)).toBeNull();
  33. });
  34. it("returns null if cached data is expired", () => {
  35. cache.set(testKey, testData, testTTL);
  36. vi.advanceTimersByTime(testTTL + 1);
  37. expect(cache.get(testKey)).toBeNull();
  38. expect(localStorage.getItem(`app_cache_${testKey}`)).toBeNull();
  39. });
  40. it("deletes data from localStorage", () => {
  41. cache.set(testKey, testData, testTTL);
  42. cache.delete(testKey);
  43. expect(localStorage.getItem(`app_cache_${testKey}`)).toBeNull();
  44. });
  45. it("clears all data with the app prefix from localStorage", () => {
  46. cache.set(testKey, testData, testTTL);
  47. cache.set("anotherKey", { data: "More data" }, testTTL);
  48. cache.clearAll();
  49. expect(localStorage.length).toBe(0);
  50. });
  51. it("does not retrieve non-prefixed data from localStorage when clearing", () => {
  52. localStorage.setItem("nonPrefixedKey", "should remain");
  53. cache.set(testKey, testData, testTTL);
  54. cache.clearAll();
  55. expect(localStorage.getItem("nonPrefixedKey")).toBe("should remain");
  56. });
  57. });