firebase - 如何对用express包装的firebase函数进行单元测试?

标签 firebase google-cloud-functions

通过 firebase 函数,您可以利用 Express 来实现不错的功能,例如中间件等。我使用过 this example获得如何编写由 Express 提供支持的 https firebase 函数的灵感。

但是,我的问题是 the official firebase documentation on how to do unit testing ,不包括 https-express 示例。

所以我的问题是如何单元测试以下函数( typescript )?:

// omitted init. of functions
import * as express from 'express';

const cors = require('cors')({origin: true});
const app = express();
app.use(cors);

// The function to test
app.get('helloWorld, (req, res) => {
   res.send('hello world');
   return 'success';
});

exports.app = functions.https.onRequest(app);

最佳答案

这适用于 Jest

import supertest from 'supertest'
import test from 'firebase-functions-test'
import sinon from 'sinon'
import admin from 'firebase-admin'

let undertest, adminInitStub, request
const functionsTest = test()

beforeAll(() => {
  adminInitStub = sinon.stub(admin, 'initializeApp')
  undertest = require('../index')
  // inject with the exports.app methode from the index.js
  request = supertest(undertest.app)
})

afterAll(() => {
  adminInitStub.restore()
  functionsTest.cleanup()
})

it('get app', async () => {
  let actual = await request.get('/')
  let { ok, status, body } = actual
  expect(ok).toBe(true)
  expect(status).toBeGreaterThanOrEqual(200)
  expect(body).toBeDefined()
})

关于firebase - 如何对用express包装的firebase函数进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49352060/

相关文章:

javascript - Firebase 值已正确提取但无法访问?

android - Flutter 构建 apk 失败

javascript - 在谷歌云功能中包含 npm 模块

javascript - 使用 node.js 从 Google Cloud Function 中的 IncomingMessage 对象读取正文

node.js - 尽管声明了 admin,但显示 "unexpected token admin"错误

javascript - 适用于 Firebase 的 Foreach 云函数

android - Alpha 版和 Beta 版的 Firebase 崩溃报告

firebase - 如何清除firebase缓存?

android - 从后台服务更新 Firebase 数据库

javascript - 如何阻止 Firebase Functions 对每个 Cloud Functions 执行一次本地函数?