How to Contract Test Async Message Queues
Message pacts verify the payload a consumer handler can process, decoupled from any specific queue technology like Kafka or RabbitMQ.
The consumer test asserts its handler accepts a described message. The provider test proves the producer emits a message matching that description. The transport itself is not part of the contract.
Steps
- Use
MessageConsumerPactto describe the message the handler expects. - Assert your real handler processes the generated example.
- On the producer side, verify the message it builds satisfies the pact.
Message consumer test
message.consumer.test.js
const { MessageConsumerPact, synchronousBodyHandler } = require('@pact-foundation/pact');
const messagePact = new MessageConsumerPact({ consumer: 'notifier', provider: 'orders-events' });
await messagePact
.expectsToReceive('an order shipped event')
.withContent({ type: 'order.shipped', id: 42 })
.verify(synchronousBodyHandler(handleOrderShipped));Gotchas
- Message pacts describe the payload only, so wiring the actual topic and serializer still needs its own test.
- Keep the handler pure enough that it can run against the example message in isolation.
Related guides
How to Set Up Provider States for VerificationImplement provider states so the provider can seed data before each interaction is verified, matching the giv…
How to Contract Test a GraphQL APIContract test a GraphQL API with Pact by treating the single POST /graphql endpoint as an HTTP interaction an…