Overview
WebSocket is a protocol that provides full-duplex communication channels over a single TCP connection. It is commonly used by single-page apps (SPAs) and mobile apps, to add server-push based functionality, which usually improves performance in polling-based solutions.
Load testing WebSockets with k6
An extension with much better and standard API exists
xk6-websockets implements the WebSockets API living standard. While the implementation isn't full, it uses a global event loop instead of local one.
Currently, it's available as an experimental module k6/experimental/websockets. It is also likely that it will at some point become part of the core of k6.
Comparing HTTP-based tests to WebSocket ones, you'll find differences in both structure and inner workings. The primary difference is that instead of continuously looping the main function (export default function() { ... }) over and over, each VU is now runs an asynchronous event loop.
The basic structure of a WebSocket test looks like this:
In this example, the connect() method takes a "run" function as its third parameter. That function should accept a Socket object as its only parameter. The run function forms the basis of the asynchronous event loop.
When the WebSocket connection is created, the run function will be immediately called, all code inside it will be executed (usually code to set up event handlers), and then blocked until the WebSocket connection is closed (by the remote host or by using socket.close()).
Error handling
To catch errors happen during the life of a WebSocket connection, attach a handler to the "error" event:
Timers
To schedule a recurring action, use the socket.setInterval to specify a function to call at a particular interval.
Timeouts
To add a timeout to the WebSocket connection, pass both a handler function and a timeout value (in milliseconds) to the socket.setTimeout function.
In the preceding example, the timeout will close the WebSocket connection after 2 seconds.
Multiple event handlers
You can attach multiple handler functions to an event: