I am developing Firebase Cloud Functions that should react on documents created or updated in Firebase Firestore. I want to write integration tests for these functions so that I can be sure they work as intended but I am stuck when trying to use the Firebase Emulator to execute my tests locally. I want my tests to only run in the emulator and not touch the production database.
According to the code, I have a simple cloud function
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, });
});
I now want to test the function using the emulator so I created an index.test.js file in the test directory with the following contents:
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));
});
});
});
I then try to run the emulator and execute my test script using
firebase emulators:exec "npm test"
where npm test
executes mocha --reporter spec
According to the docs from Run functions locally, writes from Cloud Functions that use the Firebase Admin SDK to write to Cloud Firestore will be sent to the Cloud Firestore emulator if it is running.
Unfortunately, my test is not working and I receive the following warning:
Warning, FIREBASE_CONFIG environment variable is missing. Initializing firebase-admin will fail
as well as errors afterwards:
Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.
These warnings/errors seem to be related to Node 10 FIREBASE_CONFIG not set when Node.js 10 function deployed and GCLOUD_PROJECT environment variable missing from the Node 10 runtime but besides these bugs (which will eventually be fixed at some point), is this the correct way of integration testing Firestore triggers with Cloud functions locally and also on CI?