如何使用Protobuf编码Cypress存根响应?

时间:2019-02-11 11:02:26

标签: cypress protobuf.js

我有一些固定装置,可以将用protobuf编码消息的服务器存根(我正在使用protobufjs)。我想对固定装置进行解码以轻松地对其进行操作,并让赛普拉斯在将响应发送给客户端之前对存根主体进行编码,我该怎么做?

1 个答案:

答案 0 :(得分:0)

[UPDATE]现在可以作为Cypress plugin

使用

那是我的解决办法:

  • 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");
  });
});