启用 App Check 的单元测试可调用 firebase 函数

Unit testing callable firebase function with App Check enabled

我正在尝试根据提供的示例对我的 firebase 可调用云函数进行单元测试。参见 Firebase Example。归结起来是这样的

const { expect } = require("chai");
const admin = require("firebase-admin");

const test = require("firebase-functions-test")({
    projectId: "MYPROJECTID",
});

// Import the exported function definitions from our functions/index.js file
const myFunctions = require("../lib/test");
describe("Unit tests", () => {
  
  after(() => {
    test.cleanup();
  });

  it("tests a simple callable function", async () => {
    const wrapped = test.wrap(myFunctions.sayHelloWorld);

    const data = {
      eventName: "New event"
    };

    // Call the wrapped function with data and context
    const result = await wrapped(data);

    // Check that the result looks like we expected.
    expect(result).to.eql({
      c: 3,
    });
  });

});

问题是该功能受 App Check 保护,如果我尝试对其进行测试,它总是无法通过 App Check 测试:

export const sayHelloWorld = functions.https.onCall(async (data, context) => {

    // context.app will be undefined if the request doesn't include a valid
    // App Check token.
    if (context.app === undefined) {
        throw new functions.https.HttpsError(
            'failed-precondition',
            'The function must be called from an App Check verified app.')
    }

如何包含调试 App Check Token,以便我可以测试功能? 为了在 iOS 上设置 AppCheck,我遵循了这个 guid Enable App Check with App Attest on Apple platforms. When it comes to enforce AppCheck on cloud functions I followed these steps mentioned here. Enable App Check enforcement for Cloud Functions

经过一番挖掘,我发现您需要像这样为包装函数提供一个应用程序对象:

const result = await wrapped(data, {
    auth: {
      uid: "someID",
      token: "SomeToken",
    },
    app: { appId: "SomeAppID" },
  });

希望这对某人有所帮助!