我如何使用 Protobuf 编码赛普拉斯存根响应



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

[更新] 它现在可以作为赛普拉斯插件使用


这是我的解决方案:

  • 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文件(其中编码发生在自定义赛普拉斯任务中(
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");
  });
});

最新更新