无法使用 firebase-functions-test 获取 v2 函数中的参数

问题描述 投票:0回答:1

我有一个 v2 onCall 函数:

import { HttpsError, onCall } from "firebase-functions/v2/https";
import { logger } from "firebase-functions";
import { getAuth } from "firebase-admin/auth";

const createAccount = onCall((request) => {
    return getAuth()
        .createUser({
            email: request.data.email,
            emailVerified: false,
            password: request.data.password,
            disabled: false,
        })
        .then((user) => {
            logger.log(`Successfully created new user ${user.uid} (${request.data.email})`);
            return `Successfully created new user ${request.data.email}`;
        })
        .catch((error) => {
            // Error handling (long code withheld)...
        });
});

我正在使用

firebase-functions-test
和摩卡 (
mocha --reporter spec
) 对其进行测试,如 文档指定的那样:

it('Should complete', (done) => {

    const data = test.firestore.makeDocumentSnapshot({ email: "[email protected]", password: "password12345" }, 'test/123');

    const wrapped = test.wrap(functions.createAccount);
    wrapped(data);

    done();
})

运行良好,完成时没有错误并创建一个新的用户帐户。但在控制台上,我注意到它不断创建匿名帐户。结果函数没有获取参数,所以我在 onCall 函数的开头添加了以下代码:

if (!request.data.email) {
    throw new HttpsError('invalid-argument', "Must provide an email");
}
if (!request.data.password) {
    throw new HttpsError('invalid-argument', "Must provide a password");
}

并且它不断抛出错误,因为

request.data.email
未定义。我已经尝试了我能找到的每个选项(更改文档路径、更改对象的输入、将“params”对象添加到选项、对输入进行字符串化以及 this 示例),但是
request.data
从来没有我指定的参数。如何正确添加参数?

我的配置文件:

package.json

{
  "name": "functions",
  "type": "module",
  "scripts": {
    "build": "tsc",
    "build:watch": "tsc --watch",
    "serve": "npm run build && firebase emulators:start --only functions",
    "shell": "npm run build && firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log",
    "test": "mocha --reporter spec"
  },
  "engines": {
    "node": "20"
  },
  "main": "lib/index.js",
  "dependencies": {
    "firebase": "^10.7.1",
    "firebase-admin": "^11.11.1",
    "firebase-functions": "^4.3.1",
    "ts-node": "^10.9.2",
    "tsx": "^4.7.0",
    "yup": "^1.3.3"
  },
  "devDependencies": {
    "firebase-functions-test": "^3.1.0",
    "mocha": "^10.2.0",
    "typescript": "^4.9.0"
  },
  "private": true
}

.mocharc.json

{
  "extensions": ["ts"],
  "spec": ["test/**/*.ts"],
  "node-option": [
    "experimental-specifier-resolution=node",
    "import=tsx/esm"
  ]
}
javascript firebase unit-testing google-cloud-functions mocha.js
1个回答
0
投票

看起来

firebase-functions-test
还不支持v2函数,只是将它们视为v1函数。参数仍然传递,但是需要访问“私有”
_fieldsproto
字段:

import { onCall } from "firebase-functions/v2/https";

const createAccount = onCall((request) => {

    const email = request.data.email ?? request._fieldsProto.email.stringValue;

    // ...
}

由于这需要编辑生产代码以进行测试,因此我建议使用 v1 函数

© www.soinside.com 2019 - 2024. All rights reserved.