puneet

Websocket scripting, assertions, and variables

WebSocket steps use the API Monitoring script engine, including the same scripting lifecycle, assertion framework, and variable handling as HTTP request steps. The difference is how request data and response data are represented for WebSocket connections and messages.

This topic describes how scripting, assertions, and variables work specifically for WebSocket test steps.

The API Monitoring AI Script Assistant also supports WebSocket script changes. We recommend using the AI Script Assistant to manage more advanced scripting logics and manipulations.

Scripting in Websocket steps

Script execution lifecycle

WebSocket steps support the same script execution points as other API Monitoring steps:

  • Pre‑request scripts run before the WebSocket connection is established and messages are sent.

  • Post‑response scripts run after the WebSocket session completes.

Scripts use standard JavaScript and have access to the same built‑in libraries and helpers provided by the Script engine.

request.body in WebSocket steps

In HTTP request steps, request.body contains the raw HTTP request body.

In WebSocket steps, request.body contains a JSON string that represents the messages configured in the WebSocket step UI. These messages are sent by the WebSocket client, in order, after the connection is established.

Each message entry includes metadata such as its name, payload type, and payload content.

If the WebSocket step contains two messages—one JSON message and one text message—request.body looks like this:

Copy
[
  {
    "type": "send",
    "name": "message-1",
    "payload_type": "json",
    "payload": "{\"a\":\"123\"}"
  },
  {
    "type": "send",
    "name": "message-2",
    "payload_type": "text",
    "payload": "hello world"
  }
]

Modifying WebSocket messages in a pre‑request script

You can modify WebSocket messages dynamically before they are sent, for example:

Copy
var messages = JSON.parse(request.body);

for (var i = 0; i < messages.length; i++) {
  var msg = messages[i];

  if (msg.payload_type === "json") {
    var obj = JSON.parse(msg.payload);
    obj.timestamp = new Date().toISOString();
    msg.payload = JSON.stringify(obj);
  } else {
    msg.payload = "updated: " + msg.payload;
  }
}

// Write the updated messages back
request.body = JSON.stringify(messages);

The modified messages are sent by the WebSocket client when the step runs.

Request properties not available for WebSocket steps

The following request properties are not applicable to WebSocket steps:

  • request.method
  • request.form
  • request.files

All other request properties behave the same as in HTTP request steps, including:

  • request.headers

  • request.host

  • request.path

  • request.scheme

  • request.params

  • request.url

  • request.size_bytes

response.body in WebSocket steps

In HTTP request steps, response.body contains the raw HTTP response.

In WebSocket steps, response.body contains a JSON string describing the entire WebSocket session, including:

  • Whether the connection was successfully established

  • Connection and total session duration

  • Sent and received messages

  • Message counts

  • Close code and close reason

An example of response.body structure is shown next:

Copy
{
  "connected": "true",
  "close_code": 1000,
  "close_reason": "Normal Closure",
  "connect_duration_ms": 150,
  "total_duration_ms": 31238,
  "message_count_sent": 2,
  "message_count_received": 2,
  "url": "wss://example.com/ws",
  "sent_messages": [
    {
      "payload": "{\"a\":\"123\"}",
      "payload_type": "json",
      "name": "message-1",
      "sequence": 1,
      "size": 12,
      "error": null
    }
  ],
  "received_messages": [
    {
      "payload": "{\"a\":\"123\"}",
      "message_type_name": "text",
      "sequence": 1,
      "size": 12,
      "error": null
    }
  ]
}

Using response.body in a post‑response script

Here's an example of a response.body in a post-response script:

Copy
var result = JSON.parse(response.body);

// Connection information
var wasConnected = result.connected;
var closeCode = result.close_code;
var closeReason = result.close_reason;

// Message counts
var sentCount = result.message_count_sent;
var receivedCount = result.message_count_received;

// Access a received JSON message
var msg = JSON.parse(result.received_messages[0].payload);
var value = msg.a;

// Store values for later steps
variables.set("close_code", closeCode);
variables.set("session_value", value);
Important: The final entry in received_messages may be a close frame. Close frames do not include a payload field.

Always check for a payload before accessing message content:

Copy
for (var i = 0; i < result.received_messages.length; i++) {
                    var msg = result.received_messages[i];
                    if (!msg.payload) continue;
                    // Process message payload
                }

Asserting on WebSocket results in scripts

You can validate WebSocket results using post‑response scripts and chai.assert, for example:

Copy
var assert = chai.assert;
var result = JSON.parse(response.body);

assert.isTrue(result.connected, "true");
assert.equal(result.close_code, 1000);
assert.equal(result.message_count_sent, 2);

var msg = JSON.parse(result.received_messages[0].payload);
assert.equal(msg.a, "123");
``

Other response properties

The following properties are available and work the same as HTTP steps:

  • response.headers: headers from the WebSocket upgrade handshake

  • response.status: typically 101 (Switching Protocols)

  • response.reason: "Switching Protocols"

  • response.response_time_ms: time taken to establish the WebSocket connection (DNS + TCP + TLS + upgrade) in milliseconds

  • response.size_bytes: response size in bytes

UI‑configured assertions for WebSocket steps

WebSocket steps support assertions configured directly in the test editor UI.

The following assertion sources are available:

SourceDescription
Status CodeHTTP status code from the WebSocket upgrade handshake (typically 101)
HeadersResponse headers from the upgrade handshake
Response Time (ms)Time taken to establish the WebSocket connection
Total Duration (ms)Total duration of the WebSocket session
Connected StatusWhether the WebSocket connection was successfully established
Close CodeWebSocket close code
Close ReasonReason text for the connection close
Message Count SentTotal number of messages sent
Message Count ReceivedTotal number of messages received
Sent Message (JSON)Assert on the payload of a sent message
Received Message (JSON)Assert on the payload of a received message

Asserting on sent and received message payloads

By default, message assertions target the first message (index 0).

  • To assert on a JSON property, enter the property name directly.

  • To assert on the full payload of a text, XML, or HTML message, leave the property field empty.

Examples:

  • city → asserts on the city property of the first message

  • [2].city → asserts on the city property of the third message

  • [1]. → asserts on the full payload of the second message

The same syntax applies to Sent Message (JSON) and Received Message (JSON) assertions.

Tip: For complex message validation, use a post‑response script instead of UI assertions.

Working with variables in WebSocket steps

WebSocket steps support variables in the same way as HTTP request steps. You can set variables in scripts, extract them using the UI, and reuse them in subsequent steps.

Setting variables in scripts

You can create or update variables using variables.set() in pre‑request or post‑response scripts, for example:

Copy
var result = JSON.parse(response.body);

variables.set("ws_connected", result.connected);
variables.set("ws_close_code", result.close_code);

var msg = JSON.parse(result.received_messages[0].payload);
variables.set("session_value", msg.a);

The variables are available to subsequent steps using {{variable_name}} syntax.

Using variables in WebSocket messages

Variables can be referenced in WebSocket message payloads using standard variable syntax, for example:

Copy
{
  "action": "subscribe",
  "id": "{{session_value}}"
}

Variables are resolved at runtime before the message is sent.

UI‑configured variable extraction

You can extract values from WebSocket results into variables directly in the test editor UI.

  • All assertion sources available for WebSocket steps can also be used for extraction.

  • Extracted variables are available in later steps using {{variable_name}}.

UI extraction is useful for simple reuse scenarios without writing scripts.

Variables and message indexing

When extracting values from sent or received messages, message indexes start at 0.

For advanced logic—such as conditional selection or looping over messages—use a post‑response script.