Skip to content

Instantly share code, notes, and snippets.

@starhoshi
Created April 9, 2018 07:55
Show Gist options
  • Save starhoshi/21d1fb870d485a95c86fe93cfe1ac240 to your computer and use it in GitHub Desktop.
Save starhoshi/21d1fb870d485a95c86fe93cfe1ac240 to your computer and use it in GitHub Desktop.
import * as admin from 'firebase-admin'
import * as fft from 'firebase-functions-test'
const ft = fft()
import * as sinon from 'sinon'
import { makeUppercase, addMessage } from './function'
describe('order', () => {
describe('makeUpperCase', () => {
it('should upper case input and write it to /uppercase', async () => {
const fakeSnaphost = ft.firestore.makeDocumentSnapshot({
original: 'hoge'
}, 'user/1') as FirebaseFirestore.DocumentSnapshot
sinon.stub(fakeSnaphost.ref, 'set').returns(true)
const wrapped = ft.wrap(makeUppercase)
expect(await wrapped(fakeSnaphost)).toBe(true)
})
})
describe('addMessage', () => {
it('should return a 303 redirect', async () => {
const collection = 'messages'
const addParam = { original: 'input' }
const firestoreStub = sinon.stub()
const refStub = sinon.stub()
const addStub = sinon.stub()
sinon.stub(admin, 'firestore').get(() => firestoreStub)
firestoreStub.returns({ collection: refStub })
refStub.withArgs(collection).returns({ add: addStub })
addStub.withArgs(addParam).returns(Promise.resolve({ ref: 'new_ref' }))
const req = { query: { text: 'input' } } as any
const res = {
redirect: (code, url) => {
expect(code).toBe(303)
expect(url).toBe('new_ref')
}
} as any
await addMessage(req, res)
})
})
})
import * as admin from 'firebase-admin'
import * as functions from 'firebase-functions'
export const makeUppercase = functions.firestore.document('/messages/{documentId}')
.onCreate((snap, context) => {
const original = snap.data()!.original
console.log('Uppercasing', context, original)
const uppercase = original.toUpperCase()
console.log(uppercase)
return snap.ref.set({ uppercase }, { merge: true })
})
export const addMessage = functions.https.onRequest((req, res) => {
console.log(req)
console.log(res)
const original = req.query.text
return admin.firestore().collection('messages').add({ original: original }).then((writeResult) => {
return res.json({ result: `Message with ID: ${writeResult.id} added.` })
})
})
@wichopy
Copy link

wichopy commented Apr 9, 2019

Thanks for this.. the firebase docs only have a realtime database example

@michaelmwhite
Copy link

Thank you, this has been incredibly helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment