I have been creating unit tests for my firestore security rules with the help of the node.js library @firebase/rules-unit-testing
Here is the security rule I have set for updating a document:
allow update: if request.auth.uid != null &&
request.auth.uid == userId &&
request.resource.data.updatedAt == request.time;
I specifically want the updatedAt
field to always be assigned the value of FieldValue.serverTimestamp()
.
While conducting a unit test, I attempted to update the value using FieldValue.serverTimestamp()
and ensuring its success. Here is the code snippet I used:
let testEnvironment: RulesTestEnvironment = await initializeTestEnvironment({
projectId: PROJECT_ID,
firestore: {
rules: fs.readFileSync("../firestore.rules", "utf8"),
host: "localhost",
port: 8080
}
})
const firestore = testEnvironment.authenticatedContext("user_123").firestore()
const testDoc = firestore.doc("/writers/user_123")
await assertSucceeds(testDoc.update(
"some_field", "some_value", "updatedAt", firestore.FieldValue.serverTimestamp()
))
However, I encountered an issue where firestore.FieldValue
was not defined.
In trying out the admin SDK firebase-admin
, I made a slight change to the last statement:
await assertSucceeds(testDoc.update(
"some_field", "some_value", "updatedAt", admin.firestore.FieldValue.serverTimestamp()
))
Unfortunately, this led to the following error-
FirebaseError: Function DocumentReference.update() called with invalid data. Unsupported field value: a custom object (found in field updatedAt in document writers/user_123)
If anyone has suggestions on how to effectively incorporate tests for updating the timestamp field, please share your insights!