繁体   English   中英

使用 Firebase CLI shell 测试可调用的云函数

[英]Testing callable cloud functions with the Firebase CLI shell

我一直在firebase functions:shell尝试新的 firebase 可调用云firebase functions:shell我不断收到以下错误

请求的内容类型不正确。

从函数收到的响应:400,{"error":{"status":"INVALID_ARGUMENT","message":"Bad Request"}}

这是我尝试在 shell 上调用此函数的方式

myFunc.post(dataObject)

我也试过这个

myFunc.post().form(dataObject)

但是后来我得到了错误的编码(形式)错误。 dataObject是有效的 JSON。

更新:

我想我需要使用firebase serve来对这些callable https函数进行本地模拟。 数据需要像这样在 post 请求中传递(注意它是如何嵌套在data参数中的)

{
 "data":{
    "applicantId": "XycWNYxqGOhL94ocBl9eWQ6wxHn2",
    "openingId": "-L8kYvb_jza8bPNVENRN"
 }
}

我仍然无法想象的是如何在通过 REST 客户端调用该函数时传递虚拟身份验证信息

我设法让它在函数外壳中运行它:

myFunc.post('').json({"message": "Hello!"})

据我所知,该函数的第二个参数包含所有附加数据。 传递一个包含headers映射的对象,您应该能够指定任何您想要的内容。

myFunc.post("", { headers: { "authorization": "Bearer ..." } });

如果您使用 Express 来处理路由,那么它看起来就像:

myApp.post("/my-endpoint", { headers: { "authorization": "Bearer ..." } });

如果您查看源代码,您会发现它只是一个普通的 https post 函数,带有包含 json web 令牌的身份验证标头,我建议对 https 函数使用单元测试 api并模拟标头方法从测试用户以及请求正文返回令牌

[更新]示例

const firebase = require("firebase");
var config = {
  your config
};
firebase.initializeApp(config);
const test = require("firebase-functions-test")(
  {
    your config
  },
  "your access token"
);
const admin = require("firebase-admin");
const chai = require("chai");
const sinon = require("sinon");

const email = "test@test.test";
const password = "password";
let myFunctions = require("your function file");
firebase
  .auth()
  .signInWithEmailAndPassword(email, password)
  .then(user => user.getIdToken())
  .then(token => {
    const req = {
      body: { data: { your:"data"} },
      method: "POST",
      contentType: "application/json",
      header: name =>
        name === "Authorization"
          ? `Bearer ${token}`
          : name === "Content-Type" ? "application/json" : null,
      headers: { origin: "" }
    };
    const res = {
      status: status => {
        console.log("Status: ", status);
        return {
          send: result => {
            console.log("result", result);
          }
        };
      },
      getHeader: () => {},
      setHeader: () => {}
    };
    myFunctions.yourFunction(req, res);
  })
  .catch(console.error);

CLI 的正确语法已更改为myFunc({"message": "Hello!"})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM