Skip to main content
To create a WebSocket check in Checkly, you’ll need to write a script that establishes a WebSocket connection, sends messages, and validates responses.

Set Up the WebSocket Connection

First, we’ll establish a connection to the WebSocket server. Replace wss://your.websocketserver.com with the URL of your WebSocket server.
websocket.spec.ts

Handle WebSocket Events

Handle the key events like opening the connection, receiving messages, and encountering errors.
websocket.spec.ts

Sending and Receiving Messages

Implement the logic for sending messages and processing the received responses.
websocket.spec.ts

Close the Connection

Ensure to properly close the WebSocket connection after your checks.
websocket.spec.ts

Example

Here’s the complete example script that demonstrates a WebSocket check. It sends a subscription message, prints out the echo’d response, handles different types of incoming messages and closes the connection after 5 seconds. We’ve also added an object assertion to check the data returned from the WebSocket is correct. If the message does not match, the script will throw an error, indicating a discrepancy in the expected data.
websocket.spec.ts
Don’t forget the essentials:
  • Error Handling: Implement robust error handling for scenarios like connection failures and timeouts.
  • Message Validation: Add logic to validate incoming messages to ensure data integrity.
  • Closing Connections: Always close the WebSocket connection gracefully to avoid resource leaks.