firebase / firebase/firebase-js-sdk

Can't use Timestamp in Firestore rules unit tests

Open
#6,077 18 comments 18 reactions 1 assignee Assigned to @avolkovi View on GitHub
api: firestore Backlog needs-attention testing-sdk v9
Dominant language
TypeScript
Stars
5.1k
Forks
1k
Avg merge
2d 21h
Merged PRs (30d)
37

Description

### [REQUIRED] Describe your environment

* Operating System version: Mac OS
* Firebase SDK version: "firebase": "9.6.8", "firebase-admin": "10.0.2", "@firebase/rules-unit-testing": "2.0.2",
* Firebase Product: Firestore

### [REQUIRED] Describe the problem

#### Steps to reproduce:

While writing unit tests for Firestore rules, I am trying to set a timestamp on a document, but this results in the following error:

- for `serverTimestamp()`:

> 'Function DocumentReference.set() called with invalid data. Unsupported field value: a custom ServerTimestampFieldValueImpl object (found in field timestamp in document users/new-user)

- for `Timestamp.now()` and for `adminFirebase.firestore.Timestamp.now()`:
>'Function DocumentReference.set() called with invalid data. Unsupported field value: a custom Timestamp object (found in field timestamp in document users/new-user)'

#### Relevant Code:

```javascript

import { serverTimestamp, Timestamp } from 'firebase/firestore'
import firebase from 'firebase-admin'

async function test() {
const testEnv = await initializeTestEnvironment({
//...
})

testEnv.withSecurityRulesDisabled(async (ctx) => {
// I tried three ways of generating the timestamp, none of them worked:
const timestamp = serverTimestamp()
// const timestamp = firebase.firestore.Timestamp.now()
// const timestamp = Timestamp.now()

await ctx.firestore().doc('users/new-user').set({ timestamp })
})
}

```

#### Update
It turns out that I can provide `new Date()` as timestamp, which doesn't throw an error. However, the timestamp generated in this case doesn't pass the security rule that verifies that the time:
```
allow create: request.resource.data.timestamp == request.time
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.