Tests (Admin)🧪
This section discusses how to use Firelord with emulator and jest
.
Remember to prepare script like this:
{
"test": "firebase emulators:exec --only firestore \"jest --forceExit\""
}
note
This is not a tutorial about firebase emulator or jest
, we assume you already know them.
info
Emulator forces all tests to run in emulator eventhough tests are not connected to emulator via connectFirestoreEmulator
.
This is true for Admin and partially true for Web.
With Emulator
info
Firestore Admin doesnt require @firebase/rules-unit-testing
to test because admin bypass all rules.
import {
setDoc,
getFirelord,
getDocs,
query,
where,
onSnapshot,
runTransaction,
writeBatch,
FirelordRef,
MetaTypeCreator,
getFirestore,
} from 'firelordjs'
import { initializeApp, ServiceAccount } from 'firebase-admin/app'
// for cloud function
initializeApp({ projectId: 'forTestJustUseRandomId' })
type User = MetaTypeCreator<{ name: string; age: number }, 'User', string>
const firestore = getFirestore()
const userRef = getFirelord<User>()('User')
describe('test with jest', () => {
it('test basic operation like setDoc, updateDoc, addDoc, deleteDoc etc etc', async () => {
const ref = userRef.doc('user1')
await setDoc(ref, { age: 30, name: 'John' })
// some other operations
// do your assertion here...
})
it('test getDocs', async () => {
const querySnapshot = await getDocs(
query(userRef.collectionGroup(), where('name', '==', 'abc'))
)
// do your assertion here...
})
it('test onSnapshot', done => {
expect.hasAssertions()
const unsub = onSnapshot(
query(userRef.collection(), where('age', '>', 10)),
async querySnapshot => {
// do your assertion here...
unsub()
done()
}
)
})
it('test transaction operations', async () => {
const result = await runTransaction(async transaction => {
await transaction.update(userRef.doc('user1'), {
age: 20,
})
// some other operations
return something
})
// do your assertion here...
})
it('test batch operations', async () => {
const batch = writeBatch()
batch.delete(userRef.doc('user1'))
// some other operations
// do your assertion here...
})
})