Using @firebase/rules-unit-testing to test firebase security rules, how you test that a document's createdAt field is the current time? This is for Cloud Firestore.
Background
With firebase security rules, you can make sure a field is saved as the server timestamp.
match /collection/{docId} {
allow create: if request.time == request.resource.data.createdAt
}
This security rule works. And if you were to write to the document in the browser, you would then do:
firebase.firestore().collection('collection').add({
createdAt: firebase.firestore.FieldValue.serverTimestamp()
})
However, the server timestamp method does not exist in @firebase/rules-unit-testing.
The code
Here's the boilerplate for the test setup, using Jest:
import { initializeTestApp } from '@firebase/rules-unit-testing'
const app = initializeTestApp({ projectId: 'id' })
test('some test', async () => {
firebase.assertSuccees(
app.firestore().collection('collection').add({
createdAt: firebase.firestore.FieldValue.serverTimestamp()
})
)
})
The issue is that firebase.firestore.FieldValue is not defined (unlike in the browser example).
Furthermore, app.firestore.FieldValue is also not defined.
So how would you get the server timestamp to test this security rule?
Metadata
- firebase-tools: 9.3.0
- @firebase/rules-unit-testing: 1.1.9
- jest: 26.6.3
- Using the emulator