2021年1月17日星期日

How to mock helper functions in Firebase Cloud Functions?

I am currently exploring unit-testing in Firebase Cloud Functions and ran into a use-case that seems like it would be quite frequent but isn't covered by the official documentation.

When writing Cloud Functions for various processes and triggers, we usually use separate helper functions to help us write more reusable code. For example:

// index.ts  import * as functions from "firebase-functions";    function add(num1: number, num2: number) {      return num1 + num2;  }    exports.getSum = functions.https.onCall((data, context) => {      return {          result: add(data.num1, data.num2)      }  })  

When I now want to test getSum, I would have to import it into my test file and make an assertion. However this is where I encounter the issue:

How do I assert that add has been called in getSum? Or better: how do I mock add?

The only workaround I have found so far is exporting add as well and then modifying the code to call this.add instead of just add like so:

// index.ts  import * as functions from "firebase-functions";    export function add(num1: number, num2: number) {      return num1 + num2;  }    exports.getSum = functions.https.onCall((data, context) => {      return {          // @ts-ignore          result: this.add(data.num1, data.num2)      }  })  

However this solution is not ideal as I 1. can't guarantee that this isn't undefined (which is also why I need to // @ts-ignore it) and 2. need to modify the original code to make testing work.

Is there any way to make this work without modifying the functions code? Any best practice for testing these kind of helper functions? Thank you in advance!

Here is the full unit test code I have used for the workaround:

// index.unit.test.ts  const testEnvironment = require("firebase-functions-test")(    {      databaseURL: "",          storageBucket: "",          projectId: "",      },      "credentials.json"    );    const myFunctions = require("../src/index");      describe("getSum", () => {      let wrapper: any, group: any;        beforeAll(() => {          group = myFunctions.addition          wrapper = testEnvironment.wrap(group.getSum);      });        it("adds two numbers", () => {              group.add = jest.fn()                wrapper({ num1: 2, num2: 2})            expect(group.add).toHaveBeenCalled()      });  });    
https://stackoverflow.com/questions/65763396/how-to-mock-helper-functions-in-firebase-cloud-functions January 18, 2021 at 12:52AM

没有评论:

发表评论