Skip to content

Instantly share code, notes, and snippets.

@jugyo
Created October 18, 2018 22:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jugyo/20fb5b0d9797419c5989dbdb54b96eb3 to your computer and use it in GitHub Desktop.
Save jugyo/20fb5b0d9797419c5989dbdb54b96eb3 to your computer and use it in GitHub Desktop.
const test = require("firebase-functions-test")(
{
databaseURL: "https://my-project.firebaseio.com",
storageBucket: "my-project.appspot.com",
projectId: "my-project",
},
"./testServiceAccountKey.json"
)
const functions = require("../index") // NOTE: This has to be called after `require("firebase-functions-test")(...)`
export { functions }
export const wrap = test.wrap
export const makeDocumentSnapshot = test.firestore.makeDocumentSnapshot
import * as admin from "firebase-admin"
export const db = admin.firestore()
const deleteDoc = async (doc: admin.firestore.DocumentReference | admin.firestore.Firestore) => {
if (doc instanceof admin.firestore.DocumentReference) {
console.debug("Deleting doc: " + doc.path)
await doc.delete()
}
const collections = await doc.getCollections()
await Promise.all(
collections.map(async collection => {
const collectionSnapshot = await collection.get()
const docRefs = []
collectionSnapshot.docs.forEach(documentSnapshot => docRefs.push(documentSnapshot.ref))
await Promise.all(docRefs.map(async docRef => await deleteDoc(docRef)))
})
)
}
const cleanupFirestore = async () => {
await deleteDoc(db)
}
export { cleanupFirestore }
after(() => {
test.cleanup()
})
@jugyo
Copy link
Author

jugyo commented Oct 18, 2018

Example:

import { assert } from "chai"
import "mocha"
import { wrap, db, functions, cleanupFirestore } from "./firebase-test-helpers"

describe("onUserCreate", () => {
  afterEach( async () => {
    await cleanupFirestore()
  })

  it("add data into /users", async () => {
    const uid = "123"
    const email = "user1@example.com"
    await wrap(functions.onUserCreate)({ email, uid })

    const user = (await db.doc(`_users/${uid}`).get()).data()
    assert.equal(user["email"], email)
  })
})

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