|
| 1 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; |
| 2 | +import { |
| 3 | + isPushSupported, |
| 4 | + isStandalone, |
| 5 | + getPushSubscription, |
| 6 | + subscribeToPush, |
| 7 | + unsubscribeFromPush, |
| 8 | +} from '$lib/utils/push-notifications'; |
| 9 | + |
| 10 | +// ---- Helpers ---------------------------------------------------------------- |
| 11 | + |
| 12 | +function makePushManager(overrides: { |
| 13 | + getSubscription?: ReturnType<typeof vi.fn>; |
| 14 | + subscribe?: ReturnType<typeof vi.fn>; |
| 15 | +} = {}) { |
| 16 | + return { |
| 17 | + getSubscription: overrides.getSubscription ?? vi.fn().mockResolvedValue(null), |
| 18 | + subscribe: overrides.subscribe ?? vi.fn(), |
| 19 | + }; |
| 20 | +} |
| 21 | + |
| 22 | +function installServiceWorkerMock(pushManager = makePushManager()) { |
| 23 | + const swMock = { |
| 24 | + ready: Promise.resolve({ pushManager }), |
| 25 | + register: vi.fn(), |
| 26 | + }; |
| 27 | + Object.defineProperty(navigator, 'serviceWorker', { |
| 28 | + configurable: true, |
| 29 | + value: swMock, |
| 30 | + }); |
| 31 | + return swMock; |
| 32 | +} |
| 33 | + |
| 34 | +/** Replace globalThis.navigator with a Proxy that hides the serviceWorker key. */ |
| 35 | +function hideServiceWorker() { |
| 36 | + const orig = globalThis.navigator; |
| 37 | + const proxy = new Proxy(orig, { |
| 38 | + has(target, key) { |
| 39 | + return key !== 'serviceWorker' && key in target; |
| 40 | + }, |
| 41 | + get(target, key, receiver) { |
| 42 | + if (key === 'serviceWorker') return undefined; |
| 43 | + return Reflect.get(target, key, receiver); |
| 44 | + }, |
| 45 | + }); |
| 46 | + Object.defineProperty(globalThis, 'navigator', { configurable: true, value: proxy }); |
| 47 | + return () => Object.defineProperty(globalThis, 'navigator', { configurable: true, value: orig }); |
| 48 | +} |
| 49 | + |
| 50 | +function setPushManagerPresent(present: boolean) { |
| 51 | + if (present) { |
| 52 | + Object.defineProperty(window, 'PushManager', { configurable: true, value: class PushManager {} }); |
| 53 | + } |
| 54 | + // When false: just ensure PushManager is not defined. Since jsdom does not include |
| 55 | + // PushManager natively, no action is needed — but we guard against a previous test |
| 56 | + // having set it by deleting it via the configurable descriptor. |
| 57 | + else { |
| 58 | + try { |
| 59 | + Object.defineProperty(window, 'PushManager', { configurable: true, value: undefined }); |
| 60 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 61 | + delete (window as unknown as any).PushManager; |
| 62 | + } catch { |
| 63 | + // best-effort — jsdom may not allow deletion |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +function installNotificationMock(permission: NotificationPermission = 'granted') { |
| 69 | + const mock = { |
| 70 | + requestPermission: vi.fn().mockResolvedValue(permission), |
| 71 | + }; |
| 72 | + Object.defineProperty(globalThis, 'Notification', { configurable: true, value: mock }); |
| 73 | + return mock; |
| 74 | +} |
| 75 | + |
| 76 | +function makeSubscription(overrides: Partial<{ |
| 77 | + endpoint: string; |
| 78 | + unsubscribe: ReturnType<typeof vi.fn>; |
| 79 | +}> = {}): PushSubscription { |
| 80 | + return { |
| 81 | + endpoint: overrides.endpoint ?? 'https://example.com/push/endpoint', |
| 82 | + toJSON: () => ({ endpoint: 'https://example.com/push/endpoint' }), |
| 83 | + unsubscribe: overrides.unsubscribe ?? vi.fn().mockResolvedValue(true), |
| 84 | + } as unknown as PushSubscription; |
| 85 | +} |
| 86 | + |
| 87 | +// A valid URL-safe base64 VAPID key (no padding needed for atob) |
| 88 | +const VALID_VAPID_KEY = btoa('a'.repeat(65)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); |
| 89 | + |
| 90 | +// ---- Setup / teardown ------------------------------------------------------- |
| 91 | + |
| 92 | +beforeEach(() => { |
| 93 | + vi.spyOn(console, 'warn').mockImplementation(() => {}); |
| 94 | + vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 95 | + vi.spyOn(console, 'log').mockImplementation(() => {}); |
| 96 | + // Ensure matchMedia exists (jsdom doesn't implement it by default) |
| 97 | + Object.defineProperty(window, 'matchMedia', { |
| 98 | + configurable: true, |
| 99 | + value: vi.fn().mockReturnValue({ matches: false }), |
| 100 | + }); |
| 101 | +}); |
| 102 | + |
| 103 | +afterEach(() => { |
| 104 | + vi.restoreAllMocks(); |
| 105 | +}); |
| 106 | + |
| 107 | +// ---- isPushSupported -------------------------------------------------------- |
| 108 | + |
| 109 | +describe('isPushSupported', () => { |
| 110 | + it('returns false when serviceWorker is not in navigator', () => { |
| 111 | + const restore = hideServiceWorker(); |
| 112 | + expect(isPushSupported()).toBe(false); |
| 113 | + restore(); |
| 114 | + }); |
| 115 | + |
| 116 | + it('returns false when PushManager is not in window', () => { |
| 117 | + installServiceWorkerMock(); |
| 118 | + setPushManagerPresent(false); |
| 119 | + expect(isPushSupported()).toBe(false); |
| 120 | + }); |
| 121 | + |
| 122 | + it('returns true when serviceWorker and PushManager are both present', () => { |
| 123 | + installServiceWorkerMock(); |
| 124 | + setPushManagerPresent(true); |
| 125 | + expect(isPushSupported()).toBe(true); |
| 126 | + }); |
| 127 | +}); |
| 128 | + |
| 129 | +// ---- isStandalone ----------------------------------------------------------- |
| 130 | + |
| 131 | +describe('isStandalone', () => { |
| 132 | + it('returns true when display-mode is standalone', () => { |
| 133 | + Object.defineProperty(window, 'matchMedia', { |
| 134 | + configurable: true, |
| 135 | + value: vi.fn().mockReturnValue({ matches: true }), |
| 136 | + }); |
| 137 | + expect(isStandalone()).toBe(true); |
| 138 | + }); |
| 139 | + |
| 140 | + it('returns true when navigator.standalone is true (iOS)', () => { |
| 141 | + // matchMedia already set to { matches: false } in beforeEach |
| 142 | + Object.defineProperty(navigator, 'standalone', { configurable: true, value: true }); |
| 143 | + expect(isStandalone()).toBe(true); |
| 144 | + Object.defineProperty(navigator, 'standalone', { configurable: true, value: undefined }); |
| 145 | + }); |
| 146 | + |
| 147 | + it('returns false when neither condition is met', () => { |
| 148 | + // matchMedia already set to { matches: false } in beforeEach |
| 149 | + Object.defineProperty(navigator, 'standalone', { configurable: true, value: undefined }); |
| 150 | + expect(isStandalone()).toBe(false); |
| 151 | + }); |
| 152 | +}); |
| 153 | + |
| 154 | +// ---- getPushSubscription ---------------------------------------------------- |
| 155 | + |
| 156 | +describe('getPushSubscription', () => { |
| 157 | + it('returns null when push is not supported', async () => { |
| 158 | + const restore = hideServiceWorker(); |
| 159 | + const result = await getPushSubscription(); |
| 160 | + restore(); |
| 161 | + expect(result).toBeNull(); |
| 162 | + }); |
| 163 | + |
| 164 | + it('returns the subscription from pushManager', async () => { |
| 165 | + const sub = makeSubscription(); |
| 166 | + const pm = makePushManager({ getSubscription: vi.fn().mockResolvedValue(sub) }); |
| 167 | + installServiceWorkerMock(pm); |
| 168 | + setPushManagerPresent(true); |
| 169 | + |
| 170 | + expect(await getPushSubscription()).toBe(sub); |
| 171 | + expect(pm.getSubscription).toHaveBeenCalledOnce(); |
| 172 | + }); |
| 173 | + |
| 174 | + it('returns null when there is no active subscription', async () => { |
| 175 | + const pm = makePushManager({ getSubscription: vi.fn().mockResolvedValue(null) }); |
| 176 | + installServiceWorkerMock(pm); |
| 177 | + setPushManagerPresent(true); |
| 178 | + |
| 179 | + expect(await getPushSubscription()).toBeNull(); |
| 180 | + }); |
| 181 | +}); |
| 182 | + |
| 183 | +// ---- subscribeToPush -------------------------------------------------------- |
| 184 | + |
| 185 | +describe('subscribeToPush', () => { |
| 186 | + it('returns null and warns when push is not supported', async () => { |
| 187 | + const restore = hideServiceWorker(); |
| 188 | + const result = await subscribeToPush(); |
| 189 | + restore(); |
| 190 | + expect(result).toBeNull(); |
| 191 | + expect(console.warn).toHaveBeenCalledWith('[PUSH] Push notifications not supported'); |
| 192 | + }); |
| 193 | + |
| 194 | + it('returns null when notification permission is denied', async () => { |
| 195 | + installServiceWorkerMock(); |
| 196 | + setPushManagerPresent(true); |
| 197 | + installNotificationMock('denied'); |
| 198 | + |
| 199 | + const result = await subscribeToPush(); |
| 200 | + expect(result).toBeNull(); |
| 201 | + expect(console.warn).toHaveBeenCalledWith('[PUSH] Notification permission denied'); |
| 202 | + }); |
| 203 | + |
| 204 | + it('returns null when VAPID key fetch fails', async () => { |
| 205 | + installServiceWorkerMock(); |
| 206 | + setPushManagerPresent(true); |
| 207 | + installNotificationMock('granted'); |
| 208 | + vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(new Response(null, { status: 500 })); |
| 209 | + |
| 210 | + const result = await subscribeToPush(); |
| 211 | + expect(result).toBeNull(); |
| 212 | + expect(console.error).toHaveBeenCalledWith('[PUSH] Failed to fetch VAPID key:', 500); |
| 213 | + }); |
| 214 | + |
| 215 | + it('returns null when no VAPID public key is configured', async () => { |
| 216 | + installServiceWorkerMock(); |
| 217 | + setPushManagerPresent(true); |
| 218 | + installNotificationMock('granted'); |
| 219 | + vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce( |
| 220 | + new Response(JSON.stringify({ publicKey: null }), { status: 200 }) |
| 221 | + ); |
| 222 | + |
| 223 | + const result = await subscribeToPush(); |
| 224 | + expect(result).toBeNull(); |
| 225 | + expect(console.warn).toHaveBeenCalledWith('[PUSH] No VAPID public key configured'); |
| 226 | + }); |
| 227 | + |
| 228 | + it('returns null and unsubscribes locally when server registration fails', async () => { |
| 229 | + const sub = makeSubscription(); |
| 230 | + const pm = makePushManager({ subscribe: vi.fn().mockResolvedValue(sub) }); |
| 231 | + installServiceWorkerMock(pm); |
| 232 | + setPushManagerPresent(true); |
| 233 | + installNotificationMock('granted'); |
| 234 | + vi.spyOn(globalThis, 'fetch') |
| 235 | + .mockResolvedValueOnce(new Response(JSON.stringify({ publicKey: VALID_VAPID_KEY }), { status: 200 })) |
| 236 | + .mockResolvedValueOnce(new Response(null, { status: 500 })); |
| 237 | + |
| 238 | + const result = await subscribeToPush(); |
| 239 | + expect(result).toBeNull(); |
| 240 | + expect(sub.unsubscribe).toHaveBeenCalledOnce(); |
| 241 | + expect(console.error).toHaveBeenCalledWith('[PUSH] Failed to register subscription:', 500); |
| 242 | + }); |
| 243 | + |
| 244 | + it('returns the subscription on the happy path', async () => { |
| 245 | + const sub = makeSubscription(); |
| 246 | + const pm = makePushManager({ subscribe: vi.fn().mockResolvedValue(sub) }); |
| 247 | + installServiceWorkerMock(pm); |
| 248 | + setPushManagerPresent(true); |
| 249 | + installNotificationMock('granted'); |
| 250 | + vi.spyOn(globalThis, 'fetch') |
| 251 | + .mockResolvedValueOnce(new Response(JSON.stringify({ publicKey: VALID_VAPID_KEY }), { status: 200 })) |
| 252 | + .mockResolvedValueOnce(new Response(null, { status: 200 })); |
| 253 | + |
| 254 | + const result = await subscribeToPush(); |
| 255 | + expect(result).toBe(sub); |
| 256 | + expect(console.log).toHaveBeenCalledWith('[PUSH] Successfully subscribed'); |
| 257 | + }); |
| 258 | +}); |
| 259 | + |
| 260 | +// ---- unsubscribeFromPush ---------------------------------------------------- |
| 261 | + |
| 262 | +describe('unsubscribeFromPush', () => { |
| 263 | + it('returns true immediately when there is no existing subscription', async () => { |
| 264 | + installServiceWorkerMock(); |
| 265 | + setPushManagerPresent(true); |
| 266 | + |
| 267 | + expect(await unsubscribeFromPush()).toBe(true); |
| 268 | + }); |
| 269 | + |
| 270 | + it('notifies the server and unsubscribes locally', async () => { |
| 271 | + const sub = makeSubscription({ endpoint: 'https://push.example.com/sub' }); |
| 272 | + const pm = makePushManager({ getSubscription: vi.fn().mockResolvedValue(sub) }); |
| 273 | + installServiceWorkerMock(pm); |
| 274 | + setPushManagerPresent(true); |
| 275 | + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(new Response(null, { status: 200 })); |
| 276 | + |
| 277 | + expect(await unsubscribeFromPush()).toBe(true); |
| 278 | + expect(fetchSpy).toHaveBeenCalledWith('/api/push/unsubscribe', expect.objectContaining({ method: 'POST' })); |
| 279 | + expect(sub.unsubscribe).toHaveBeenCalledOnce(); |
| 280 | + }); |
| 281 | + |
| 282 | + it('still unsubscribes locally when the server request throws', async () => { |
| 283 | + const sub = makeSubscription(); |
| 284 | + const pm = makePushManager({ getSubscription: vi.fn().mockResolvedValue(sub) }); |
| 285 | + installServiceWorkerMock(pm); |
| 286 | + setPushManagerPresent(true); |
| 287 | + vi.spyOn(globalThis, 'fetch').mockRejectedValueOnce(new Error('Network error')); |
| 288 | + |
| 289 | + expect(await unsubscribeFromPush()).toBe(true); |
| 290 | + expect(console.warn).toHaveBeenCalledWith('[PUSH] Server unsubscribe failed:', expect.any(Error)); |
| 291 | + expect(sub.unsubscribe).toHaveBeenCalledOnce(); |
| 292 | + }); |
| 293 | +}); |
0 commit comments