![](/img/trans.png)
[英]How to share a link to a firebase development environment when using firebase emulators?
[英]How to call a firebase functions from a unit test using Firebase Emulators?
我正在运行 Firebase 模拟器。
我的应用程序可以调用 firebase 云函数,如果允许用户创建自定义用户声明(取决于数据库中的值)
我正在尝试调用该函数:
import * as firebase from '@firebase/testing';
import * as fs from 'fs';
const app = firebase.initializeTestApp({
databaseName: 'mydb',
auth: {
uid: 'useruid'
},
});
describe('Firebase Functions', () => {
beforeEach(async () => {
await firebase.loadDatabaseRules({
databaseName: 'mydb',
rules: fs.readFileSync('database.rules.json', 'utf8'),
});
});
afterAll(async () => {
await Promise.all(firebase.apps().map((app) => app.delete()));
});
const cloudfunction = app.functions().httpsCallable('cloudfunction')
it('throws error if user is not authenticated', async () => {
await firebase.assertFail(cloudfunction())
})
});
这是抛出错误:
错误:错误:预检响应具有无效的 HTTP 状态代码 404
在我看来,你不需要从你的单元测试中调用 firebase,因为它不是你的业务是否正常工作,你需要测试你的业务逻辑,这意味着你将模拟调用firebase 并测试此方法的预期返回值,例如,您可以编写 2 种情况,即发送通知没有错误,第二种情况是 firebase 服务返回失败,对于这 2 种情况,您的代码应该具有适当的行为。 测试 firebase 服务将由在 firebase 上工作的团队完成
为此存在firebase-functions-test 。 这允许您包装您的云函数并直接调用它们,以及为文档更新创建存根。 在模拟器的上下文中运行时,firebase-admin SDK 仍然与模拟器交互。 基本设置可能如下所示(假设打字稿):
// functions/src/test/functions.test.ts
import {expect} from "chai";
import "mocha";
import firebaseFunctionTest from "firebase-functions-test";
import * as cf from "../index";
const projectId = "demo-project";
const test = firebaseFunctionTest({
projectId,
});
after(() => test.cleanup());
describe("cloud functions", () => {
afterEach(async () => {
await test.firestore.clearFirestoreData(projectId);
});
describe("myFunction", () => {
const myFunction = test.wrap(cf.myFunction);
// Create mock data with the admin SDK and test function.
}
}
在您的package.json
您可以放置一个类似的脚本。
"scripts": {
"test:unit": "mocha -r ts-node/register --timeout 5000 --exit src/**/*.test.ts",
"test": "npm run build && npx firebase -P demo-project emulators:exec 'npm run test:unit'",
...
}
您可能还想查看https://github.com/firebase/quickstart-testing/tree/master/unit-test-cloud-functions和https://firebase.google.com/docs/functions/unit - 测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.