你如何单独测试用快递包裹的firebase功能?

Dau*_*eDK 9 firebase google-cloud-functions

使用firebase功能,你可以利用express来实现很好的功能,比如中间件等.我用这个例子来获得如何编写https firebase功能的灵感,由express提供支持.

但是,我的问题是关于如何进行单元测试的官方firebase文档,不包括https-express示例.

所以我的问题是如何对以下函数(打字稿)进行单元测试?:

// 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);
Run Code Online (Sandbox Code Playgroud)

Yor*_*uba 6

这适用于 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()
})
Run Code Online (Sandbox Code Playgroud)

  • 它是索引文件中的导出函数。例如,索引文件中的“exports.api =functions.https.onRequest(app)”将位于测试文件“request = supertest(undertest.api)”中。因此,每个导出的函数都可以使用 'request = supertest(undertest.function_name)' 进行测试 (3认同)

小智 -2

您可以使用邮递员应用程序进行单元测试。输入以下网址和您的项目名称

https://us-central1-your-project.cloudfunctions.net/hello

app.get('/hello/',(req, res) => {
   res.send('hello world');
   return 'success';
});
Run Code Online (Sandbox Code Playgroud)

  • 你好沙拉特,谢谢你的回答。确实,我可以用邮递员进行测试,但答案是特别要求进行单元测试。 (2认同)