【问题标题】:How to inject dependencies into Firebase/Google Cloud Functions? (unit & integration testing)如何将依赖项注入 Firebase/Google Cloud Functions? (单元和集成测试)
【发布时间】:2020-03-27 07:43:57
【问题描述】:

我不知道我的问题是否真的与 Firebase Cloud Functions 相关,但我在尝试测试 Firebase Cloud Functions 时遇到了这个问题。

假设我有一个用 NodeJS 编写的 Firebase Cloud 函数:

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"
    })
  }
}

通常我有一个接口,可以轻松地模拟我想测试的任何类。

例如,authVerifier 看起来像:

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
}

我正在尝试测试 function.ts,我只能将 res 和 req 传递给它,例如:

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
})

所以问题是:如何模拟 authVerifier.identifyClientRequest(req) 以在 function.ts 和 function.test.ts 中使用不同的实现?

我不太了解 NodeJS/TypeScript,所以我想知道是否可以导入另一个模拟类 authVerifier 进行测试或类似的东西。

【问题讨论】:

    标签: node.js typescript firebase unit-testing google-cloud-functions


    【解决方案1】:

    好的,看来我找到了答案。我会在这里发布以防万一。

    使用 sinonjs,chai 我们可以存根我们的类(在这种情况下为 authVerifier)以返回必要的结果:

    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))
    })
    

    结果是:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-03
      • 2021-06-19
      • 1970-01-01
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      相关资源
      最近更新 更多