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)
有一个简单的技巧,可以简化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)
现在,您可以使用您在函数调用中定义的输入来使用普通函数来改变所有情况。
尽管官方 Firebase Cloud Function 文档尚未更新,但您现在可以将firebase-functions-test与onCall函数一起使用。
我已经设法使用 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)
| 归档时间: |
|
| 查看次数: |
6014 次 |
| 最近记录: |