freshyo/apps/backend/tests/unit/slots-create-cleanup.test.ts
2026-10-20 16:13:09 +05:30

84 lines
2.8 KiB
TypeScript

/**
* Unit test for `admin.slots.createSlot`'s post-create cleanup.
*
* `staleSlotsCleanup` used to be called fire-and-forget. In workerd the
* mutation could return (and the isolate be frozen) before the cleanup ran.
* Because the cleanup is an incremental 20-slot window, a skipped run leaves
* `skuIds` on the slot that fell out of the window permanently. These tests pin
* the awaited behaviour and the existing "cleanup failure must not fail slot
* creation" contract.
*/
import { slotsRouter } from '@/src/trpc/apis/admin-apis/apis/slots'
import { createSlotWithRelations, staleSlotsCleanup } from '@/src/dbService'
import { createSlotsCacheFile } from '@/src/lib/cloud_cache'
jest.mock('@/src/dbService', () => ({
createSlotWithRelations: jest.fn(async () => ({
slot: { id: 1 },
createdSnippets: [],
message: 'Slot created',
})),
staleSlotsCleanup: jest.fn(async () => 1),
}))
jest.mock('@/src/lib/cloud_cache', () => ({
createSlotsCacheFile: jest.fn(async () => 1),
}))
const mockedCleanup = staleSlotsCleanup as jest.MockedFunction<typeof staleSlotsCleanup>
const mockedCreate = createSlotWithRelations as jest.MockedFunction<typeof createSlotWithRelations>
const mockedCache = createSlotsCacheFile as jest.MockedFunction<typeof createSlotsCacheFile>
const input = {
deliveryTime: new Date(Date.now() + 3_600_000).toISOString(),
freezeTime: new Date(Date.now() + 1_800_000).toISOString(),
}
const ctx = { staffUser: { id: 3, regionId: 1 } }
/** tRPC stores the resolver on the procedure's `_def`; call it with a fake ctx. */
const resolveCreateSlot = () => (slotsRouter.createSlot as any)._def.resolver
const drainMicrotasks = () => new Promise<void>((resolve) => setImmediate(resolve))
describe('admin.slots.createSlot cleanup', () => {
beforeEach(() => {
jest.clearAllMocks()
})
it('awaits staleSlotsCleanup before resolving', async () => {
let release!: () => void
const work = new Promise<number>((resolve) => {
release = () => resolve(1)
})
mockedCleanup.mockReturnValueOnce(work)
const run = resolveCreateSlot()({ input, ctx })
let settled = false
run.then(() => {
settled = true
})
await drainMicrotasks()
expect(mockedCreate).toHaveBeenCalledTimes(1)
expect(mockedCache).toHaveBeenCalledTimes(1)
expect(mockedCleanup).toHaveBeenCalledTimes(1)
expect(settled).toBe(false)
release()
await run
expect(settled).toBe(true)
})
it('swallows a cleanup rejection so slot creation still succeeds', async () => {
mockedCleanup.mockRejectedValueOnce(new Error('cleanup failed'))
const result = await resolveCreateSlot()({ input, ctx })
expect(result).toEqual(expect.objectContaining({ message: 'Slot created' }))
expect(mockedCleanup).toHaveBeenCalledTimes(1)
})
})