firebase / firebase-functions-test

MIT License
232 stars 48 forks source link

makeDataSnapshot does not create data snapshots in function (online mode) #42

Closed ceejayvarias closed 5 years ago

ceejayvarias commented 5 years ago

Version info

firebase-functions-test: ^0.1.6

firebase-functions: ^2.3.0

firebase-admin: ~6.0.0

Test case

I am trying to write a function that references existing data to make certain calculations before updating other data. Unfortunately makeDataSnapshot does not actually create data in the database. Is there any other way to invoke this data without creating real data or would I need to set it in the before block?

Steps to reproduce

index.js

exports.incrementClassStarted = functions.database
  .ref("/users_progress/{uid}/class_progress/{classId}/started")
  .onCreate((snapshot, context) => {
    const db = admin.database();

    return db
      .ref(`/users_progress/${context.params.uid}/class_progress`)
      .once("value")
      .then(progressSnap => {
        const classProgress = progressSnap.val(); // this returns null

        const startedClassesCount = _.filter(
          classProgress,
          progress => progress.started,
        ).length; // this is 0

        return db.ref(`/users_progress/${context.params.uid}`).update({
          classes_started: startedClassesCount,
        });
      });
  });

index.test.js

const TEST_UID = "tester-uid";
const CLASS_ID = "tester-class-id";

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

  before(() => {
    myFunctions = require('../index');
  });

  after(() => {
    test.cleanup();
    admin.database().ref(`/users_progress/${TEST_UID}`).remove();
  });

  describe('incrementClassStarted', () => {
    it('onCreate: should increment classes_started on users_progress', () => {
      const snap = test.database.makeDataSnapshot(
        "FAKE_TIMESTAMP",
        `/users_progress/${TEST_UID}/class_progress/${CLASS_ID}/started`,
      );

      const wrapped = test.wrap(myFunctions.incrementClassStarted);
      return wrapped(snap, {
        params: {
          uid: TEST_UID,
          classId: CLASS_ID,
        },
      }).then(() =>
        admin
          .database()
          .ref(`/users_progress/${TEST_UID}/classes_started`)
          .once("value")
          .then(createdSnap => {
            assert.equal(createdSnap.val(), 1); // createdSnap.val() === 0
          }),
      );
    });
  });
});

Expected behavior

admin.database().ref("/users_progress/${context.params.uid}/class_progress"). returns { started: "FAKE_TIMESTAMP" }

Actual behavior

admin.database().ref("/users_progress/${context.params.uid}/class_progress"). returns null

ceejayvarias commented 5 years ago

Realized that admin.database() is an external dependency I need to mock.