Q17 of 20 · GraphQL
What are GraphQL subscriptions, and how do you test them?
GraphQLSeniorgraphqlsubscriptionsreal-timesenior
Short answer
Short answer: Subscriptions are real-time streams, usually over WebSocket — the server pushes data when an event occurs. Test the connection lifecycle, that a triggering event delivers the expected message, ordering/delivery guarantees, and clean teardown on unsubscribe.
Detail
Where queries and mutations are request/response, subscriptions are long-lived: the client subscribes and the server pushes messages as events happen, typically over a WebSocket.
subscription {
orderStatusChanged(orderId: "1001") { status updatedAt }
}
Testing is more involved than request/response:
- Connection: the subscription establishes and acknowledges.
- Delivery: trigger the underlying event (e.g. change the order status via a mutation) and assert the subscriber receives the expected message.
- Filtering: a subscription scoped to
orderId: 1001must NOT receive events for order 1002. - Ordering/dedup: if ordering matters, assert messages arrive in order and aren't duplicated.
- Teardown: unsubscribe/disconnect cleanly, and assert no messages arrive after; check for resource/connection leaks.
- Reconnection: behaviour on dropped connection — does it resume, and are missed messages handled?
Because they're stateful and timing-dependent, subscription tests are flakier — use explicit waits for expected messages with timeouts rather than fixed sleeps.
// WHAT INTERVIEWERS LOOK FOR
Understanding the WebSocket streaming model and testing the full lifecycle — connect, deliver, filter, teardown — not just one message.
// COMMON PITFALL
Testing only that one message arrives, missing filtering, teardown, and reconnection behaviour.