简体   繁体   中英

How to inject dependencies into Firebase/Google Cloud Functions? (unit & integration testing)

I don't know whether my question is really related to Firebase Cloud Functions, but I came across this problem trying to test my Firebase Cloud Functions.

Let's say I have a Firebase Cloud function written in NodeJS:

function.ts

import * as functions from "firebase-functions"
const admin = require("firebase-admin")

import * as authVerifier from "../../auth/authVerifier"

export default functions.https.onRequest(async (req, res) => {
  let authId
  try {
    authId = await authVerifier.identifyClientRequest(req)
  } catch (err) {
    console.error(`Unauthorized request error: ${err}`)
    return res.status(401).send({
      error: "Unauthorized request"
    })
  }
}

Usually I have an interface and can easily mock any class I want to test it.

And, for example, authVerifier looks like:

authVerifier.ts

import * as express from "express"

export async function identifyClientRequest(req: express.Request) {
  return true // whatever, it doesn't really matter, should be real logic here
}

I'm trying to test function.ts and I only can pass res and req into it, eg:

function.test.ts

it("should verify client identity", async () => {
  const req = {
    method: "PUT"
  }

  const res = { }

  await myFunctions(req as express.Request, res as express.Response)

  // assert that authVerifier.identifyClientRequest(req) called with passed req
})

So the question is: how can I mock authVerifier.identifyClientRequest(req) to use different implementations in function.ts and in function.test.ts?

I don't really know NodeJS/TypeScript, so I wonder if I can import another mock class of authVerifier for test or something like that.

Ok, seems like I found the answer. I'll post it here just in case.

Using sinonjs, chai we can stub our class (authVerifier in that case) to return necessary results:

const chai = require("chai")
const assert = chai.assert
const sinon = require("sinon")

import * as authVerifier from "../../../src/auth/authVerifier"

it("should verify client identity", async () => {
   const req = {
     method: "PUT"
   }

   const res = mocks.createMockResponse()

   const identifyClientRequestStub = sinon.stub(authVerifier, "identifyClientRequest");
   const authVerifierStub = identifyClientRequestStub.resolves("UID")

   await updateUser(req as express.Request, res as express.Response)

   assert.isTrue(authVerifierStub.calledWith(req))
})

And the result is:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM