Offline Jest unit test implementation in firebase functions in Nodejs

Viewed 108

I am trying to implement jest unit testing for firebase functions in my application. I was purely looking at implementing an offline test. I have mocked the request and response objects and am still trying to access some other firebase resources on execution. I am not sure whether I missed any sort of mocking. I intend to not use any firebase-related configuration URLs.

Here is my function and test samples,

randomgenerator.ts

import { https } from "firebase-functions";

export const generateTrickyNumber = https.onRequest(async (req, res) => {
    corsHandler(req, res, async () => {
            try {
                let num =0;
                switch (req.body.type) {
                    case "palindrome":
                       num= await generatePalindrome(req.body.startnumber,req.body.endnumber);
                        break;
                    case "prime":
                       num= await generatePrime(req.body.startnumber,req.body.endnumber);
                        break;
                    default:
                        break;
                }
                return res.status(200).send(num);
            } catch (err) {
                console.log({ err });
                return;
            }
    });
});

randomgenerator.test.ts

import 'jest';
import * as httpMock from 'node-mocks-http';
import * as TestFunctions from 'firebase-functions-test';
const testEnv = TestFunctions();
import { generateTrickyNumber } from "../src/randomgenrator.ts";

describe('generateTrickyNumber ', () => {
    test('it returns a successful response with a valid card', async () => {
        const req = { method: "POST", body: {type:"palindrome", startnumber:1,endnumber:200} };
        const res = {
            send: (payload) => {
                expect(payload).toBe(153)
            },
        };

        await generateTrickyNumber (req as any, res as any);
    });


    test('it returns an error if the method is not passed', async () => {
        const req = { body: { type: "palindrome" } };
        const res = {
            send: (payload) => {
                expect(payload).toBe('Missing value!')
            },
        };

        await generateTrickyNumber (req as any, res as any);
    });
});

Do we need to handle any more mocking for making this successful? Please feel free to suggest.

0 Answers
Related