| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192 |
- import { signal } from '@angular/core';
- import { fakeAsync, tick, TestBed } from '@angular/core/testing';
- import { firstValueFrom, of, Subject, throwError } from 'rxjs';
- import { HomeDailyCacheService } from './home-daily-cache.service';
- import { SessionService } from './session.service';
- const storageKey = 'xiaoshu.learning.homeDaily.v1';
- describe('HomeDailyCacheService', () => {
- let cache: HomeDailyCacheService;
- const user = signal({ userId: 100, groupId: 1 });
- const token = signal('r:daily-cache-test');
- beforeEach(() => {
- localStorage.removeItem(storageKey);
- user.set({ userId: 100, groupId: 1 });
- token.set('r:daily-cache-test');
- TestBed.configureTestingModule({ providers: [{ provide: SessionService, useValue: { user, token } }] });
- cache = TestBed.inject(HomeDailyCacheService);
- });
- afterEach(() => localStorage.removeItem(storageKey));
- it('reuses the same day after navigation and page reload, and forces a manual refresh', async () => {
- const fetch = jasmine.createSpy('fetch').and.returnValue(of({ totalIncome: 25 }));
- const first = await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
- expect(await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch))).toEqual(first);
- const restored = TestBed.runInInjectionContext(() => new HomeDailyCacheService());
- expect(await firstValueFrom(restored.load<{ totalIncome: number }>('stats', fetch))).toEqual(first);
- expect(fetch).toHaveBeenCalledTimes(1);
- fetch.and.returnValue(of({ totalIncome: 30 }));
- expect((await firstValueFrom(restored.load<{ totalIncome: number }>('stats', fetch, true))).value.totalIncome).toBe(30);
- expect(fetch).toHaveBeenCalledTimes(2);
- });
- it('separates Beijing days, accounts and roles', async () => {
- jasmine.clock().install();
- try {
- const fetch = jasmine.createSpy('fetch').and.returnValue(of({ totalIncome: 25 }));
- jasmine.clock().mockDate(new Date('2026-10-31T15:59:59Z'));
- await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
- jasmine.clock().mockDate(new Date('2026-10-31T16:00:00Z'));
- await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
- user.set({ userId: 300, groupId: 3 });
- await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
- user.set({ userId: 300, groupId: 1 });
- await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
- expect(fetch).toHaveBeenCalledTimes(4);
- } finally { jasmine.clock().uninstall(); }
- });
- it('deduplicates concurrent requests and caches success even after navigating away', async () => {
- const response = new Subject<{ totalIncome: number }>();
- const fetch = jasmine.createSpy('fetch').and.returnValue(response);
- const leaving = cache.load<{ totalIncome: number }>('stats', fetch).subscribe();
- leaving.unsubscribe();
- const second = firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch, true));
- response.next({ totalIncome: 50 });
- expect((await second).value.totalIncome).toBe(50);
- expect((await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch))).value.totalIncome).toBe(50);
- expect(fetch).toHaveBeenCalledTimes(1);
- });
- it('shows the cached result immediately when returning during a manual refresh', async () => {
- await firstValueFrom(cache.load('stats', () => of({ totalIncome: 25 })));
- const response = new Subject<{ totalIncome: number }>();
- const manual = firstValueFrom(cache.load('stats', () => response, true));
- const fetch = jasmine.createSpy('fetch');
- expect((await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch))).value.totalIncome).toBe(25);
- expect(fetch).not.toHaveBeenCalled();
- response.next({ totalIncome: 50 });
- expect((await manual).value.totalIncome).toBe(50);
- });
- it('keeps account and companion filter/page snapshots separate after a browser reload', async () => {
- const fetch = jasmine.createSpy('fetch').and.callFake((id: string) => of({ courses: [], schedules: [{ id }] }));
- for (const key of ['companion:today-page1', 'companion:today-page2', 'companion:tomorrow-student2'] as const) {
- await firstValueFrom(cache.load(key, () => fetch(key)));
- }
- await firstValueFrom(cache.load('account', () => of({ profile: { userId: 100 } })));
- const restored = TestBed.runInInjectionContext(() => new HomeDailyCacheService());
- expect((await firstValueFrom(restored.load<{ courses: unknown[]; schedules: { id: string }[] }>('companion:today-page1', () => fetch('unexpected')))).value.schedules[0].id).toBe('companion:today-page1');
- expect((await firstValueFrom(restored.load<{ courses: unknown[]; schedules: { id: string }[] }>('companion:today-page2', () => fetch('unexpected')))).value.schedules[0].id).toBe('companion:today-page2');
- expect(fetch).toHaveBeenCalledTimes(3);
- const accountFetch = jasmine.createSpy('accountFetch');
- expect((await firstValueFrom(restored.load<{ profile: { userId: number } }>('account', accountFetch))).value.profile.userId).toBe(100);
- expect(accountFetch).not.toHaveBeenCalled();
- });
- it('refreshes only on a visible day transition and removes its timer/listener on leave', fakeAsync(() => {
- const visibility = spyOnProperty(document, 'visibilityState', 'get').and.returnValue('visible');
- const refresh = jasmine.createSpy('refresh');
- const stop = cache.watchDay(refresh);
- document.dispatchEvent(new Event('visibilitychange'));
- expect(refresh).not.toHaveBeenCalled();
- const now = Date.now(), midnight = (Math.floor((now + 8 * 3600000) / 86400000) + 1) * 86400000 - 8 * 3600000;
- tick(midnight - now + 101);
- expect(refresh).toHaveBeenCalledTimes(1);
- document.dispatchEvent(new Event('visibilitychange'));
- expect(refresh).toHaveBeenCalledTimes(1);
- visibility.and.returnValue('hidden');
- tick(86400000);
- expect(refresh).toHaveBeenCalledTimes(1);
- visibility.and.returnValue('visible');
- document.dispatchEvent(new Event('visibilitychange'));
- expect(refresh).toHaveBeenCalledTimes(2);
- stop();
- tick(86400000);
- document.dispatchEvent(new Event('visibilitychange'));
- expect(refresh).toHaveBeenCalledTimes(2);
- }));
- it('invalidates every companion page in memory and storage while retaining other daily summaries', async () => {
- const sections = ['companion:today-page1', 'companion:today-page2', 'companion:tomorrow-student2'] as const;
- for (const key of sections) await firstValueFrom(cache.load(key, () => of({ courses: [], schedules: [{ dszt: 0 }] })));
- await firstValueFrom(cache.load('stats', () => of({ totalIncome: 25 })));
- cache.invalidateCompanion();
- const restored = TestBed.runInInjectionContext(() => new HomeDailyCacheService());
- const fetch = jasmine.createSpy('fetch').and.returnValue(of({ courses: [], schedules: [{ dszt: 30 }] }));
- for (const key of sections) {
- expect((await firstValueFrom(restored.load<{ schedules: { dszt: number }[] }>(key, fetch))).value.schedules[0].dszt).toBe(30);
- }
- expect(fetch).toHaveBeenCalledTimes(3);
- const statsFetch = jasmine.createSpy('statsFetch');
- expect((await firstValueFrom(cache.load<{ totalIncome: number }>('stats', statsFetch))).value.totalIncome).toBe(25);
- expect(statsFetch).not.toHaveBeenCalled();
- expect((await firstValueFrom(cache.load<{ schedules: { dszt: number }[] }>('companion:today-page1', fetch))).value.schedules[0].dszt).toBe(30);
- expect(fetch).toHaveBeenCalledTimes(4);
- });
- it('discards an in-flight timetable read after a write and lets a fresh read replace it', async () => {
- const old = new Subject<{ courses: unknown[]; schedules: { dszt: number }[] }>();
- const first = firstValueFrom(cache.load('companion:today', () => old), { defaultValue: null });
- cache.invalidateCompanion();
- const fresh = { courses: [], schedules: [{ dszt: 30 }] };
- await firstValueFrom(cache.load('companion:today', () => of(fresh)));
- old.next({ courses: [], schedules: [{ dszt: 0 }] });
- expect(await first).toBeNull();
- const fetch = jasmine.createSpy('fetch');
- expect((await firstValueFrom(cache.load('companion:today', fetch))).value).toEqual(fresh);
- expect(fetch).not.toHaveBeenCalled();
- });
- it('drops persisted companion snapshots from before the fix on the first upgraded visit', async () => {
- await firstValueFrom(cache.load('companion:today', () => of({ courses: [], schedules: [{ dszt: 0 }] })));
- const saved = JSON.parse(localStorage.getItem(storageKey)!);
- delete saved.companionCacheVersion;
- localStorage.setItem(storageKey, JSON.stringify(saved));
- const upgraded = TestBed.runInInjectionContext(() => new HomeDailyCacheService());
- const fetch = jasmine.createSpy('fetch').and.returnValue(of({ courses: [], schedules: [{ dszt: 30 }] }));
- expect((await firstValueFrom(upgraded.load<{ schedules: { dszt: number }[] }>('companion:today', fetch))).value.schedules[0].dszt).toBe(30);
- expect(fetch).toHaveBeenCalledTimes(1);
- });
- it('does not cache failures and retains the last success after a failed manual refresh', async () => {
- const fetch = jasmine.createSpy('fetch').and.returnValue(throwError(() => new Error('offline')));
- await expectAsync(firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch))).toBeRejectedWithError('offline');
- expect(localStorage.getItem(storageKey)).toBeNull();
- fetch.and.returnValue(of({ totalIncome: 0 }));
- await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
- fetch.and.returnValue(throwError(() => new Error('offline')));
- await expectAsync(firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch, true))).toBeRejectedWithError('offline');
- expect((await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch))).value.totalIncome).toBe(0);
- });
- it('ignores an old account response and a request crossing midnight', async () => {
- jasmine.clock().install();
- try {
- jasmine.clock().mockDate(new Date('2026-10-15T15:59:59Z'));
- const old = new Subject<{ totalIncome: number }>();
- const first = firstValueFrom(cache.load<{ totalIncome: number }>('stats', () => old), { defaultValue: null });
- user.set({ userId: 301, groupId: 3 });
- await firstValueFrom(cache.load<{ totalIncome: number }>('stats', () => of({ totalIncome: 80 })));
- old.next({ totalIncome: 25 });
- expect(await first).toBeNull();
- const late = new Subject<{ totalIncome: number }>();
- const crossing = firstValueFrom(cache.load<{ totalIncome: number }>('stats', () => late, true), { defaultValue: null });
- jasmine.clock().mockDate(new Date('2026-10-15T16:00:00Z'));
- late.next({ totalIncome: 90 });
- expect(await crossing).toBeNull();
- const fetch = jasmine.createSpy('fetch').and.returnValue(of({ totalIncome: 100 }));
- expect((await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch))).value.totalIncome).toBe(100);
- expect(fetch).toHaveBeenCalledTimes(1);
- } finally { jasmine.clock().uninstall(); }
- });
- it('falls back to memory when storage is unavailable and ignores broken persisted data', async () => {
- localStorage.setItem(storageKey, '{broken');
- spyOn(Storage.prototype, 'setItem').and.throwError('blocked');
- const fetch = jasmine.createSpy('fetch').and.returnValue(of({ totalIncome: 25 }));
- await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
- await firstValueFrom(cache.load<{ totalIncome: number }>('stats', fetch));
- expect(fetch).toHaveBeenCalledTimes(1);
- });
- });
|