如何在本地集成测试Firestore的Firebase Cloud Function触发器?

时间:2019-06-09 19:48:41

标签: firebase testing google-cloud-firestore google-cloud-functions firebase-cli

我正在开发Firebase Cloud Functions,这些功能应该对在Firebase Firestore中创建或更新的文档做出反应。 我想为这些功能编写集成测试,以便确保它们可以按预期运行,但是在尝试使用Firebase仿真器在本地执行测试时遇到问题。 我希望我的测试只能在模拟器中运行,而不要接触生产数据库。

根据代码,我有一个简单的云功能

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

exports.increaseNumberOnNewDoc = functions.firestore.document('mycollection/{newdocid}').onCreate((snap, context) => {
  const newDoc = snap.data();

  return snap.ref.set({
    number: 10,
  },
    { merge: true, });
});

我现在想使用仿真器测试该功能,因此我在测试目录中创建了一个index.test.js文件,其内容如下:

const sinon = require('sinon');

// Require firebase-admin so we can stub out some of its methods.
const admin = require('firebase-admin');
const functions = require('firebase-functions');

const test = require('firebase-functions-test')();

describe('Cloud Functions', () => {
  let myFunctions; //, adminInitStub;

  before(() => {
    adminInitStub = sinon.stub(admin, 'initializeApp');
    myFunctions = require('../index.js');
  });

  after(() => {
    test.cleanup();
  });

  describe('Increase Number for newly created docs', () => {
    let oldDatabase;

    before(() => {
      admin.initializeApp({
        projectId: 'sampleid'
      })
    });

    after(() => {
      firebase.clearFirestoreData({
        projectId: "sampleid"
      });
    });

    it('should increase the number for new docs', (done) => {
      return admin.firestore().collection('mycollection').add({
        sampleField: 'Unit Test'
      }).then((onValue) => onValue.get()).then((onNewData) => assert.equal(onNewData['number'], 2));
    });
  });
});

然后我尝试运行仿真器并使用以下命令执行测试脚本

firebase emulators:exec "npm test"

其中npm test执行mocha --reporter spec

根据Run functions locally中的文档,使用Firebase Admin SDK写入Cloud Firestore的Cloud Functions写入(如果正在运行)将被发送到Cloud Firestore模拟器。 < / p>

很遗憾,我的测试无法正常工作,并且收到以下警告:

Warning, FIREBASE_CONFIG environment variable is missing. Initializing firebase-admin will fail

以及之后的错误:

Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.

这些警告/错误似乎与节点10有关 FIREBASE_CONFIG not set when Node.js 10 function deployedGCLOUD_PROJECT environment variable missing from the Node 10 runtime,但除了这些错误(最终将在某个时间点修复)之外,这是否是在本地以及在CI上集成测试Firestore触发器与Cloud函数的正确方法?

0 个答案:

没有答案