Mocking Firestore v9 getDocs() in Jest: A Comprehensive Guide

After upgrading our webapp from Firebase v8 to v9, we encountered various issues due to the new syntax. As I am still relatively new to Jest and Firebase/Firestore, not everything is completely clear to me yet ...

I am attempting to mock getDocs from firebase/firestore because of the error message I am receiving:

      TypeError: Cannot read properties of undefined (reading 'docs')
          at /.../src/.../operations.ts:123:45
          at processTicksAndRejections (node:internal/process/task_queues:34:5)
          at Object.<anonymous> (/.../src/.../index.test.ts:1234:6)

The error occurs during testing when the code reaches the following section:

const firestoreInstance = getFirestore(firebaseApp)
...
      const dataList = query(
        getDataCollection(),
        where('id', 'in', idList)
      )
      const dataDict: { [key: string]: {id: string, name: string} } = {}
      ;(await getDocs(dataList)).docs.forEach(
        (dataItem) => {
          const data = dataItem.data()
          dataDict[data['id']].name = data.name
        }
      )

Where getDataCollection resembles something like:

export const getDataCollection = (): CollectionReference  =>
  collection(
    firestoreInstance,
    `path-to-collection`
  )

Due to getDocs not being mocked, when I attempt to mock it in this manner:

    ;(getDocs as any).mockImplementation(() => Promise.resolve({
      docs: {
        data: () => ({
          name: 'name-for-this-data-item',
        }),
      },
    }))

I encounter the following error in the Jest output for this particular test:

TypeError: _firestore.getDocs.mockImplementation is not a function

Mocking Firebase v9 appears challenging based on the unanswered queries I have come across online, and I have yet to find a direct solution to my issue.

Any insights into what I may be doing incorrectly? And any guidance on how to resolve this problem?

Answer №1

Whenever I come here with questions, I always seem to end up answering them myself before long...

Just a friendly reminder: don't make fun of the getDocs function!

The tweak needed was not in mocking getDataCollection, but rather adjusting the collection get function from:

; (getDataCollection as any).mockImplementation(() => ({
  docs: {
    data: () => ({
      name: 'name-for-this-data-item',
    }),
  },
}))

To:

; (getDataCollection as any).mockImplementation(() => ({
  query: {
    docs:[{
      data: () => ({
        id: 'id-for-this-data-item',
        name: 'name-for-this-data-item',
      }),
    }],
  },
}))
})

This change introduced a new level for the query function.

I also included an id parameter in the data structure to fix a separate issue in my code.

Hoping this insight might assist fellow newcomers navigating Jest, Firebase, and Firestore challenges like me.

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

Tips for creating a deepCss selector for an input Textbox in Protractor

When I attempt to use sendKeys in an input textbox with Protractor, the element is located within a shadow-root and there are three separate input textboxes. ...

Typescript's definition file includes imports that can result in errors

Occasionally, typescript may generate a definition file with code like the following, leading to compile errors: // issue.ts import { Observable } from 'rxjs'; class Issue { get data() { return new Observable(); } } // issue.d.ts class ...

Setting up the environment variable for ApolloClient to be utilized in server-side rendering for continuous integration/continuous deployment involves following a specific

My apolloClient is configured as follows: /** * Initializes an ApolloClient instance. For configuration values refer to the following page * https://www.apollographql.com/docs/react/api/core/ApolloClient/#the-apolloclient-constructor * * @returns Apoll ...

What is the best way to categorize an array based on a specific key, while also compiling distinct property values into a list

Suppose there is an array containing objects of type User[]: type User = { id: string; name: string; role: string; }; There may be several users in this array with the same id but different role (for example, admin or editor). The goal is to conv ...

When is the best time to access user credentials in the FirebaseUI authentication process?

Referring to a provided example on using firebase authentication with Next.js from the Next.js github, I have noticed that many projects I have studied incorporate createUserWithEmailAndPassword at some point. This function allows them to utilize user cred ...

Using typescript for Gnome shell extension development. Guidelines on importing .ts files

I'm currently working on a gnome shell extension using typescript, but I've encountered issues when trying to import .ts files. The Gnome shell documentation suggests configuring the tsconfig file as outlined in this Gnome typescript docs: { &q ...

How does TypeScript provide me with insights even before compiling with tsc?

As I follow the instructions for incorporating TypeScript into my existing React Native project here, the final step instructs me to: Run yarn tsc to type-check your new TypeScript files. However, when I check VSCode, I am already receiving feedback from ...

The 'firestore' property is not found within the 'Firebase' type

I'm currently working on retrieving the precise time a document is generated. To achieve this task, I have included the following imports: import { Firebase } from '@ionic-native/firebase/ngx'; import { AngularFirestore } from '@angul ...

Is it possible to import SVG files and inline them in Angular?

Behold, an SVG Circle: <svg viewBox="0 0 104 104"> <circle cx="52" cy="52" r="50" stroke="#003EFF" stroke-width="4" fill="#00FF98" /> </svg> The Angular Project imports it in this manner: import circle from './circle.svg'; ...

Converting JSON Arrays into Typescript Arrays

I am working with a JSON file that contains an array object like this: [ { "VergiNo": "XXXXXXX" }, { "VergiNo": "YYYYYY" }, { "VergiNo": "ZZZZZZ" } ] After importing this JSON file into my Typescript file, import * as companies f ...

What is the best way to handle closing popups that have opened during an error redirection

In my interceptor, I have a mechanism for redirecting the page in case of an error. The issue arises when there are popups already open, as they will not automatically close and the error page ends up appearing behind them. Here's the code snippet re ...

Avoid the occurrence of the parent's event on the child node

Attempting to make changes to an existing table created in react, the table is comprised of rows and cells structured as follows: <Table> <Row onClick={rowClickHandler}> <Cell onCLick={cellClickHandler} /> <Cell /> ...

What is the best method for searching a string without considering uppercase or lowercase letters?

Here's a straightforward question I have: I need to search for a specific string match in a query. The code snippet is shown below: const test_name = 'ExAmPlE' const database_resources = await prisma.market.findMany({ where: { na ...

The use of findDOMNode has been marked as outdated in StrictMode. Specifically, findDOMNode was utilized with an instance of Transition (generated by MUI Backdrop) that is contained

I encountered the following alert: Alert: detectDOMNode is now outdated in StrictMode. detectDOMNode was given an instance of Transition which resides within StrictMode. Instead, attach a ref directly to the element you wish to reference. Get more inform ...

Angular 7 is throwing an error message stating that it is unable to locate the module named './auth.service'

Currently, I am facing a challenge while using Angular Guards to secure my pages from unauthorized access. import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot , Router } from '@angular/router'; import { Observable } from 'rxjs& ...

The Ionic framework has a defined variable

In my code, I have initialized a variable inside the constructor like this: constructor(public http: HttpClient) { this.data = null; this.http.get(this.url).subscribe((datas: any) => { this.dbUrl = datas[0].db_url2; console.log(this ...

Error: NullInjector - The injector encountered an error when trying to inject the Component into the MatDialogRef in the AppModule

When utilizing a component via routing as well as injecting it as the "target" of a modal dialog, I encountered an issue: export class Component1 implements OnInit { constructor(private service: <someService>, public dialogRef: MatDialogRef<Compo ...

Executing MongoDB collection operations with array filtering

I am looking to count records based on tags and filter them before including in specific groups // data in database {tags: ['video', 'Alex'], ... }, {tags: ['video', 'John'], ... }, {tags: ['video', 'J ...

Determining if an object aligns with a specific type in Typescript

Hey there, I've got a little dilemma. Imagine I have a type called A: type A = { prop1: string, prop2: { prop3: string } } Now, let's say I'm getting a JSON object from an outside service and I need to check if that JSO ...

Issue regarding angularjs type definitions

I am facing an issue with installing typings for Angular and I need some guidance on how to resolve the error. Any suggestions or assistance would be greatly appreciated! Below is the error message that I encountered: ERROR in C:\Users\test&b ...