google-cloud-functions - 如何将单元测试中的上下文参数发送到在函数模拟器上运行的 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
}
})
并且对模拟器的函数调用工作得很好
解决方案
寻找与您提供的错误类似的情况,我发现了一个尝试从上下文获取用户凭据的问题,我注意到他们使用的函数不是异步的,您可能需要检查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));
}
推荐阅读
- javascript - 刷新页面后反应路由器不渲染页面
- php - PHP 上的 Viber 机器人。返回欢迎消息的onConversation问题
- javascript - Mongoose - 如何找到并列出链接到另一个集合的所有实例?
- javascript - 如何检查在一系列随机按钮中单击了哪个按钮?
- java - 你如何简单地通过java从图像中获取像素数据数组?
- html - 如何使用 jinja 动态地将两个元素放在同一行中?
- android - 创建未执行的活动时调用的函数
- reactjs - 如何在遵守钩子规则的同时正确使用 useRouter?
- java - JUnit 5 真的可以注入扩展实例吗?
- python - 尝试将使用 ursina 的 python 脚本转换为可执行文件时出错