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

Does Typescript fail to recognize the "delete" operator?

Whenever I utilize the delete operator in Typescript, it appears that the system does not recognize that the property has been eliminated. For instance: interface HasName { name: string; } interface HasNoName { name: never; } function removeName( ...

The credentials in AWS S3Client are failing to load correctly

I encountered an issue with the S3 Client from aws sdk v3: When using the S3Client as outlined in the documentation and providing credentials via environment variables, I received an error message stating The AWS Access Key Id you provided does not exist ...

Encountering browser freezing issues with a Next.JS app when trying to add an input field

I am currently utilizing Next.JS to construct a form with two inputs. I have followed the traditional React approach for input text reading and validation. "use client" import { firebaseApp } from '@/app/firebase'; import React, { useCa ...

Variability in determining union types for matched conditional results

In my experience, I have noticed a discrepancy in TypeScript's type inference when dealing with conditional return statements in functions. I have two identical functions, register and register2, outlined below: const register = (step: 1 | 2) => { ...

What is the recommended approach for testing a different branch of a return guard using jest?

My code testing tool, Jest, is indicating that I have only covered 50% of the branches in my return statement test. How can I go about testing the alternate branches? The code snippet below defines a function called getClient. It returns a collection h ...

What is the best way to make the current tab stand out?

I have implemented a TabHeader component to create a dynamic Tab Menu that displays table contents based on months. The loop runs from the current month back to January, and the content is updated dynamically through an API call triggered by changes in the ...

Retrieve the current state of the toggle component by extracting its value from the HTML

I have a unique component that consists of a special switch and several other elements: <mat-slide-toggle (change)="toggle($event)" [checked]="false" attX="test"> ... </mat-slide-toggle> <p> ... </p> F ...

Encountering Issues with NextJS Dynamic SSR: Mobile Devices stuck on loading screen

Issue: The dynamic import feature of Next JS is encountering loading issues specifically on mobile browsers such as Google Chrome and Safari on IOS. Strangely, the functionality works smoothly on desktop browsers like Google Chrome and Mozilla. The projec ...

Pagination feature in MUI DataGrid table is malfunctioning

I'm struggling to get the pagination feature to work in my Material UI DataGrid component, but I'm hitting a roadblock: https://i.stack.imgur.com/eT7s7.gif The console is not showing any errors. Here is the code for my component: import { ...

Discover more efficient methods for utilizing generics in hierarchical objects within typescript

How can I optimize the structure of an object that contains nested objects in Typescript to minimize type repetitions? type itemType = { [key: string]: { [key: string]: { [key: string]: { [key: string]: string } }; }; }; ...

Encountering a problem with react-select in typescript when using react-use-form-state

Having a specific and tricky issue that I can't seem to solve right now. Our project has wrappers around certain Form controls to manage all the necessary setup code, and I'm currently facing an issue with the Select component wrapping the Selec ...

What is the best way to transition this endpoint from JavaScript to TypeScript?

I'm in the process of building a chat application with the t3 stack. I've successfully created a socket endpoint using JavaScript, but now I'm facing some challenges as I try to convert it to TypeScript. import { Server } from "Socket.I ...

Enhancing RTK Query: Efficiently Filtering Query Results in Separate Components

I am currently working on a Todo application using Nextjs 13 with various tools such as app directory, prisma, redux toolkit, shadcnui, and clerk. Within my app, I have implemented two key components - TodoList and Filter. The TodoList component is respons ...

Steps for integrating a valid SSL certificate into a Reactjs application

After completing my ReactJS app for my website, I am now ready to launch it in production mode. The only hurdle I face is getting it to work under https mode. This app was developed using create-react-app in a local environment and has since been deployed ...

Enumerate the names of the private properties within the class

I am working on a problem where I need to use some of the class properties as values in a map within the class. In the example below, I have used an array instead of a map because when a property is marked private, it is not included in the keyof list. How ...

TSConfig - Automatically Generates a ".js" File for Every ".ts" File

Having a unique software application with an unconventional file structure project ├── tsconfig.json ├── app_1 │ ├── ts │ └── js | └── app_2 ├── ts └── js I aim to compile files located inside the ...

Challenges in Power BI Custom Visual Development: Trouble setting height for div elements

Currently, I am working on creating a custom visual for Power BI that includes a leaflet map within a div element. However, the issue arises when I fail to set a specific height for the map, resulting in an empty visual. I have managed to set a fixed heigh ...

What methods can be used to accurately display the data type with TypeOf()?

When working with the following code: const data = Observable.from([{name: 'Alice', age: 25}, {name: 'Bob', age: 35}]); console.log(typeof(data)); The type is displayed as Object(). Is there a way to obtain more specific information? ...

Toggle the presence of a string in an array with a checkbox

Currently, I am working on a user creation form for my Next.js front end project using TypeScript. The main goal is to allow an administrator to create new users by filling out a simple form which will generate a basic user object. Here is the structure of ...

Error: Unable to locate module: Could not find 'react-server-dom-webpack/client.edge'

I've been trying to incorporate server components into my nextJS project, but I keep encountering an issue when using "use server" in my component. Error message: `./node_modules/next/dist/build/webpack/loaders/next-flight-loader/action-client-wrappe ...