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

83 lines
2.6 KiB
TypeScript

/**
* Unit tests for the worker `queue()` dispatcher.
*
* The catch-all branch used to call `handleNotifQueue(batch)` without `await`.
* In workerd that lets the queue handler resolve (and the batch be implicitly
* acked) before the push work finishes, so notifications could be silently
* dropped. These tests pin the awaited behaviour:
* - the handler does not resolve until the fallback promise settles;
* - a fallback rejection propagates so Cloudflare retries the batch.
*/
import worker from '@/worker'
import { handleNotifQueue } from '@/src/lib/queue-consumer'
jest.mock('@/src/app', () => ({
createApp: jest.fn(() => ({ fetch: jest.fn() })),
}))
jest.mock('@/src/jobs/cache-creator', () => ({
CacheCreator: class {},
}))
jest.mock('@/src/lib/worker-init', () => ({
ensureWorkerInit: jest.fn(),
}))
jest.mock('@/src/lib/flash-delivery-cron', () => ({
runFlashDeliveryToggleCron: jest.fn(async () => undefined),
}))
jest.mock('@/src/jobs/order-items-archive', () => ({
CRON_ORDER_ITEMS_ARCHIVE: '30 20 * * *',
runOrderItemsArchiveCron: jest.fn(async () => null),
}))
jest.mock('@/src/lib/queue-consumer', () => ({
handleNotifQueue: jest.fn(async () => undefined),
handleOrderPlacedQueue: jest.fn(async () => undefined),
handleOrderCancelledQueue: jest.fn(async () => undefined),
}))
const mockedHandleNotifQueue = handleNotifQueue as jest.MockedFunction<typeof handleNotifQueue>
const env = {
NOTIF_QUEUE_NAME: 'notif-queue',
ORDER_PLACED_QUEUE_NAME: 'order-placed-queue',
ORDER_CANCELLED_QUEUE_NAME: 'order-cancelled-queue',
} as any
const unknownBatch = { queue: 'some-other-queue', messages: [] } as any
describe('worker queue() fallback', () => {
beforeEach(() => {
jest.clearAllMocks()
})
it('awaits handleNotifQueue for an unknown queue before resolving', async () => {
let release!: () => void
const work = new Promise<void>((resolve) => {
release = resolve
})
mockedHandleNotifQueue.mockReturnValueOnce(work)
const handler = (worker as any).queue(unknownBatch, env, {})
let settled = false
handler.then(() => {
settled = true
})
// Let the handler reach the await; it must still be pending.
await Promise.resolve()
await Promise.resolve()
expect(mockedHandleNotifQueue).toHaveBeenCalledTimes(1)
expect(settled).toBe(false)
release()
await handler
expect(settled).toBe(true)
})
it('propagates a fallback rejection so the batch is retried', async () => {
mockedHandleNotifQueue.mockRejectedValueOnce(new Error('push failed'))
await expect((worker as any).queue(unknownBatch, env, {})).rejects.toThrow('push failed')
})
})