1- import { TLRUCache } from './lru -cache' ;
1+ import { TLRUCache } from './tlru -cache' ;
22
33describe ( 'TLRU Cache' , ( ) => {
44 let cache : TLRUCache ;
5- const expectedCacheTimeoutMs = 50 ;
5+ const expectedCacheTimeoutMs = 10 ;
66
77 beforeEach ( async ( ) => {
88 cache = new TLRUCache ( 2 , expectedCacheTimeoutMs ) ;
99 } ) ;
1010
11- afterAll ( async ( ) => {
11+ afterEach ( async ( ) => {
1212 jest . restoreAllMocks ( ) ;
13+ jest . clearAllTimers ( ) ;
1314 } ) ;
1415
15- it ( 'should evict cache after timeout' , async ( ) => {
16+ it ( 'should evict cache after timeout' , ( ) => {
1617 jest . useFakeTimers ( ) ;
1718 jest . spyOn ( global , 'setTimeout' ) ;
1819
@@ -23,4 +24,38 @@ describe('TLRU Cache', () => {
2324 expect ( setTimeout ) . toHaveBeenLastCalledWith ( expect . any ( Function ) , expectedCacheTimeoutMs ) ;
2425 expect ( cache . get ( 'a' ) ) . toBeUndefined ( ) ;
2526 } ) ;
27+
28+ /**
29+ * This test assumes implementation which is not ideal, but that's
30+ * the only way I know of how to go around timers in jest
31+ **/
32+ it ( 'should overwrite existing cache entry' , ( ) => {
33+ jest . useFakeTimers ( ) ;
34+ jest . spyOn ( global , 'setTimeout' ) ;
35+ jest . spyOn ( global , 'clearTimeout' ) ;
36+
37+ cache . set ( 'a' , 'apple' ) ;
38+ jest . advanceTimersByTime ( expectedCacheTimeoutMs - 1 ) ;
39+ cache . set ( 'a' , 'avocado' ) ;
40+
41+ expect ( setTimeout ) . toHaveBeenCalledTimes ( 2 ) ;
42+ expect ( setTimeout ) . toHaveBeenLastCalledWith ( expect . any ( Function ) , expectedCacheTimeoutMs ) ;
43+ expect ( clearTimeout ) . toHaveBeenCalledTimes ( 1 ) ;
44+ // spin the clock by 5sec. After that time cache entry should be still valid.
45+ jest . advanceTimersByTime ( expectedCacheTimeoutMs / 2 ) ;
46+
47+ // setting assertion in a weird way because calling cache.get()
48+ // will reset eviction timer which will mess up next assertion
49+ let avocadoInCache = false ;
50+ cache . forEach ( ( value , key ) => {
51+ if ( key === 'a' && value === 'avocado' ) {
52+ avocadoInCache = true ;
53+ }
54+ } ) ;
55+ expect ( avocadoInCache ) . toBe ( true ) ;
56+
57+ // after another spin of 5 sec, cache entry should evict itself
58+ jest . advanceTimersByTime ( expectedCacheTimeoutMs / 2 ) ;
59+ expect ( cache . has ( 'a' ) ) . toBeFalsy ( ) ;
60+ } ) ;
2661} ) ;
0 commit comments