Issue with unit testing in Firestore: Anticipated data type was supposed to be 'DocumentReference', however, what was received was a unique Firestore object

I am trying to execute unit tests for Firestore. Below is the code snippet I am using:

import { getDoc, setDoc } from "@firebase/firestore";
import {
  assertFails,
  assertSucceeds,
  initializeTestEnvironment,
  RulesTestEnvironment,
} from "@firebase/rules-unit-testing"

describe('Creating a user', () => {
  let alice;
  let anon;
  let testEnv;

  beforeAll(async () => {
    testEnv = await initializeTestEnvironment({
      projectId: "PROJECT_ID"
    })
  })

  beforeEach(() => {
    alice = testEnv.authenticatedContext("alice", { user_id: "1" });
    anon = testEnv.unauthenticatedContext();
  });

  test('alice can create a user', async () => {
    await assertSucceeds(setDoc(alice.firestore(), '/users/alice'), { "name": "alice" });
  })
});

The above code is based on the guidance provided in the official documentation, where they demonstrate a similar sample code:

// Assuming a Firestore app and the Firestore emulator for this example
import { setDoc } from "firebase/firestore";

const alice = testEnv.authenticatedContext("alice", { … });
// Use the Firestore instance associated with this context
await assertSucceeds(setDoc(alice.firestore(), '/users/alice'), { ... });

However, I encountered an error when running the code:

FirebaseError: Expected type 'DocumentReference', but it was: a custom Firestore object

This error occurred at the following line:

await assertSucceeds(setDoc(alice.firestore(), '/users/alice'), { "name": "alice" });

I am puzzled by why this is not functioning correctly even after reviewing the official documentation. Can anyone offer insight into what might be the issue here?

List of npm dependencies:

├── @babel/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="690a0500295e475b58d3c4c2d7cacbdcc0c9dae1cceeddeec597ccd51e89827a8ce89595b829507aca742848eeaa6fafa6eea9faedaafae689bbbaa8">[email protected]</a>
├── @babel/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e98a869969486978745c51577365606d7660767077">[email protected]</a>
├── @babel/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddb7bfbeb196bdb494abbfb8adbab3aeb298fcbbeeeaa69cebcbdaaacb8bcade9a6e3fcedfced3fe">[email protected]</a>
├── @babel/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="02727067642d0001407b78697d76767b71696d00777901">[email protected]</a>
├── @firebase/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdadacb5afac87bfb2badfbbbaffbacabcbaeffbdfd6cad4cecfc8caedd5dfaaa583cfd2dbdbeedbcaeefdcc91cd20cada"><span style="display: none;">[email protected]</span>[email protected]</a>
├── <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="62e6fdf0faf9f079fef2e0f681"
	data-prefix=""
	data-domain=""
	data-suffix="">[email protected]</a>
└──
	<a href="/cdn-cgi/l/email-protection" class="__cf_email__"
		data-cfemail="4d34393d77723872617474817269757971757215">[email protected]</a>

Answer №1

I am unable to locate the specific example you referred to in the provided link.

As per the official documentation, they recommend using this sample code:

setDoc requires a DocumentReference as the first argument, which aligns with the error message you received.

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 are some strategies for stopping Knex.js from executing a query object upon return from an asynchronous function?

My node.js backend utilizes Knex.js to construct dynamic DB queries based on various inputs. The challenge I'm facing is handling asynchronous processing of certain inputs. When returning a knex query object from an async function or a Promise resolve ...

"Learn how to deactivate the submit button while the form is being processed and reactivate it once the process is

I have been searching for solutions to this issue, but none seem to address my specific concern. Here is the HTML in question: <form action=".."> <input type="submit" value="download" /> </form> After submitting the form, it takes a ...

Generating a unique event triggered by element class change

Is it possible to create custom JavaScript events that are triggered when elements receive a specific class? I am trying to monitor all elements within a table and perform certain actions once a particular class is added to them. Can this be done, and if ...

Error in Node.js: Unable to access properties of null value within Express

While using Express (with node.js) and MongoDB, I encountered an error when trying to view or update a user profile. The middleware token check worked fine getProfileFields:::::::::::::>>>>e: TypeError: Cannot read properties of null (rea ...

Struggling with passing parameters through a route and displaying them in the Reddit app using React?

I'm currently working on a project that involves displaying threads from various subreddits when a user clicks on a list item using routes and react. However, I've encountered some issues with getting the information to display correctly. Below i ...

``Where can I find information on setting a timeout for a node.js application

Is it feasible to implement a timeout for running node.js? I am faced with the issue of connecting to external services that occasionally do not respond, causing my script to hang and the node.js process to freeze. I am seeking a solution to enforce the t ...

When Select2 doesn't find a suitable option, the text "other" will be displayed

Is it possible to show a default option in select2 dropdown if the user's typed input does not match any available options? $("something").select2({ formatNoMatches: function(term) { //return a predefined search choice } }); I have searched ...

Ways to synchronize countdown timer on different tabs using the same link

Is there a method available to synchronize a React countdown timer across two separate tabs, for example: 1:46          ||   1:52 first tab     ||   second tab Appreciate any help! ...

Columns that can be resized in a right-to-left (

Whenever I use RTL, the columns behave erratically when resizing... I have implemented colResizable. You can see an example here: http://jsfiddle.net/r0rfrhb7/ $("#nonFixedSample").colResizable({ fixed: false, liveDrag: true, gripInnerHtml: "<d ...

MUI: Issue with pseudo element appearing cropped outside of Paper container

I am facing an issue where a red arrow pseudo element '::before' is partially cut off outside its container '.MuiPaper-root'. I need the arrow to remain visible, any suggestions on how to fix this? Here is the relevant code snippet and ...

Do you have an index.d.ts file available for canonical-json?

I am currently working on creating an index.d.ts file specifically for canonical-json. Below is my attempted code: declare module 'canonical-json' { export function stringify(s: any): string; } I have also experimented with the following sn ...

The functionality of findDOMNode is no longer supported

My website, built using React, features a calendar that allows users to select a date and time range with the help of the react-advanced-datetimerange-picker library. However, I encounter some warnings in my index.js file due to the use of <React.Stric ...

Does the react key have scope limited to the local environment or does it have

After reading this intriguing article discussing the use of the index as a react key, I began to ponder. Imagine having two distinct lists: <List1> <el key="1" /> <el key="2" /> </List1> <List2> <other-el key="1" / ...

Listener of events calculates the outcome

In need of help with retrieving the current coordinates of a clicked point on Google Maps. Here is my code snippet: let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); getCoords() { google.maps.event.addListener ...

Determine the number of properties present in two arrays by comparing them

Looking to compare two arrays and determine the count of items in the master list. A sample master list could be: { name: 'Emily', age: 29 }, { name: 'Jack', age: 31 }, { name: 'Lily', age: 28 }, { name: 'Emily', a ...

The most efficient method for retrieving data in React

Recently, I started working on a React App integrated with Riot API to display users' recent games and more. As part of this project, I'm utilizing React and NextJS (fairly new to NextJS). However, I'm contemplating the most efficient way to ...

I'm looking to instantiate a Backbone collection outside of a script - how can I do that?

I have created my backbone collection named "Events" with a model called "Event". I want to create the backbone collection in this manner: Check out my code below: <script src="<?php echo site_url(); ?>js/backbone-calendar.js"></script&g ...

I'm having trouble understanding why I am not receiving any response with the "form.submit()" function inside xhr.onreadystatechange() in JavaScript/AJAX

When I try to use the form.submit() function in response to xhr.onreadystatechange, it doesn't work as expected. Below is my login form: <form action="user_home.php" method="post" id="loginForm" > <tr> <td colspan=2>Members ...

Tips for utilizing New FormData() to convert Array data from an Object for executing the POST request with Axios in ReactJs

When working on the backend, I utilize multer to handle multiple file/image uploads successfully with Postman. However, when trying to implement this in ReactJS on the frontend, I find myself puzzled. Here's a sample case: state = { name: 'pro ...

Ending user data snapshot listeners in web application

I have implemented a snapshot listener in my code to detect real-time changes on user data stored in Firestore. The purpose of this listener is for a chat feature I am currently developing, as I need to ensure that the list of chat Id's is updated in ...