首页 > 解决方案 > 如何将单元测试中的上下文参数发送到在函数模拟器上运行的 firebase 函数

问题描述

我设法启动了 firebase 模拟器并加载了云功能。现在我想写一个测试。

问题我用来chai-http在模拟器中调用该函数,但我没有成功将 a 发送context到该函数。

使用调用函数时chai-http,我看到以下警告和错误:

{"severity":"WARNING","message":"Request body has extra fields: context"} {"severity":"ERROR","message":"Invalid request, unable to process."}

这是测试代码片段:

    it("function_call", async() => {
        await new Promise((resolve, reject) => {
            chai.request(url)
                .post("")
                .send({
                    data: {
                        id: FILE_ID
                    },
                    context: {
                        auth: {
                            uid: USER_ID,
                            token: USER_TOKEN
                        }
                    }
                })
                .end(function(err, res) {
                    console.info(JSON.stringify(res));
                    const payload = JSON.parse(res.text);
                    chai.expect(payload.error).not.null;
                    resolve();
                });

        });
        // expect some data from firestore emulator to be deleted
        const afterCAll = await firestore.collection(`users/${USER_ID}/files/${FILE_ID}`).get();
        chai.expect(afterCAll.empty).is.true;
    });

这是功能代码:

export const doSomething = async(data, context) => {

    console.log("context=" + JSON.stringify(context));
    console.log("context.auth=" + JSON.stringify(context.auth));

}


export const CLOUD_FUNCTION = functions
    .runWith(runtimeOpts)
    .region("REGION")
    .https
    .onCall(doSomething);

并执行测试,我运行:

firebase emulators:exec --project dev-export 'npm test --prefix functions --verbose --debug'

省略参数中的上下文:

            chai.request(url)
                .post("")
                .send({
                    data: {
                        id: FILE_ID
                    }
                })

并且对模拟器的函数调用工作得很好

标签: google-cloud-functionsfirebase-toolschai-http

解决方案


寻找与您提供的错误类似的情况,我发现了一个尝试从上下文获取用户凭据的问题,我注意到他们使用的函数不是异步的,您可能需要检查context, 和authData . 你可以试试:

exports.doSomething = functions.https.onCall((data, context) => {
    const result = context;
    const result= context.auth;
    console.log("context=" + JSON.stringify(result));
    console.log("context.auth=" + JSON.stringify(resultAuth));
}

推荐阅读