通过 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/