|
| 1 | +import { describe, it, expect, vi, beforeEach } from 'vitest'; |
| 2 | + |
| 3 | +// import target functions |
| 4 | +import {} from // exports |
| 5 | +'./StudentProfile'; |
| 6 | + |
| 7 | +describe('StudentProfile async service layer mock & cache stub integrations', () => { |
| 8 | + beforeEach(() => { |
| 9 | + vi.clearAllMocks(); |
| 10 | + }); |
| 11 | + |
| 12 | + it('shows pending service state while loading', async () => { |
| 13 | + const mockService = vi.fn( |
| 14 | + () => new Promise((resolve) => setTimeout(() => resolve('done'), 50)) |
| 15 | + ); |
| 16 | + |
| 17 | + const promise = mockService(); |
| 18 | + |
| 19 | + expect(mockService).toHaveBeenCalled(); |
| 20 | + |
| 21 | + await promise; |
| 22 | + }); |
| 23 | + |
| 24 | + it('checks cache before database retrieval', async () => { |
| 25 | + const cacheGet = vi.fn().mockReturnValue('cached-data'); |
| 26 | + const dbGet = vi.fn(); |
| 27 | + |
| 28 | + const result = cacheGet(); |
| 29 | + |
| 30 | + expect(result).toBe('cached-data'); |
| 31 | + expect(dbGet).not.toHaveBeenCalled(); |
| 32 | + }); |
| 33 | + |
| 34 | + it('uses fallback when endpoint timeout occurs', async () => { |
| 35 | + const api = vi.fn().mockRejectedValue(new Error('timeout')); |
| 36 | + |
| 37 | + let result; |
| 38 | + |
| 39 | + try { |
| 40 | + await api(); |
| 41 | + } catch { |
| 42 | + result = 'fallback'; |
| 43 | + } |
| 44 | + |
| 45 | + expect(result).toBe('fallback'); |
| 46 | + }); |
| 47 | + |
| 48 | + it('writes cache after successful refresh', async () => { |
| 49 | + const cacheSet = vi.fn(); |
| 50 | + |
| 51 | + const data = { |
| 52 | + login: 'ganesh', |
| 53 | + }; |
| 54 | + |
| 55 | + cacheSet(data); |
| 56 | + |
| 57 | + expect(cacheSet).toHaveBeenCalledWith(data); |
| 58 | + }); |
| 59 | + |
| 60 | + it('handles async service mock flow', async () => { |
| 61 | + const cacheGet = vi.fn().mockReturnValue(null); |
| 62 | + |
| 63 | + const dbGet = vi.fn().mockResolvedValue({ |
| 64 | + value: 'fresh', |
| 65 | + }); |
| 66 | + |
| 67 | + const cacheSet = vi.fn(); |
| 68 | + |
| 69 | + const cached = cacheGet(); |
| 70 | + |
| 71 | + if (!cached) { |
| 72 | + const fresh = await dbGet(); |
| 73 | + cacheSet(fresh); |
| 74 | + } |
| 75 | + |
| 76 | + expect(cacheGet).toHaveBeenCalled(); |
| 77 | + expect(dbGet).toHaveBeenCalled(); |
| 78 | + expect(cacheSet).toHaveBeenCalled(); |
| 79 | + }); |
| 80 | +}); |
0 commit comments