cache.test.ts•2.75 kB
/**
* Tests for the cache utility
*/
import { describe, test, expect, beforeEach } from '@jest/globals';
import { cacheService } from '../utils/cache';
// These tests focus only on the cache functionality which doesn't require database access
describe('Cache Service', () => {
beforeEach(() => {
// Clear the cache before each test
cacheService.clear();
});
test('should set and get values from cache', () => {
const key = 'testKey';
const value = { test: 'data' };
// Set a value in the cache
cacheService.set(key, value);
// Retrieve the value from the cache
const retrieved = cacheService.get(key);
// Verify it matches the original value
expect(retrieved).toEqual(value);
});
test('should clear the cache', () => {
// Set some values in the cache
cacheService.set('key1', 'value1');
cacheService.set('key2', 'value2');
// Verify values are in the cache
expect(cacheService.get('key1')).toBe('value1');
expect(cacheService.get('key2')).toBe('value2');
// Clear the cache
cacheService.clear();
// Verify values are no longer in the cache
expect(cacheService.get('key1')).toBeUndefined();
expect(cacheService.get('key2')).toBeUndefined();
});
test('should delete by prefix', () => {
// Set some values with different prefixes
cacheService.set('prefix1_key1', 'value1');
cacheService.set('prefix1_key2', 'value2');
cacheService.set('prefix2_key1', 'value3');
// Delete all keys with prefix1_
const deletedCount = cacheService.deleteByPrefix('prefix1_');
// Check that the correct number of keys were deleted
expect(deletedCount).toBe(2);
// Verify prefix1_ keys are gone
expect(cacheService.get('prefix1_key1')).toBeUndefined();
expect(cacheService.get('prefix1_key2')).toBeUndefined();
// Verify prefix2_ keys remain
expect(cacheService.get('prefix2_key1')).toBe('value3');
});
test('should get cache statistics', () => {
// Set a value
cacheService.set('key1', 'value1');
// Get the value (this should count as a hit)
cacheService.get('key1');
// Try to get a non-existent value (this should count as a miss)
cacheService.get('nonexistent');
// Get statistics
const stats = cacheService.getStats() as { hits: number, misses: number, keys: number };
// Verify statistics object has expected properties
expect(stats).toHaveProperty('hits');
expect(stats).toHaveProperty('misses');
expect(stats).toHaveProperty('keys');
// Verify counts
expect(stats.hits).toBeGreaterThanOrEqual(1);
expect(stats.misses).toBeGreaterThanOrEqual(1);
});
});