2

Is it possible to test graphql subscriptions using k6 framework? I tried to do it, but did not have much success. Also tried to do it with k6 websockets, but did not help. Thanks

1 Answers1

5

Grapqhql Subscription is based on Websockets so this is theoretically possible to implement using k6 WebSocket.

You can also refer to the documentation for subscriptions here. You can also use the playground and Networks tab in developer tools to figure out the messages/requests that are sent to the server.

Here is how I was able to achieve it:

import ws from "k6/ws";

export default function(){
const url = "ws://localhost:4000/graphql" // replace with your url
  const token = null; // replace with your auth token
  const operation = `
  subscription PostFeed {
    postCreated {
      author
      comment
    }
  }` // replace with your subscription
  const headers = {
    "Sec-WebSocket-Protocol": "graphql-ws",
  };

  if (token != null) Object.assign(headers,{ Authorization: `Bearer ${token}`});

  ws.connect(
    url,
    {
      headers,
    },
    (socket) => {
      socket.on("message", (msg) => {
        const message = JSON.parse(msg);
        if (message.type == "connection_ack")
          console.log("Connection Established with WebSocket");
        if (message.type == "data") console.log(`Message Received: ${message}`)
      });
      socket.on("open", () => {
        socket.send(
          JSON.stringify({
            type: "connection_init",
            payload: headers,
          })
        );
        socket.send(
          JSON.stringify({
            type: "start",
            payload: {
              query: operation,
            },
          })
        );
      });
    }
  );
}
  

Hope this helps!

Marmik Thakkar
  • 108
  • 1
  • 6