如何在本地测试`functions.https.onCall` firebase云功能?

czp*_*lip 11 firebase google-cloud-functions

我在Firebase文档中找不到解决方案.

我想在functions.https.onCall本地测试我的功能.是否可以使用shell或以某种方式将我的客户端(启用firebase SDK)连接到本地服务器?

我想避免每次只是为了测试对我的onCall功能的更改而进行部署.


我的代码

功能:

exports.myFunction = functions.https.onCall((data, context) => {
  // Do something
});
Run Code Online (Sandbox Code Playgroud)

客户:

const message = { message: 'Hello.' };

firebase.functions().httpsCallable('myFunction')(message)
  .then(result => {
    // Do something //
  })
  .catch(error => {
    // Error handler //
  });
Run Code Online (Sandbox Code Playgroud)

小智 28

对于本地,您必须调用(在firebase.initializeApp之后)

firebase.functions().useFunctionsEmulator('http://localhost:5000') 
Run Code Online (Sandbox Code Playgroud)

  • 这有效!我即将进入一个永无止境的部署-编辑-部署循环......这应该在文档指南中。谢谢。 (2认同)
  • 这对我来说不起作用。没有functions().useFunctionsEmulator 的方法。有什么帮助吗? (2认同)

Vil*_*nen 8

有一个简单的技巧,可以简化onCall功能测试。只需将 onCall 函数回调声明为本地函数并进行测试即可:

export const _myFunction = (data, context) => { // <= call this on your unit tests
  // Do something
}

exports.myFunction = functions.https.onCall(_myFunction);
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用您在函数调用中定义的输入来使用普通函数来改变所有情况。


Dou*_*son 6

Callables 只是具有特定格式的 HTTPS 函数。您可以像测试 HTTPS 功能一样进行测试,不同之处在于您必须编写代码以向其提供文档中定义的协议。


Bre*_*ill 5

尽管官方 Firebase Cloud Function 文档尚未更新,但您现在可以将firebase-functions-testonCall函数一起使用。

您可以在他们的存储库中看到一个示例

我已经设法使用 jest 测试了我的 TypeScript 函数,这是一个简短的例子。这里有一些特殊性,比如导入顺序,所以一定要阅读文档:-)

/* functions/src/test/index.test.js */
/* dependencies: Jest and jest-ts */

const admin = require("firebase-admin");
jest.mock("firebase-admin");
admin.initializeApp = jest.fn(); // stub the init (see docs)
const fft = require("firebase-functions-test")();

import * as funcs from "../index";

// myFunc is an https.onCall function
describe("test myFunc", () => {
  // helper function so I can easily test different context/auth scenarios
  const getContext = (uid = "test-uid", email_verified = true) => ({
    auth: {
      uid,
      token: {
        firebase: {
          email_verified
        }
      }
    }
  });
  const wrapped = fft.wrap(funcs.myFunc);

  test("returns data on success", async () => {
    const result = await wrapped(null, getContext());
    expect(result).toBeTruthy();
  });

  test("throws when no Auth context", async () => {
    await expect(wrapped(null, { auth: null })).rejects.toThrow(
      "No authentication context."
    );
  });
});
Run Code Online (Sandbox Code Playgroud)