Unit Testing Firebase Cloud Function 2nd Gen: makeDataSnapshot refPath does not works

56 views Asked by At

When creating a test using mocha for the following cloud function

//index.js
exports.cloudFnTest = onValueCreated({
  timeoutSeconds: 30,
  memory: '128MiB',
  instance: "test-instance",
  ref: "abc/{uid}"
}, (event) => {
  // Code
});

I wrote the test in the following way:

//index.test.js
require('dotenv').config();
const test = require('firebase-functions-test')({
  databaseURL: 'my-database-url',
  projectId: 'my-project-id',
}, './serviceAccountKey.json');

const myFunctions = require('../index.js'); // relative path to functions code

const { expect } = require('chai');

describe("Test Cloud Function", () => {

  it("Test 1", async () => {
    const wrapped = test.wrap(myFunctions.cloudFnTest);
    const data = {
      ab: 176
    }

    const eventData = {
      data: test.database.makeDataSnapshot(data, 'xyz/live/ui')
    }

    // cloud fn gets executed even for wrong ref as xyz/live/ui does not match abc/{uid}
    p = await wrapped(eventData)
  });

})

I want to know why the cloud function gets executed even for wrong ref as opposed by the cloud function.

How do I test that cloud function should not be executed for this ref: xyz/live/ui

Expected results:

I want the cloud function not be executed for wrong ref and only gets executed for correct ref. How do I do that

1

There are 1 answers

0
Robina Mirbahar On

Modify the test to check the reference before invoking the cloud function

    require('dotenv').config();
const test = require('firebase-functions-test')({
  databaseURL: 'my-database-url',
  projectId: 'my-project-id',
}, './serviceAccountKey.json');

const myFunctions = require('../index.js'); // relative path to functions code

const { expect } = require('chai');

describe("Test Cloud Function", () => {

  it("Should not execute for wrong ref", async () => {
    const wrapped = test.wrap(myFunctions.cloudFnTest);
    const data = {
      ab: 176
    }

    const eventData = {
      data: test.database.makeDataSnapshot(data, 'xyz/live/ui')
    }

    // Ensure the cloud function is not executed for the wrong ref
    await expect(wrapped(eventData)).to.not.be.eventually.fulfilled;
  });

  it("Should execute for correct ref", async () => {
    const wrapped = test.wrap(myFunctions.cloudFnTest);
    const data = {
      ab: 176
    }

    const eventData = {
      data: test.database.makeDataSnapshot(data, 'abc/123') // Provide a valid reference
    }

    // Ensure the cloud function is executed for the correct ref
    await expect(wrapped(eventData)).to.be.eventually.fulfilled;
  });

});

This approach helps validate the behaviour of the cloud function based on the reference provided in the event data.