/** * TEST-ONLY unit tests for the Durable Object *scheduling wrapper*. * * `tests/unit/cache-creator.test.ts` covers the DO class itself (debounce, * coalescing, routing, alarm, /clear). This file covers the logic around it — * `scheduleStoreInitialization` in `src/stores/store-initializer.ts`: * * - the `ENABLE_TEST_ROUTES` bypass (no binding access in tests), * - the missing-binding guard, * - the `store-init` instance name, * - `/schedule?regionId=` vs `/schedule` (global) URL construction, * - swallowing scheduling failures so a mutation never fails because of cache. * * The binding is faked through `globalThis.ENV`, so no worker/server is needed. */ import { scheduleStoreInitialization } from '@/src/stores/store-initializer' type FakeEnv = Record function setEnv(env: FakeEnv) { ;(globalThis as any).ENV = env } function makeBinding() { const fetch = jest.fn(async () => new Response('OK')) const stub = { fetch } const get = jest.fn(() => stub) const idFromName = jest.fn(() => 'instance-id') return { binding: { idFromName, get }, idFromName, get, fetch } } afterEach(() => { delete (globalThis as any).ENV }) describe('scheduleStoreInitialization (DO wrapper)', () => { it('does not touch the DO binding when ENABLE_TEST_ROUTES is on', async () => { const { binding, idFromName, get, fetch } = makeBinding() setEnv({ ENABLE_TEST_ROUTES: 'true', CACHE_CREATOR: binding }) await scheduleStoreInitialization(1) expect(idFromName).not.toHaveBeenCalled() expect(get).not.toHaveBeenCalled() expect(fetch).not.toHaveBeenCalled() }) it('returns without throwing when the binding is absent', async () => { setEnv({}) await expect(scheduleStoreInitialization(1)).resolves.toBeUndefined() }) it('targets the single `store-init` instance with the region id', async () => { const { binding, idFromName, get, fetch } = makeBinding() setEnv({ CACHE_CREATOR: binding }) await scheduleStoreInitialization(7) expect(idFromName).toHaveBeenCalledWith('store-init') expect(get).toHaveBeenCalledWith('instance-id') expect(fetch).toHaveBeenCalledWith('https://cache-creator/schedule?regionId=7', { method: 'POST', }) }) it('omits regionId for a global (all-regions) request', async () => { const { binding, fetch } = makeBinding() setEnv({ CACHE_CREATOR: binding }) await scheduleStoreInitialization() expect(fetch).toHaveBeenCalledWith('https://cache-creator/schedule', { method: 'POST' }) }) it('swallows a scheduling failure so the mutation still succeeds', async () => { const fetch = jest.fn(async () => { throw new Error('stub fetch failed') }) setEnv({ CACHE_CREATOR: { idFromName: jest.fn(() => 'id'), get: jest.fn(() => ({ fetch })) } }) await expect(scheduleStoreInitialization(1)).resolves.toBeUndefined() expect(fetch).toHaveBeenCalledTimes(1) }) })