|
| 1 | +import Cache from '../Cache'; |
| 2 | + |
| 3 | +let cache: Cache; |
| 4 | + |
| 5 | +describe('util/Cache', () => { |
| 6 | + beforeEach(() => { |
| 7 | + cache = new Cache(); |
| 8 | + }); |
| 9 | + |
| 10 | + test('should set, get and unset correctly', () => { |
| 11 | + cache.set<string>('foo', 'bar'); |
| 12 | + expect(cache.has('foo')).toBeTruthy(); |
| 13 | + expect(cache.get<string>('foo')).toBe('bar'); |
| 14 | + |
| 15 | + cache.unset('foo'); |
| 16 | + cache.unset('foo'); |
| 17 | + expect(cache.has('foo')).toBeFalsy(); |
| 18 | + }); |
| 19 | + |
| 20 | + test('should set and get correctly with 0 value', () => { |
| 21 | + cache.set<number>('foo', 0); |
| 22 | + expect(cache.has('foo')).toBeTruthy(); |
| 23 | + expect(cache.get<number>('foo')).toBe(0); |
| 24 | + }); |
| 25 | + |
| 26 | + test('should return undefined when not set', () => { |
| 27 | + cache.set<string>('foo1', 'bar1'); |
| 28 | + cache.set<string>('foo2', 'bar2'); |
| 29 | + cache.set<string>('foo3', 'bar3'); |
| 30 | + expect(cache.get<string>('foo1')).toBe('bar1'); |
| 31 | + expect(cache.get<string>('foo2')).toBe('bar2'); |
| 32 | + expect(cache.get<string>('foo3')).toBe('bar3'); |
| 33 | + cache.unsetAll('foo'); |
| 34 | + expect(cache.get<string>('foo1')).toBeUndefined(); |
| 35 | + expect(cache.get<string>('foo2')).toBeUndefined(); |
| 36 | + expect(cache.get<string>('foo3')).toBeUndefined(); |
| 37 | + }); |
| 38 | + |
| 39 | + test('should properly unset all', () => { |
| 40 | + expect(cache.get<string>('foobar')).toBeUndefined(); |
| 41 | + }); |
| 42 | + |
| 43 | + test('should merge correctly without mutating original object', () => { |
| 44 | + const origObj = { a: 1 }; |
| 45 | + const newObj = { b: 2 }; |
| 46 | + cache.set<typeof origObj>('foo', origObj); |
| 47 | + cache.merge('foo', newObj); |
| 48 | + const value = cache.get<typeof origObj & typeof newObj>('foo'); |
| 49 | + expect(1).toBe(value?.a); |
| 50 | + expect(2).toBe(value?.b); |
| 51 | + expect(value).not.toBe(origObj); |
| 52 | + }); |
| 53 | + |
| 54 | + test('should not merge non existant items', () => { |
| 55 | + try { |
| 56 | + cache.merge('foo', { b: 2 }); |
| 57 | + } catch (e) { |
| 58 | + expect('Key foo not in cache!').toBe((e as Error).message); |
| 59 | + } |
| 60 | + }); |
| 61 | +}); |
0 commit comments