Testing the timestamp field rule in security rules for Firestore

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!

Answer №1

The data you are attempting to provide is in an incorrect format

Here is a suggested solution:

Ensure proper formatting of the data being passed by using the following code:
await assertSucceeds(testDoc.update(
  {some_field: "some_value", updatedAt: admin.firestore.FieldValue.serverTimestamp()})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What mistakes am I making with Typescript and jquery-ui?

Having some difficulty integrating jquery, jquery-ui, and typescript in my project. I used npm to install both jquery and jquery-ui with the following commands: npm install --save jquery npm install --save jquery-ui On my typescript file, I included them ...

Using Higher Order Components (HOC) in combination with Redux compose and Typescript

I am trying to leverage two Higher Order Components (HOC) with Redux compose, but the compiler is not generating the correct types. The Compose function is defined in the Redux source code here source code. To better understand how the code works, you ca ...

Generating table columns using *ngFor method

Trying to create a table in Angular and wondering how to generate table columns using something like *ngFor. I currently have two lists: Data: [ 0: data: [ 0: 0 1: 4 2: 4 3: 3 4: 5 5: 1 ] id: 49 label: "Label_1" 1: data:[ 0: 5 1: 0 2: 1 3: 5 4: 0 ...

Solve the error "Property 'container' of null is not accessible" in musickit.js while running an Angular application on a server

I am currently developing an application that combines Angular and MusicKit to offer users the ability to listen to music simultaneously. However, I encountered a challenging error when trying to run the application using ng serve --host x.x.x.x instead of ...

Limiting the parameter type in Node.js and TypeScript functions

Currently working on a Node.js project utilizing TypeScript. I'm attempting to limit the argument type of a function to a specific base class. As a newcomer to both Node and TypeScript with a background in C#, I may not fully grasp some of the langua ...

The lazy loading feature in Angular 12 is not functioning correctly for path modules

My application has a jobs module with various components, and I'm trying to lazy load it. However, I've encountered an issue where accessing the module through the full path http://localhost:4200/job/artist doesn't work, but accessing it thr ...

TensorflowJS Error: The property 'fetch' cannot be read as it is undefined

I am working on an Angular 7 application and attempting to load the mobilenet model by following the instructions in this example. To do this, I first installed tensorflowjs using the command npm install @tensorflow/tfjs (based on the steps provided in th ...

Creating a bullet list from a dynamically parsed object: step-by-step guide

Here is my JSON string foo_json_string: [{"foo_name":"foo_value"},{"foo_name1":"foo_value1"}] I am trying to parse it and display it as an HTML list. This is the method I attempted: <ul> <li v-for=" ...

Utilizing WebWorkers with @mediapipe/tasks-vision (Pose Landmarker): A Step-by-Step Guide

I've been experimenting with using a web worker to detect poses frame by frame, and then displaying the results on the main thread. However, I'm encountering some delays and synchronization issues. My setup involves Next.js 14.0.4 with @mediapip ...

Angular - Error: Object returned from response does not match the expected type of 'request?: HttpRequest<any>'

While working on implementing an AuthGuard in Angular, I encountered the following Error: Type 'typeof AuthServiceService' is not assignable to type '(request?: HttpRequest) => string | Promise'. Type 'typeof AuthServiceServic ...

Using TypeScript interfaces to define key-value pairs for object properties

My goal is to accurately type situations where I need to map an array of objects to an array with the same objects, but using the property value as the index key. View code on playground interface ValueDefinition { name: string; } function getByName ...

I am experiencing difficulty with VS Code IntelliSense as it is not displaying certain classes for auto-import in my TypeScript project

I'm currently working on a project that has an entrypoint index.ts in the main folder, with all other files located in src (which are then built in dist). However, I've noticed that when I try to use autocomplete or quick fix to import existing ...

Error encountered when sending a POST request: net::ERR_CERT_COMMON_NAME_INVALID

Trying to send a POST request from a React app hosted on Firebase to an API built with express.js and Firebase Cloud Functions is resulting in failure. The error message received is: POST "Request URL" net::ERR_CERT_COMMON_NAME_INVALID Upon rese ...

Issue with nextJS/Firebase database while experimenting with enabling web frameworks

I encountered an issue with a nextJS app I built on Firebase, following the steps and running the commands mentioned below: % npx create-next-app@latest % cd myapp % firebase experiments:enable webframeworks % npm install -g firebase-tools % firebase ...

The Angular RXJS HTTPClient fails to properly handle HttpErrorResponses

In my Angular 12 project, I am facing an issue with setting up unit tests that should capture errors from HTTP responses. However, when running the tests, instead of receiving the error as an actual error object, it is being passed within the response body ...

In order to limit the disabled series/legends in the HighChart pie chart, it is necessary to implement restrictions when exporting

I am currently utilizing the Highcharts library to create visually appealing charts. When exporting data into a CSV file from a Pie chart, I would like to prevent legends/series data from being included. Here is what I have attempted: ... plotOptions: { ...

Setting the value in an Autocomplete Component using React-Hook-Forms in MUI

My form data contains: `agreementHeaderData.salesPerson ={{ id: "2", name: "Jhon,Snow", label: "Jhon,Snow", value: "<a href="/cdn-cgi/l/email-prot ...

Issue with Undefined Variable in Angular 2 and Ionic Framework

I included the following code in my HTML file: <ion-col col-3 align="right"> <ion-item> <ion-label>Show as</ion-label> <ion-select [ngModel]="SelectedView" (ngModelChange)="onViewChange($eve ...

Arranging a list of objects in Angular 6

I am facing difficulties in sorting an array of objects The structure of the object is as follows: https://i.sstatic.net/z5UMv.png My goal is to sort the *ngFor loop based on the group_id property. component.html <ul *ngFor="let list of selectgi ...

``There seems to be an issue with retrieving and displaying data in Ionic2 when using nav

I am facing an issue with displaying the data received from NavParams. I have used console.log() to confirm that I am getting the correct data, but for some reason, I am unable to display it on the new page. I suspect that there might be an error in how I ...