代码之家  ›  专栏  ›  技术社区  ›  NoriSte

我如何用一个柏树树桩响应的原buf编码?

  •  0
  • NoriSte  · 技术社区  · 7 年前

    我有一些固定装置来截取用protobuf编码消息的服务器(我正在使用 protobufjs )我想让装置解码,以便于操作它们,并让Cypress在将响应发送给客户之前对存根体进行编码,我该怎么做?

    1 回复  |  直到 7 年前
        1
  •  0
  •   NoriSte    7 年前

    这就是我的解决方案:

    • cypress/plugins/protobufjs/index.js 文件(导入protobuf定义的位置)
    const path = require("path");
    const protobufjs = require("protobufjs");
    const definition = path.join(__dirname, "../../../public/escrow/ui.proto");
    const proto = protobufjs.loadSync(definition);
    module.exports = {
      Status: proto.lookupType("escrow.Status"),
    };
    
    • cypress/plugins/index.js 文件(在自定义Cypress任务中进行编码)
    const { StringDecoder } = require("string_decoder");
    const Messages = require("./protobufjs");
    
    module.exports = on => {
      on("task", {
        protobufEncode: ({ data, encoderName }) => {
          const decoder = new StringDecoder("utf8");
          const bufferValue = Messages[encoderName].encode(data).finish();
          return decoder.end(Buffer.from(bufferValue));
        }
      });
    };
    
    • 在你的测试中
    cy.fixture("YOUR_FIXTURE.json").then(async json => {
      cy.task("protobufEncode", { encoderName: "Status", data: json }).then(result => {
        cy.route({
          headers: {
            "content-type": "application/octet-stream"
          },
          method: "GET",
          response: result,
          status: 200,
          url: `**/YOUR_URL`
        }).as("route_status_one_usb_key");
      });
    });