3

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
Nick
  • 5,108
  • 2
  • 25
  • 58
  • `FieldValue` is not included in the `rules-unit-testing` package, try importing the admin sdk and then use `admin.firestore.FieldValue` to access it, as described in this [community answer](https://stackoverflow.com/questions/47091940/fieldvalue-undefined-when-using-functions-and-firestore). This should fix the issue you are facing. Try it out and let me know if this helps. – Ralemos Feb 09 '21 at 15:53
  • I'm facing the same issue and it wasn't resolved by using admin-sdk. It gives the error- `Function DocumentReference.set() called with invalid data. Unsupported field value: a custom object (found in field createdAt in document col/doc` – Akshay Jain Aug 31 '21 at 16:05

0 Answers0