home-daily-cache.service.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import { signal } from '@angular/core';
  2. import { fakeAsync, tick, TestBed } from '@angular/core/testing';
  3. import { firstValueFrom, of, Subject, throwError } from 'rxjs';
  4. import { HomeDailyCacheService } from './home-daily-cache.service';
  5. import { SessionService } from './session.service';
  6. const storageKey = 'xiaoshu.learning.homeDaily.v1';
  7. describe('HomeDailyCacheService', () => {
  8. let cache: HomeDailyCacheService;
  9. const user = signal({ userId: 100, groupId: 1 });
  10. const token = signal('r:daily-cache-test');
  11. beforeEach(() => {
  12. localStorage.removeItem(storageKey);
  13. user.set({ userId: 100, groupId: 1 });
  14. token.set('r:daily-cache-test');
  15. TestBed.configureTestingModule({ providers: [{ provide: SessionService, useValue: { user, token } }] });
  16. cache = TestBed.inject(HomeDailyCacheService);
  17. });
  18. afterEach(() => localStorage.removeItem(storageKey));
  19. it('reuses the same day after navigation and page reload, and forces a manual refresh', async () => {
  20. const fetch = jasmine.createSpy('fetch').and.returnValue(of({ totalIncome: 25 }));
  21. const first = await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
  22. expect(await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch))).toEqual(first);
  23. const restored = TestBed.runInInjectionContext(() => new HomeDailyCacheService());
  24. expect(await firstValueFrom(restored.load<{ totalIncome: number }>('stats', fetch))).toEqual(first);
  25. expect(fetch).toHaveBeenCalledTimes(1);
  26. fetch.and.returnValue(of({ totalIncome: 30 }));
  27. expect((await firstValueFrom(restored.load<{ totalIncome: number }>('stats', fetch, true))).value.totalIncome).toBe(30);
  28. expect(fetch).toHaveBeenCalledTimes(2);
  29. });
  30. it('separates Beijing days, accounts and roles', async () => {
  31. jasmine.clock().install();
  32. try {
  33. const fetch = jasmine.createSpy('fetch').and.returnValue(of({ totalIncome: 25 }));
  34. jasmine.clock().mockDate(new Date('2026-10-31T15:59:59Z'));
  35. await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
  36. jasmine.clock().mockDate(new Date('2026-10-31T16:00:00Z'));
  37. await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
  38. user.set({ userId: 300, groupId: 3 });
  39. await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
  40. user.set({ userId: 300, groupId: 1 });
  41. await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
  42. expect(fetch).toHaveBeenCalledTimes(4);
  43. } finally { jasmine.clock().uninstall(); }
  44. });
  45. it('deduplicates concurrent requests and caches success even after navigating away', async () => {
  46. const response = new Subject<{ totalIncome: number }>();
  47. const fetch = jasmine.createSpy('fetch').and.returnValue(response);
  48. const leaving = cache.load<{ totalIncome: number }>('stats', fetch).subscribe();
  49. leaving.unsubscribe();
  50. const second = firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch, true));
  51. response.next({ totalIncome: 50 });
  52. expect((await second).value.totalIncome).toBe(50);
  53. expect((await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch))).value.totalIncome).toBe(50);
  54. expect(fetch).toHaveBeenCalledTimes(1);
  55. });
  56. it('shows the cached result immediately when returning during a manual refresh', async () => {
  57. await firstValueFrom(cache.load('stats', () => of({ totalIncome: 25 })));
  58. const response = new Subject<{ totalIncome: number }>();
  59. const manual = firstValueFrom(cache.load('stats', () => response, true));
  60. const fetch = jasmine.createSpy('fetch');
  61. expect((await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch))).value.totalIncome).toBe(25);
  62. expect(fetch).not.toHaveBeenCalled();
  63. response.next({ totalIncome: 50 });
  64. expect((await manual).value.totalIncome).toBe(50);
  65. });
  66. it('keeps account and companion filter/page snapshots separate after a browser reload', async () => {
  67. const fetch = jasmine.createSpy('fetch').and.callFake((id: string) => of({ courses: [], schedules: [{ id }] }));
  68. for (const key of ['companion:today-page1', 'companion:today-page2', 'companion:tomorrow-student2'] as const) {
  69. await firstValueFrom(cache.load(key, () => fetch(key)));
  70. }
  71. await firstValueFrom(cache.load('account', () => of({ profile: { userId: 100 } })));
  72. const restored = TestBed.runInInjectionContext(() => new HomeDailyCacheService());
  73. expect((await firstValueFrom(restored.load<{ courses: unknown[]; schedules: { id: string }[] }>('companion:today-page1', () => fetch('unexpected')))).value.schedules[0].id).toBe('companion:today-page1');
  74. expect((await firstValueFrom(restored.load<{ courses: unknown[]; schedules: { id: string }[] }>('companion:today-page2', () => fetch('unexpected')))).value.schedules[0].id).toBe('companion:today-page2');
  75. expect(fetch).toHaveBeenCalledTimes(3);
  76. const accountFetch = jasmine.createSpy('accountFetch');
  77. expect((await firstValueFrom(restored.load<{ profile: { userId: number } }>('account', accountFetch))).value.profile.userId).toBe(100);
  78. expect(accountFetch).not.toHaveBeenCalled();
  79. });
  80. it('refreshes only on a visible day transition and removes its timer/listener on leave', fakeAsync(() => {
  81. const visibility = spyOnProperty(document, 'visibilityState', 'get').and.returnValue('visible');
  82. const refresh = jasmine.createSpy('refresh');
  83. const stop = cache.watchDay(refresh);
  84. document.dispatchEvent(new Event('visibilitychange'));
  85. expect(refresh).not.toHaveBeenCalled();
  86. const now = Date.now(), midnight = (Math.floor((now + 8 * 3600000) / 86400000) + 1) * 86400000 - 8 * 3600000;
  87. tick(midnight - now + 101);
  88. expect(refresh).toHaveBeenCalledTimes(1);
  89. document.dispatchEvent(new Event('visibilitychange'));
  90. expect(refresh).toHaveBeenCalledTimes(1);
  91. visibility.and.returnValue('hidden');
  92. tick(86400000);
  93. expect(refresh).toHaveBeenCalledTimes(1);
  94. visibility.and.returnValue('visible');
  95. document.dispatchEvent(new Event('visibilitychange'));
  96. expect(refresh).toHaveBeenCalledTimes(2);
  97. stop();
  98. tick(86400000);
  99. document.dispatchEvent(new Event('visibilitychange'));
  100. expect(refresh).toHaveBeenCalledTimes(2);
  101. }));
  102. it('invalidates every companion page in memory and storage while retaining other daily summaries', async () => {
  103. const sections = ['companion:today-page1', 'companion:today-page2', 'companion:tomorrow-student2'] as const;
  104. for (const key of sections) await firstValueFrom(cache.load(key, () => of({ courses: [], schedules: [{ dszt: 0 }] })));
  105. await firstValueFrom(cache.load('stats', () => of({ totalIncome: 25 })));
  106. cache.invalidateCompanion();
  107. const restored = TestBed.runInInjectionContext(() => new HomeDailyCacheService());
  108. const fetch = jasmine.createSpy('fetch').and.returnValue(of({ courses: [], schedules: [{ dszt: 30 }] }));
  109. for (const key of sections) {
  110. expect((await firstValueFrom(restored.load<{ schedules: { dszt: number }[] }>(key, fetch))).value.schedules[0].dszt).toBe(30);
  111. }
  112. expect(fetch).toHaveBeenCalledTimes(3);
  113. const statsFetch = jasmine.createSpy('statsFetch');
  114. expect((await firstValueFrom(cache.load<{ totalIncome: number }>('stats', statsFetch))).value.totalIncome).toBe(25);
  115. expect(statsFetch).not.toHaveBeenCalled();
  116. expect((await firstValueFrom(cache.load<{ schedules: { dszt: number }[] }>('companion:today-page1', fetch))).value.schedules[0].dszt).toBe(30);
  117. expect(fetch).toHaveBeenCalledTimes(4);
  118. });
  119. it('discards an in-flight timetable read after a write and lets a fresh read replace it', async () => {
  120. const old = new Subject<{ courses: unknown[]; schedules: { dszt: number }[] }>();
  121. const first = firstValueFrom(cache.load('companion:today', () => old), { defaultValue: null });
  122. cache.invalidateCompanion();
  123. const fresh = { courses: [], schedules: [{ dszt: 30 }] };
  124. await firstValueFrom(cache.load('companion:today', () => of(fresh)));
  125. old.next({ courses: [], schedules: [{ dszt: 0 }] });
  126. expect(await first).toBeNull();
  127. const fetch = jasmine.createSpy('fetch');
  128. expect((await firstValueFrom(cache.load('companion:today', fetch))).value).toEqual(fresh);
  129. expect(fetch).not.toHaveBeenCalled();
  130. });
  131. it('drops persisted companion snapshots from before the fix on the first upgraded visit', async () => {
  132. await firstValueFrom(cache.load('companion:today', () => of({ courses: [], schedules: [{ dszt: 0 }] })));
  133. const saved = JSON.parse(localStorage.getItem(storageKey)!);
  134. delete saved.companionCacheVersion;
  135. localStorage.setItem(storageKey, JSON.stringify(saved));
  136. const upgraded = TestBed.runInInjectionContext(() => new HomeDailyCacheService());
  137. const fetch = jasmine.createSpy('fetch').and.returnValue(of({ courses: [], schedules: [{ dszt: 30 }] }));
  138. expect((await firstValueFrom(upgraded.load<{ schedules: { dszt: number }[] }>('companion:today', fetch))).value.schedules[0].dszt).toBe(30);
  139. expect(fetch).toHaveBeenCalledTimes(1);
  140. });
  141. it('does not cache failures and retains the last success after a failed manual refresh', async () => {
  142. const fetch = jasmine.createSpy('fetch').and.returnValue(throwError(() => new Error('offline')));
  143. await expectAsync(firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch))).toBeRejectedWithError('offline');
  144. expect(localStorage.getItem(storageKey)).toBeNull();
  145. fetch.and.returnValue(of({ totalIncome: 0 }));
  146. await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
  147. fetch.and.returnValue(throwError(() => new Error('offline')));
  148. await expectAsync(firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch, true))).toBeRejectedWithError('offline');
  149. expect((await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch))).value.totalIncome).toBe(0);
  150. });
  151. it('ignores an old account response and a request crossing midnight', async () => {
  152. jasmine.clock().install();
  153. try {
  154. jasmine.clock().mockDate(new Date('2026-10-15T15:59:59Z'));
  155. const old = new Subject<{ totalIncome: number }>();
  156. const first = firstValueFrom(cache.load<{ totalIncome: number }>('stats', () => old), { defaultValue: null });
  157. user.set({ userId: 301, groupId: 3 });
  158. await firstValueFrom(cache.load<{ totalIncome: number }>('stats', () => of({ totalIncome: 80 })));
  159. old.next({ totalIncome: 25 });
  160. expect(await first).toBeNull();
  161. const late = new Subject<{ totalIncome: number }>();
  162. const crossing = firstValueFrom(cache.load<{ totalIncome: number }>('stats', () => late, true), { defaultValue: null });
  163. jasmine.clock().mockDate(new Date('2026-10-15T16:00:00Z'));
  164. late.next({ totalIncome: 90 });
  165. expect(await crossing).toBeNull();
  166. const fetch = jasmine.createSpy('fetch').and.returnValue(of({ totalIncome: 100 }));
  167. expect((await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch))).value.totalIncome).toBe(100);
  168. expect(fetch).toHaveBeenCalledTimes(1);
  169. } finally { jasmine.clock().uninstall(); }
  170. });
  171. it('falls back to memory when storage is unavailable and ignores broken persisted data', async () => {
  172. localStorage.setItem(storageKey, '{broken');
  173. spyOn(Storage.prototype, 'setItem').and.throwError('blocked');
  174. const fetch = jasmine.createSpy('fetch').and.returnValue(of({ totalIncome: 25 }));
  175. await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
  176. await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
  177. expect(fetch).toHaveBeenCalledTimes(1);
  178. });
  179. });