Having issue in writing simple unit test for Google Cloud Function using Chai, Mocha and Sinon although I am referring Google unit testing reference doc but unable to understand it.
Problems
- I'm getting below error message while running unit test.
TypeError: response.status is not a function
- Why do I need to typecast Request and Response object while call function? In Google docs example (Github), they are not doing typecasting.
onCalculate(req as Request, res as unknown as Response);
Objective: Test should pass
onCalculate.ts
import * as functions from "firebase-functions";
export const onCalculate = functions.https.onRequest((request, response) => {
const param1 = request.body.param1;
const param2 = request.body.param2;
response.status(200).send(calculate(param1 as number, param2 as number));
});
/**
* Function to calculate two numbers
* @param {number} param1
* @param {number} param2
* @return {number}
*/
function calculate(param1: number, param2: number): number {
return param1 + param2;
}
onCalculate.spec.ts
import firebase from "firebase-functions-test";
import { Request, Response } from "firebase-functions";
import { stub } from "sinon";
import { assert } from "chai";
import { onCalculate } from "./onCalculate";
const test = firebase();
describe("Calculate", () => {
after(() => {
test.cleanup();
});
it("should return 3", () => {
const req = {
query: {},
body: {
param1: 1,
param2: 2,
},
};
const res = { send: stub() };
onCalculate(req as Request, res as unknown as Response);
assert.ok(res.send.calledOnce);
});
});