|
| 1 | +/** |
| 2 | + * useGatewayHealth 单元测试(P0-4 网关健康软阻断状态机) |
| 3 | + * |
| 4 | + * @ai-context: mock fetch 覆盖 ok / down / down→恢复放行三态,另含 |
| 5 | + * 网关 URL 未配置视为 down(不发探针)、缓存优先、卸载清定时器、 |
| 6 | + * 卸载后迟到探针响应不写共享缓存。 |
| 7 | + * 每个用例 resetModules 取全新模块注册表,隔离 gatewayHealthCache 的 |
| 8 | + * 模块级缓存,避免用例间互相污染。 |
| 9 | + * @ai-context: Covers ok/down/recovery transitions with mocked fetch, |
| 10 | + * empty-URL short-circuit, cache-first path, interval cleanup and the |
| 11 | + * unmount guard (late probe responses must not write the shared cache); |
| 12 | + * fresh module registry per test isolates the shared health cache. |
| 13 | + */ |
| 14 | +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; |
| 15 | +import { renderHook, act } from '@testing-library/react'; |
| 16 | + |
| 17 | +// jsdom 部分版本缺少 AbortSignal.timeout:补齐以免探针构造参数时抛错 |
| 18 | +if (typeof (AbortSignal as { timeout?: unknown }).timeout !== 'function') { |
| 19 | + (AbortSignal as unknown as { timeout: (ms: number) => AbortSignal }).timeout = |
| 20 | + () => new AbortController().signal; |
| 21 | +} |
| 22 | + |
| 23 | +/** 重置模块注册表后装配全新 store + hook(健康缓存随之归零) */ |
| 24 | +async function renderFresh(gatewayUrl: string) { |
| 25 | + vi.resetModules(); |
| 26 | + const { useSettingsStore } = await import('@/stores/useSettingsStore'); |
| 27 | + useSettingsStore.setState((s) => ({ |
| 28 | + aiConfig: { ...s.aiConfig, gatewayUrl }, |
| 29 | + })); |
| 30 | + const { useGatewayHealth } = await import('./useGatewayHealth'); |
| 31 | + // 预检的异步 setState 可能落在微任务里:整体包进 act 抑制告警 |
| 32 | + return await act(async () => renderHook(() => useGatewayHealth())); |
| 33 | +} |
| 34 | + |
| 35 | +/** 冲刷微任务,让探针 Promise 落定 */ |
| 36 | +const flush = () => act(async () => {}); |
| 37 | + |
| 38 | +beforeEach(() => { |
| 39 | + vi.useFakeTimers(); |
| 40 | +}); |
| 41 | + |
| 42 | +afterEach(() => { |
| 43 | + vi.useRealTimers(); |
| 44 | + vi.unstubAllGlobals(); |
| 45 | + vi.restoreAllMocks(); |
| 46 | +}); |
| 47 | + |
| 48 | +describe('useGatewayHealth', () => { |
| 49 | + it('网关可达:预检后进入 ok', async () => { |
| 50 | + const fetchMock = vi.fn().mockResolvedValue({ ok: true }); |
| 51 | + vi.stubGlobal('fetch', fetchMock); |
| 52 | + const { result } = await renderFresh('http://gateway.test'); |
| 53 | + await flush(); |
| 54 | + expect(result.current.status).toBe('ok'); |
| 55 | + expect(fetchMock).toHaveBeenCalledWith( |
| 56 | + 'http://gateway.test/health/quick', |
| 57 | + expect.objectContaining({ method: 'GET' }), |
| 58 | + ); |
| 59 | + }); |
| 60 | + |
| 61 | + it('网关不可达:进入 down 并挂 15s 自动复检定时器', async () => { |
| 62 | + const fetchMock = vi.fn().mockRejectedValue(new TypeError('Failed to fetch')); |
| 63 | + vi.stubGlobal('fetch', fetchMock); |
| 64 | + const intervalSpy = vi.spyOn(window, 'setInterval'); |
| 65 | + const { result } = await renderFresh('http://gateway.test'); |
| 66 | + await flush(); |
| 67 | + expect(result.current.status).toBe('down'); |
| 68 | + expect(intervalSpy).toHaveBeenCalledWith(expect.any(Function), 15_000); |
| 69 | + }); |
| 70 | + |
| 71 | + it('down→恢复:复检命中后自动放行并清除定时器', async () => { |
| 72 | + const fetchMock = vi.fn() |
| 73 | + .mockRejectedValueOnce(new TypeError('Failed to fetch')) |
| 74 | + .mockResolvedValue({ ok: true }); |
| 75 | + vi.stubGlobal('fetch', fetchMock); |
| 76 | + const clearSpy = vi.spyOn(window, 'clearInterval'); |
| 77 | + const { result } = await renderFresh('http://gateway.test'); |
| 78 | + await flush(); |
| 79 | + expect(result.current.status).toBe('down'); |
| 80 | + |
| 81 | + // 推进 15s 触发复检:探针恢复 → 放行 |
| 82 | + await act(async () => { vi.advanceTimersByTime(15_000); }); |
| 83 | + await flush(); |
| 84 | + expect(result.current.status).toBe('ok'); |
| 85 | + expect(fetchMock).toHaveBeenCalledTimes(2); |
| 86 | + expect(clearSpy).toHaveBeenCalled(); |
| 87 | + }); |
| 88 | + |
| 89 | + it('网关 URL 未配置:视为 down 且不发起探针', async () => { |
| 90 | + const fetchMock = vi.fn(); |
| 91 | + vi.stubGlobal('fetch', fetchMock); |
| 92 | + const { result } = await renderFresh(' '); |
| 93 | + await flush(); |
| 94 | + expect(result.current.status).toBe('down'); |
| 95 | + expect(fetchMock).not.toHaveBeenCalled(); |
| 96 | + }); |
| 97 | + |
| 98 | + it('缓存命中:直接采用缓存结果,不发探针', async () => { |
| 99 | + const fetchMock = vi.fn(); |
| 100 | + vi.stubGlobal('fetch', fetchMock); |
| 101 | + vi.resetModules(); |
| 102 | + const { useSettingsStore } = await import('@/stores/useSettingsStore'); |
| 103 | + useSettingsStore.setState((s) => ({ |
| 104 | + aiConfig: { ...s.aiConfig, gatewayUrl: 'http://gateway.test' }, |
| 105 | + })); |
| 106 | + const cache = await import('@/hooks/gatewayHealthCache'); |
| 107 | + cache.writeHealthCache({ status: 'online', latency: 10 }); |
| 108 | + const { useGatewayHealth } = await import('./useGatewayHealth'); |
| 109 | + const { result } = await act(async () => renderHook(() => useGatewayHealth())); |
| 110 | + await flush(); |
| 111 | + expect(result.current.status).toBe('ok'); |
| 112 | + expect(fetchMock).not.toHaveBeenCalled(); |
| 113 | + }); |
| 114 | + |
| 115 | + it('组件卸载:清除复检定时器', async () => { |
| 116 | + const fetchMock = vi.fn().mockRejectedValue(new TypeError('Failed to fetch')); |
| 117 | + vi.stubGlobal('fetch', fetchMock); |
| 118 | + const clearSpy = vi.spyOn(window, 'clearInterval'); |
| 119 | + const { result, unmount } = await renderFresh('http://gateway.test'); |
| 120 | + await flush(); |
| 121 | + expect(result.current.status).toBe('down'); |
| 122 | + unmount(); |
| 123 | + expect(clearSpy).toHaveBeenCalled(); |
| 124 | + }); |
| 125 | + |
| 126 | + it('组件卸载:迟到探针响应不写共享缓存', async () => { |
| 127 | + // fetch 挂起:探针在途时卸载,随后才 resolve 的响应必须被代际保护丢弃 |
| 128 | + let resolveFetch!: (v: unknown) => void; |
| 129 | + const pending = new Promise((r) => { resolveFetch = r; }); |
| 130 | + const fetchMock = vi.fn().mockReturnValue(pending); |
| 131 | + vi.stubGlobal('fetch', fetchMock); |
| 132 | + const { result, unmount } = await renderFresh('http://gateway.test'); |
| 133 | + // 必须在 renderFresh(内部 resetModules)之后导入,才是 hook 共用的缓存实例 |
| 134 | + const cache = await import('@/hooks/gatewayHealthCache'); |
| 135 | + await flush(); |
| 136 | + expect(result.current.status).toBe('checking'); |
| 137 | + expect(cache.readHealthCache()).toBeNull(); |
| 138 | + unmount(); |
| 139 | + // 卸载后响应才到达:不得写共享缓存(否则陈旧结果扩散给其他消费方) |
| 140 | + resolveFetch({ ok: true, json: async () => ({ status: 'ok' }) }); |
| 141 | + await flush(); |
| 142 | + expect(cache.readHealthCache()).toBeNull(); |
| 143 | + }); |
| 144 | +}); |
0 commit comments