freshyo/apps/backend/tests/unit/initialize-all-stores.test.ts
2026-10-20 16:13:09 +05:30

81 lines
2.7 KiB
TypeScript

/**
* Unit tests for `initializeAllStores`' cache-generation step.
*
* `initializeAllStores` used to call `createAllCacheFiles(...)` while returning
* immediately (fire-and-forget). In workerd that can let the caller (the
* CacheCreator alarm, or the Node startup path) finish while the S3 upload and
* CDN purge are still in flight. These tests pin the awaited behaviour:
* - the function does not resolve until cache generation settles;
* - a cache-generation failure is swallowed so store initialization still
* resolves (the existing `.catch` contract).
*/
import { initializeAllStores } from '@/src/stores/store-initializer'
import { createAllCacheFiles } from '@/src/lib/cloud_cache'
jest.mock('@/src/dbService', () => ({
getAllRegions: jest.fn(async () => [{ id: 1 }, { id: 2 }]),
}))
jest.mock('@/src/lib/roles-manager', () => ({
__esModule: true,
default: { fetchRoles: jest.fn(async () => undefined) },
}))
jest.mock('@/src/lib/const-store', () => ({
computeConstants: jest.fn(async () => undefined),
}))
jest.mock('@/src/stores/product-store', () => ({
initializeProducts: jest.fn(async () => undefined),
}))
jest.mock('@/src/stores/product-tag-store', () => ({
initializeProductTagStore: jest.fn(async () => undefined),
}))
jest.mock('@/src/stores/slot-store', () => ({
initializeSlotStore: jest.fn(async () => undefined),
}))
jest.mock('@/src/stores/banner-store', () => ({
initializeBannerStore: jest.fn(async () => undefined),
}))
jest.mock('@/src/lib/cloud_cache', () => ({
createAllCacheFiles: jest.fn(async () => []),
}))
const mockedCreateAllCacheFiles = createAllCacheFiles as jest.MockedFunction<typeof createAllCacheFiles>
const drainMicrotasks = () => new Promise<void>((resolve) => setImmediate(resolve))
describe('initializeAllStores cache generation', () => {
beforeEach(() => {
jest.clearAllMocks()
})
it('awaits createAllCacheFiles before resolving', async () => {
let release!: () => void
const work = new Promise<any[]>((resolve) => {
release = () => resolve([])
})
mockedCreateAllCacheFiles.mockReturnValueOnce(work)
const run = initializeAllStores(1)
let settled = false
run.then(() => {
settled = true
})
await drainMicrotasks()
expect(mockedCreateAllCacheFiles).toHaveBeenCalledTimes(1)
expect(mockedCreateAllCacheFiles).toHaveBeenCalledWith(1)
expect(settled).toBe(false)
release()
await run
expect(settled).toBe(true)
})
it('swallows a cache-generation failure so store init still resolves', async () => {
mockedCreateAllCacheFiles.mockRejectedValueOnce(new Error('s3 down'))
await expect(initializeAllStores(1)).resolves.toBeUndefined()
})
})