【问题标题】:Testing graphql subscriptions with k6使用 k6 测试 graphql 订阅
【发布时间】:2021-02-28 15:03:04
【问题描述】:

是否可以使用 k6 框架测试 graphql 订阅? 我试着去做,但没有太大的成功。也尝试用 k6 websockets 来做,但没有帮助。 谢谢

【问题讨论】:

    标签: load-testing k6


    【解决方案1】:

    Grapqhql Subscription 是基于Websockets,所以理论上可以使用 k6 WebSocket 来实现。

    您也可以参考订阅文档here。 您还可以使用开发人员工具中的 Playground 和 Networks 选项卡来确定发送到服务器的消息/请求。

    这是我实现它的方法:

    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,
                },
              })
            );
          });
        }
      );
    }
      
    

    希望这会有所帮助! ?

    【讨论】:

      猜你喜欢
      • 2019-03-10
      • 2020-11-17
      • 2021-08-20
      • 2017-09-01
      • 2020-01-30
      • 2022-01-21
      • 2017-09-19
      • 2019-12-02
      • 2021-10-09
      相关资源
      最近更新 更多