首页 > 解决方案 > 无法使用 Firebase 云功能存根管理功能

问题描述

当我尝试在我的数据上调用包装函数时,我收到以下错误消息:

错误:默认 Firebase 应用不存在。确保在使用任何 Firebase 服务之前调用 initializeApp()。

我的代码如下所示:

const {expect} = require("chai")
const sinon = require('sinon');
const admin = require('firebase-admin');
const test = require('firebase-functions-test')()

describe('Unit tests', () => {
    let myFunctions, adminInitStub;

    before(() => {
        adminInitStub = sinon.stub(admin, 'initializeApp');
        myFunctions = require('../index');
    });
    after(() => {
        adminInitStub.restore();
        test.cleanup()
    })
    describe("addSchoolVerified", () => {
        it('should create school with value-pair "name":"placeholder"', async () => {
            const wrapped = test.wrap(myFunctions.addSchoolVerified)

            const data = {
                name: 'placeholder'
            }

            // Call the wrapped function with data and context
            const result = await wrapped(data)

            // Check that the result looks like we expected.
            expect(result).to.not.be.undefined
        })
    })
})

到目前为止,我尝试使用不同的方式调用存根,比如在 before() 之外调用它,但这也确实导致了上述错误

index.js

const functions = require('firebase-functions')

const admin = require('firebase-admin')
admin.initializeApp()

exports.addSchoolVerified = functions.https.onCall(async (data, context) => {
    /*if (!context.auth) {
        // Throwing an HttpsError so that the client gets the error details.
        throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' +
            'while authenticated.');
    }*/
    const schoolName = data.name;
    const writeResult = await admin.firestore().collection('Schule').add({name: schoolName})
    return {result: `School with id: ${writeResult.id} successfully added.`}
});

标签: javascriptnode.jsfirebasegoogle-cloud-functionschai

解决方案


推荐阅读