|
9 | 9 | * [test:2026-01-10] PWA 離線功能測試 |
10 | 10 | */ |
11 | 11 |
|
12 | | -import { describe, it, expect, vi } from 'vitest'; |
| 12 | +import { describe, it, expect, vi, beforeAll, afterEach } from 'vitest'; |
| 13 | + |
| 14 | +const { matchPrecacheMock, navigationHandlerRef } = vi.hoisted(() => ({ |
| 15 | + matchPrecacheMock: vi.fn(), |
| 16 | + navigationHandlerRef: { |
| 17 | + current: null as |
| 18 | + | ((params: { event: ExtendableEvent; request: Request }) => Promise<Response>) |
| 19 | + | null, |
| 20 | + }, |
| 21 | +})); |
| 22 | + |
| 23 | +vi.mock('workbox-core', () => ({ |
| 24 | + clientsClaim: vi.fn(), |
| 25 | +})); |
| 26 | + |
| 27 | +vi.mock('workbox-precaching', () => ({ |
| 28 | + cleanupOutdatedCaches: vi.fn(), |
| 29 | + matchPrecache: (...args: unknown[]) => matchPrecacheMock(...args), |
| 30 | + precacheAndRoute: vi.fn(), |
| 31 | +})); |
| 32 | + |
| 33 | +vi.mock('workbox-routing', () => ({ |
| 34 | + NavigationRoute: class NavigationRoute { |
| 35 | + constructor( |
| 36 | + handler: (params: { event: ExtendableEvent; request: Request }) => Promise<Response>, |
| 37 | + ) { |
| 38 | + navigationHandlerRef.current = handler; |
| 39 | + } |
| 40 | + }, |
| 41 | + registerRoute: vi.fn(), |
| 42 | + setCatchHandler: vi.fn(), |
| 43 | +})); |
| 44 | + |
| 45 | +vi.mock('workbox-strategies', () => ({ |
| 46 | + CacheFirst: class CacheFirst {}, |
| 47 | + NetworkOnly: class NetworkOnly {}, |
| 48 | + StaleWhileRevalidate: class StaleWhileRevalidate {}, |
| 49 | +})); |
| 50 | + |
| 51 | +vi.mock('workbox-cacheable-response', () => ({ |
| 52 | + CacheableResponsePlugin: class CacheableResponsePlugin {}, |
| 53 | +})); |
| 54 | + |
| 55 | +vi.mock('workbox-expiration', () => ({ |
| 56 | + ExpirationPlugin: class ExpirationPlugin {}, |
| 57 | +})); |
13 | 58 |
|
14 | 59 | // Mock ServiceWorkerGlobalScope |
15 | 60 | const mockScope = 'https://example.com/ratewise/'; |
@@ -166,7 +211,12 @@ describe('Service Worker Cache Strategies', () => { |
166 | 211 | expect(sourceCode).toContain("matchPrecache('index.html')"); |
167 | 212 | // 防回歸:禁止重新引入 NetworkFirst navigation(cold-start 白屏根因之一)。 |
168 | 213 | expect(sourceCode).not.toContain('new NetworkFirst('); |
169 | | - expect(sourceCode).not.toContain('NAVIGATION_NETWORK_TIMEOUT_MS'); |
| 214 | + // 防回歸:禁止重新引入 3s 全域 navigation timeout(iOS eviction 假離線根因)。 |
| 215 | + expect(sourceCode).not.toContain('const NAVIGATION_NETWORK_TIMEOUT_MS'); |
| 216 | + expect(sourceCode).not.toContain('Promise.race([networkResponse, timeoutFallback])'); |
| 217 | + // case 3(precache 已 miss)允許 8s bounded race,避免 hung network 無限白屏。 |
| 218 | + expect(sourceCode).toContain('const NAVIGATION_FETCH_TIMEOUT_MS = 8000'); |
| 219 | + expect(sourceCode).toContain('navigation-fetch-timeout'); |
170 | 220 | }); |
171 | 221 |
|
172 | 222 | it('should have correct historical rates cache configuration', () => { |
@@ -381,3 +431,207 @@ describe('Service Worker Denylist', () => { |
381 | 431 | expect(isDenied('/faq')).toBe(false); |
382 | 432 | }); |
383 | 433 | }); |
| 434 | + |
| 435 | +describe('handleNavigationRequest', () => { |
| 436 | + const htmlCacheName = 'html-cache'; |
| 437 | + const navigationUrl = 'https://example.com/ratewise/about'; |
| 438 | + const offlineHtml = '<html>offline fallback</html>'; |
| 439 | + |
| 440 | + let htmlCache: { |
| 441 | + match: ReturnType<typeof vi.fn>; |
| 442 | + put: ReturnType<typeof vi.fn>; |
| 443 | + }; |
| 444 | + let cachesOpen: ReturnType<typeof vi.fn>; |
| 445 | + let cachesMatch: ReturnType<typeof vi.fn>; |
| 446 | + |
| 447 | + beforeAll(async () => { |
| 448 | + htmlCache = { |
| 449 | + match: vi.fn(), |
| 450 | + put: vi.fn(), |
| 451 | + }; |
| 452 | + cachesOpen = vi.fn().mockResolvedValue(htmlCache); |
| 453 | + cachesMatch = vi.fn().mockResolvedValue(undefined); |
| 454 | + |
| 455 | + vi.stubGlobal('caches', { |
| 456 | + open: cachesOpen, |
| 457 | + match: cachesMatch, |
| 458 | + keys: vi.fn().mockResolvedValue([]), |
| 459 | + delete: vi.fn(), |
| 460 | + }); |
| 461 | + |
| 462 | + await import('../sw.ts'); |
| 463 | + expect(navigationHandlerRef.current).not.toBeNull(); |
| 464 | + }); |
| 465 | + |
| 466 | + afterEach(() => { |
| 467 | + vi.useRealTimers(); |
| 468 | + vi.clearAllMocks(); |
| 469 | + cachesOpen.mockResolvedValue(htmlCache); |
| 470 | + cachesMatch.mockResolvedValue(undefined); |
| 471 | + htmlCache.match.mockReset(); |
| 472 | + htmlCache.put.mockReset(); |
| 473 | + matchPrecacheMock.mockReset(); |
| 474 | + }); |
| 475 | + |
| 476 | + function createNavigationEvent(): ExtendableEvent { |
| 477 | + return { waitUntil: vi.fn() } as unknown as ExtendableEvent; |
| 478 | + } |
| 479 | + |
| 480 | + function createOfflineFallbackResponse(): Response { |
| 481 | + return new Response(offlineHtml, { |
| 482 | + status: 200, |
| 483 | + headers: { 'Content-Type': 'text/html; charset=utf-8' }, |
| 484 | + }); |
| 485 | + } |
| 486 | + |
| 487 | + it('case 2: precache hit resolves instantly without timer dependency', async () => { |
| 488 | + vi.useFakeTimers(); |
| 489 | + |
| 490 | + const precachedShell = new Response('<html>precached index</html>', { |
| 491 | + status: 200, |
| 492 | + headers: { 'Content-Type': 'text/html; charset=utf-8' }, |
| 493 | + }); |
| 494 | + |
| 495 | + htmlCache.match.mockResolvedValue(undefined); |
| 496 | + matchPrecacheMock.mockImplementation((url: string) => |
| 497 | + Promise.resolve(url === 'index.html' ? precachedShell : null), |
| 498 | + ); |
| 499 | + vi.stubGlobal( |
| 500 | + 'fetch', |
| 501 | + vi.fn(() => new Promise<Response>(() => undefined)), |
| 502 | + ); |
| 503 | + |
| 504 | + const handler = navigationHandlerRef.current!; |
| 505 | + const response = await handler({ |
| 506 | + event: createNavigationEvent(), |
| 507 | + request: new Request(navigationUrl), |
| 508 | + }); |
| 509 | + |
| 510 | + expect(response).toBe(precachedShell); |
| 511 | + expect(matchPrecacheMock).toHaveBeenCalledWith('index.html'); |
| 512 | + await vi.runAllTimersAsync(); |
| 513 | + }); |
| 514 | + |
| 515 | + it('case 3: network resolves within 8s returns network response without orphan timer', async () => { |
| 516 | + vi.useFakeTimers(); |
| 517 | + |
| 518 | + const networkHtml = '<html>network fresh</html>'; |
| 519 | + const networkResponse = new Response(networkHtml, { |
| 520 | + status: 200, |
| 521 | + headers: { 'Content-Type': 'text/html; charset=utf-8' }, |
| 522 | + }); |
| 523 | + |
| 524 | + htmlCache.match.mockResolvedValue(undefined); |
| 525 | + matchPrecacheMock.mockImplementation((url: string) => |
| 526 | + Promise.resolve(url === 'index.html' ? null : null), |
| 527 | + ); |
| 528 | + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(networkResponse.clone())); |
| 529 | + |
| 530 | + const orphanRejections: unknown[] = []; |
| 531 | + const onRejection = (reason: unknown) => { |
| 532 | + orphanRejections.push(reason); |
| 533 | + }; |
| 534 | + process.on('unhandledRejection', onRejection); |
| 535 | + |
| 536 | + try { |
| 537 | + const handler = navigationHandlerRef.current!; |
| 538 | + const response = await handler({ |
| 539 | + event: createNavigationEvent(), |
| 540 | + request: new Request(navigationUrl), |
| 541 | + }); |
| 542 | + const body = await response.text(); |
| 543 | + |
| 544 | + expect(body).toBe(networkHtml); |
| 545 | + expect(matchPrecacheMock).toHaveBeenCalledWith('index.html'); |
| 546 | + expect(matchPrecacheMock).not.toHaveBeenCalledWith('offline.html'); |
| 547 | + |
| 548 | + await vi.advanceTimersByTimeAsync(8000); |
| 549 | + expect(orphanRejections).toHaveLength(0); |
| 550 | + } finally { |
| 551 | + process.off('unhandledRejection', onRejection); |
| 552 | + } |
| 553 | + }); |
| 554 | + |
| 555 | + it('case 3: timeout fallback still waitUntils late network fetch to html-cache', async () => { |
| 556 | + vi.useFakeTimers(); |
| 557 | + |
| 558 | + const offlineFallback = createOfflineFallbackResponse(); |
| 559 | + const networkHtml = '<html>late network</html>'; |
| 560 | + let resolveFetch!: (value: Response) => void; |
| 561 | + const fetchPromise = new Promise<Response>((resolve) => { |
| 562 | + resolveFetch = resolve; |
| 563 | + }); |
| 564 | + |
| 565 | + htmlCache.match.mockResolvedValue(undefined); |
| 566 | + matchPrecacheMock.mockImplementation((url: string) => { |
| 567 | + if (url === 'index.html') return Promise.resolve(null); |
| 568 | + if (url === 'offline.html') return Promise.resolve(offlineFallback); |
| 569 | + return Promise.resolve(null); |
| 570 | + }); |
| 571 | + vi.stubGlobal( |
| 572 | + 'fetch', |
| 573 | + vi.fn(() => fetchPromise), |
| 574 | + ); |
| 575 | + |
| 576 | + const waitUntilMock = vi.fn(); |
| 577 | + const event = { waitUntil: waitUntilMock } as unknown as ExtendableEvent; |
| 578 | + const handler = navigationHandlerRef.current!; |
| 579 | + const responsePromise = handler({ |
| 580 | + event, |
| 581 | + request: new Request(navigationUrl), |
| 582 | + }); |
| 583 | + |
| 584 | + await vi.advanceTimersByTimeAsync(8000); |
| 585 | + |
| 586 | + const response = await responsePromise; |
| 587 | + const body = await response.text(); |
| 588 | + |
| 589 | + expect(body).toBe(offlineHtml); |
| 590 | + expect(waitUntilMock).toHaveBeenCalledTimes(1); |
| 591 | + |
| 592 | + resolveFetch( |
| 593 | + new Response(networkHtml, { |
| 594 | + status: 200, |
| 595 | + headers: { 'Content-Type': 'text/html; charset=utf-8' }, |
| 596 | + }), |
| 597 | + ); |
| 598 | + const waitUntilPromise = waitUntilMock.mock.calls[0]?.[0] as Promise<unknown> | undefined; |
| 599 | + await waitUntilPromise; |
| 600 | + |
| 601 | + expect(htmlCache.put).toHaveBeenCalled(); |
| 602 | + }); |
| 603 | + |
| 604 | + it('case 3: hung network falls back to offline.html after bounded timeout', async () => { |
| 605 | + vi.useFakeTimers(); |
| 606 | + |
| 607 | + const offlineFallback = createOfflineFallbackResponse(); |
| 608 | + |
| 609 | + htmlCache.match.mockResolvedValue(undefined); |
| 610 | + matchPrecacheMock.mockImplementation((url: string) => { |
| 611 | + if (url === 'index.html') return Promise.resolve(null); |
| 612 | + if (url === 'offline.html') return Promise.resolve(offlineFallback); |
| 613 | + return Promise.resolve(null); |
| 614 | + }); |
| 615 | + cachesMatch.mockResolvedValue(undefined); |
| 616 | + vi.stubGlobal( |
| 617 | + 'fetch', |
| 618 | + vi.fn(() => new Promise<Response>(() => undefined)), |
| 619 | + ); |
| 620 | + |
| 621 | + const handler = navigationHandlerRef.current!; |
| 622 | + const responsePromise = handler({ |
| 623 | + event: createNavigationEvent(), |
| 624 | + request: new Request(navigationUrl), |
| 625 | + }); |
| 626 | + |
| 627 | + await vi.advanceTimersByTimeAsync(8000); |
| 628 | + |
| 629 | + const response = await responsePromise; |
| 630 | + const body = await response.text(); |
| 631 | + |
| 632 | + expect(body).toBe(offlineHtml); |
| 633 | + expect(matchPrecacheMock).toHaveBeenCalledWith('index.html'); |
| 634 | + expect(matchPrecacheMock).toHaveBeenCalledWith('offline.html'); |
| 635 | + expect(cachesOpen).toHaveBeenCalledWith(htmlCacheName); |
| 636 | + }); |
| 637 | +}); |
0 commit comments