Testing an async workflow that spans DB and message queue
Verifying side effects that finish after the HTTP response.
Assert the DB row, then verify the queue message via a test consumer or spy, polling with a timeout rather than fixed sleeps.
WHAT THIS TESTS: Whether you can test eventually-consistent, multi-step asynchronous flows where the work continues after the response is sent, and whether you avoid timing-based flakiness.
A GOOD ANSWER COVERS: The challenge is that returning 200 does not mean the queue publish happened. Structure the test to assert each observable outcome. Fire the request with supertest. Then verify the database side: query for the row the handler should have written. Then verify the messaging side using one of two approaches: subscribe a real test consumer to the queue (real RabbitMQ/Kafka in a container) and wait for the expected message, or mock the broker client and assert publish was called with the right payload and routing key. Because these effects are asynchronous, replace fixed sleeps with a polling helper that retries an assertion until it passes or a timeout elapses, which is fast when ready and tolerant of variable latency. For higher fidelity, prefer a containerized broker so serialization and topic/exchange config are exercised.
COMMON WRONG ANSWERS: Asserting only the HTTP status and assuming downstream steps succeeded; sprinkling setTimeout with magic numbers, which is flaky under load and slow when over-padded; mocking everything so the test proves nothing about the real chain; ignoring failure paths where the DB write succeeds but the publish fails.
LIKELY FOLLOW-UPS: How do you guarantee atomicity between the DB write and the publish (outbox pattern, transactional messaging)? How do you test the failure case where publish throws after commit? How do you avoid leaking consumers between tests?
ONE CONCRETE EXAMPLE: After POST /orders returns 201, poll the orders table until the row appears, then await a test consumer that asserts an order.created message with the correct order id arrived on the exchange within a timeout. If either side is missing, the test fails clearly at the broken link.
Read the original → github.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.