With firebase functions, you can utilize express to achieve nice functionality, like middleware etc. I have used this example to get inspiration of how to write https firebase functions, powered by express.
However, my issue is that the official firebase documentation on how to do unit testing, does not include a https-express example.
So my question is how to unit test the following function (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);
Firebase and express are common to use together - it's up to use to use them correctly.
On the Firebase console navigation bar, click Test Lab, and then click Get Started -> Run a Robo test. Click Browse, browse to your app APK, and then click Continue. Define your test matrix by selecting which devices, Android API levels, screen orientations and locales you want to test your app against.
Google Firebase is a Google-backed application development software that enables developers to develop iOS, Android and Web apps. Firebase provides tools for tracking analytics, reporting and fixing app crashes, creating marketing and product experiment.
This works with 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()
})
You can use supertest
paired with the guide from Firebase. Below is a very basic example of testing your app, however, you can make it more complex/better by integrating mocha
.
import * as admin from 'firebase-admin'
import * as testFn from 'firebase-functions-test'
import * as sinon from 'sinon'
import * as request from 'supertest'
const test = testFn()
import * as myFunctions from './get-tested' // relative path to functions code
const adminInitStub = sinon.stub(admin, 'initializeApp')
request(myFunctions.app)
.get('/helloWorld')
.expect('hello world')
.expect(200)
.end((err, res) => {
if (err) {
throw err
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With