1+ import { cacheGet } from './redis' ;
2+ import { redis } from './redis' ; // or your Redis client module
3+
4+ describe ( 'cacheGet' , ( ) => {
5+ const testKey = 'test-corrupt-entry' ;
6+ const fullKey = `cache:${ testKey } ` ;
7+
8+ afterEach ( async ( ) => {
9+ await redis . del ( fullKey ) ;
10+ jest . restoreAllMocks ( ) ;
11+ } ) ;
12+
13+ it ( 'should return parsed data for a valid cache entry' , async ( ) => {
14+ const data = { id : 123 , name : 'Alice' } ;
15+ await redis . set ( fullKey , JSON . stringify ( data ) ) ;
16+
17+ const result = await cacheGet < { id : number ; name : string } > ( testKey ) ;
18+ expect ( result ) . toEqual ( data ) ;
19+ } ) ;
20+
21+ it ( 'should handle malformed JSON safely by logging, deleting the key, and returning null' , async ( ) => {
22+ // 1. Seed a corrupted JSON entry in Redis
23+ const corruptedValue = '{ "id": 123, "name": invalid_json ' ;
24+ await redis . set ( fullKey , corruptedValue ) ;
25+
26+ const warnSpy = jest . spyOn ( console , 'warn' ) . mockImplementation ( ( ) => { } ) ;
27+
28+ // 2. Call cacheGet — should NOT throw
29+ const result = await cacheGet ( testKey ) ;
30+
31+ // 3. Verify acceptance criteria
32+ expect ( result ) . toBeNull ( ) ;
33+ expect ( warnSpy ) . toHaveBeenCalledWith (
34+ expect . stringContaining ( `Failed to parse cached JSON for key "${ fullKey } "` ) ,
35+ expect . any ( Error )
36+ ) ;
37+
38+ // 4. Verify the corrupted key was evicted from Redis
39+ const remainingKey = await redis . get ( fullKey ) ;
40+ expect ( remainingKey ) . toBeNull ( ) ;
41+ } ) ;
42+ } ) ;
0 commit comments