Skip to content

Instantly share code, notes, and snippets.

@pocha
Created January 1, 2023 23:10
Show Gist options
  • Save pocha/5eb4d1321ee40298e298422881b335e2 to your computer and use it in GitHub Desktop.
Save pocha/5eb4d1321ee40298e298422881b335e2 to your computer and use it in GitHub Desktop.
import { assertFails, assertSucceeds } from "@firebase/rules-unit-testing"
import {
getDoc,
setDoc,
collection,
doc,
connectFirestoreEmulator,
CollectionReference,
DocumentData,
setLogLevel,
updateDoc,
} from "firebase/firestore"
import { describe, expect, test, beforeEach, beforeAll, afterEach } from "@jest/globals"
import { generateName } from "./generate-name-helper"
import { USER_COLLECTION, initialize_firestore_db, get_fresh_collection_ref, ASHISH_ID, BETTS_ID } from "./setup"
beforeAll(async () => {
await initialize_firestore_db()
})
const read_ashish_data = async (user_ref) => {
const response = await getDoc(doc(user_ref, ASHISH_ID))
expect(response.data()?.uid).toBe(ASHISH_ID)
return response.data()
}
const update_ashish_data = async (user_ref, user, name) => {
return setDoc(doc(user_ref, ASHISH_ID), { ...user, name: name })
}
test("user can read/write his data normally", async () => {
const userref_ashish = get_fresh_collection_ref(ASHISH_ID, USER_COLLECTION)
let user = await read_ashish_data(userref_ashish)
//console.log(user)
const new_name = generateName()
await assertSucceeds(update_ashish_data(userref_ashish, user, new_name))
const user1 = await read_ashish_data(userref_ashish)
//console.log(user?.name)
expect(user1?.name).toBe(new_name)
// revert back name
await update_ashish_data(userref_ashish, user, "pocha")
})
test("user can only read but cant update another user data", async () => {
let userref_betts = get_fresh_collection_ref(BETTS_ID, USER_COLLECTION)
let user = await read_ashish_data(userref_betts)
//console.log(user)
await assertFails(update_ashish_data(userref_betts, user, generateName()))
// get a fresh instance else you will get cached data
userref_betts = get_fresh_collection_ref(BETTS_ID, USER_COLLECTION)
let user1 = await read_ashish_data(userref_betts)
//console.log(user1)
expect(user1?.name).toBe(user?.name)
})
test("unauth-user can read user data", async () => {
const user_ref = get_fresh_collection_ref(undefined, USER_COLLECTION)
assertSucceeds(getDoc(doc(user_ref, ASHISH_ID)))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment