// deno-coverage-ignore-file -- test helper, not shipped source /// /// import { fromFileUrl } from '@std/path'; import { ok as assert } from 'node:assert/strict'; import { mock, getTestContext as maybeGetTestContext, type TestContext } from 'node:test'; /** Produces a `Response` (or a rejection) for each intercepted `fetch` call. */ type Responder = () => Response | Promise; /** Resolves a promise after a given delay in milliseconds, optionally resolved with passed value */ export function delay(ms: number, resolveValue?: T) { return new Promise(resolve => setTimeout(() => resolve(resolveValue as T), ms)); } /** Retrieves the current test context, excluding missing or suite contexts. */ function getTestContext() { const t = maybeGetTestContext(); assert(t, 'failed to retrieve test context; must be called from within a test callback'); assert('assert' in t, 'cannot be called within a Suite context; must be called within a test context'); return t; } /** * Stubs `globalThis.fetch` for the lifetime of a `using` binding, restoring the * original on dispose. Defaults to an empty `200` JSON response; override the * response(s) per-test with `respondWith()`. Use `mock` for call assertions. * * @example * ```ts * test('should call fetch', async (t) => { * using f = withFetchMock(); * await api.notify.end(); * t.assert.strictEqual(f.mock.callCount(), 1); * f.assertSnapshot(t); * }); * ``` */ export function withFetchMock(responder: Responder = () => new Response('{}', { status: 200 })) { let respond = responder; let createdSnapshot = false; const t: TestContext = getTestContext(); const { mock: m } = mock.method(globalThis, 'fetch', () => Promise.resolve(respond())); return { mock: m, /** Check fetch mock calls against expected snapshot */ assertSnapshot(expectedCalls = m.callCount()) { t.assert.ok(!createdSnapshot, 'assertSnapshot() cannot be called multiple times (will overwrite previous snapshot)'); const slug = t.fullName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, ''); const path = fromFileUrl(import.meta.resolve(`../__snapshots__/${slug}.snap`)); t.assert.strictEqual(m.callCount(), expectedCalls, 'fetch mock call count does not match expected snapshot'); t.assert.fileSnapshot(m.calls.map(c => c.arguments), path); createdSnapshot = true; }, /** Replace the responder used for subsequent `fetch` calls. */ respondWith(next: Responder) { respond = next; }, /** Helper to get `Request` for a specific `fetch` call index. */ requestForCall(callIndex: number) { t.assert.ok(callIndex >= 0 && callIndex < m.callCount(), 'callIndex is out of bounds'); return new Request(...(m.calls[callIndex].arguments as Parameters)); }, [Symbol.dispose]() { m.restore(); if (m.callCount() === 0 || createdSnapshot) return; t.diagnostic('⚠️ Fetch calls made without assertSnapshot() being called'); } }; }