Knowledgebase

Websockets


Background

Scripting example on how to test websocket APIs.


WebSocket

Testing a WebSocket API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import ws from "k6/ws";
import { check } from "k6";

export default function() {
    var url = "ws://echo.websocket.org";
    var params = { "tags": { "my_tag": "hello" } };

    var res = ws.connect(url, params, function(socket) {
        socket.on('open', function open() {
            console.log('connected');

            socket.setInterval(function timeout() {
              socket.ping();
              console.log("Pinging every 1sec (setInterval test)");
            }, 1000);
        });

        socket.on('ping', function () {
            console.log("PING!");
        });

        socket.on('pong', function () {
            console.log("PONG!");
        });

        socket.on('close', function() {
            console.log('disconnected');
        });

        socket.setTimeout(function () {
            console.log('2 seconds passed, closing the socket');
            socket.close();
        }, 2000);
    });

    check(res, { "status is 101": (r) => r && r.status === 101 });
}