|
| 1 | +import { of, throwError } from 'rxjs'; |
| 2 | +import { delay } from 'rxjs/operators'; |
| 3 | +import { cache, CacheOptions } from './cache'; |
| 4 | + |
| 5 | +describe('cache operator', () => { |
| 6 | + it('should cache the result of the observable', (done) => { |
| 7 | + const callback = jest.fn(() => of('test').pipe(delay(100))); |
| 8 | + const options: CacheOptions = {}; |
| 9 | + |
| 10 | + const cached$ = cache(callback, options); |
| 11 | + |
| 12 | + let callCount = 0; |
| 13 | + cached$.subscribe((value) => { |
| 14 | + expect(value).toBe('test'); |
| 15 | + expect(callback).toHaveBeenCalledTimes(1); |
| 16 | + callCount++; |
| 17 | + if (callCount === 2) { |
| 18 | + done(); |
| 19 | + } |
| 20 | + }); |
| 21 | + |
| 22 | + // Subscribe again to ensure the cached value is used |
| 23 | + cached$.subscribe((value) => { |
| 24 | + expect(value).toBe('test'); |
| 25 | + expect(callback).toHaveBeenCalledTimes(1); |
| 26 | + callCount++; |
| 27 | + if (callCount === 2) { |
| 28 | + done(); |
| 29 | + } |
| 30 | + }); |
| 31 | + }); |
| 32 | + |
| 33 | + it('should handle errors correctly', (done) => { |
| 34 | + const callback = jest.fn(() => throwError(() => new Error('test error'))); |
| 35 | + const options: CacheOptions = {}; |
| 36 | + |
| 37 | + const cached$ = cache(callback, options); |
| 38 | + |
| 39 | + cached$.subscribe({ |
| 40 | + next: () => ({}), |
| 41 | + error: (err) => { |
| 42 | + expect(err.message).toBe('test error'); |
| 43 | + expect(callback).toHaveBeenCalledTimes(1); |
| 44 | + done(); |
| 45 | + }, |
| 46 | + complete: () => ({}), |
| 47 | + }); |
| 48 | + }); |
| 49 | + |
| 50 | + it('should not call the callback again if the cache is still valid', (done) => { |
| 51 | + const callback = jest.fn(() => of('test').pipe(delay(100))); |
| 52 | + const options: CacheOptions = {}; |
| 53 | + |
| 54 | + const cached$ = cache(callback, options); |
| 55 | + |
| 56 | + cached$.subscribe((value) => { |
| 57 | + expect(value).toBe('test'); |
| 58 | + expect(callback).toHaveBeenCalledTimes(1); |
| 59 | + cached$.subscribe((value) => { |
| 60 | + expect(value).toBe('test'); |
| 61 | + expect(callback).toHaveBeenCalledTimes(1); |
| 62 | + done(); |
| 63 | + }); |
| 64 | + }); |
| 65 | + }); |
| 66 | + |
| 67 | + it('should call the callback again if the cache is invalidated', (done) => { |
| 68 | + const callback = jest.fn(() => of('test').pipe(delay(100))); |
| 69 | + const options: CacheOptions = { expirationTime: 50 }; |
| 70 | + |
| 71 | + const cached$ = cache(callback, options); |
| 72 | + |
| 73 | + cached$.subscribe((value) => { |
| 74 | + expect(value).toBe('test'); |
| 75 | + expect(callback).toHaveBeenCalledTimes(1); |
| 76 | + setTimeout(() => { |
| 77 | + cached$.subscribe((value) => { |
| 78 | + expect(value).toBe('test'); |
| 79 | + expect(callback).toHaveBeenCalledTimes(2); |
| 80 | + done(); |
| 81 | + }); |
| 82 | + }, 100); |
| 83 | + }); |
| 84 | + }); |
| 85 | +}); |
0 commit comments