Is there a way to mock a "find" call in mockingoose without getting back "undefined"?

I am currently working with mockingoose 2.13.2 and mongoose 5.12.2, leveraging Typescript and jest for testing purposes. Within my test scenario, I am attempting to mock a call to my schema's find method. Here is what I have tried:

import mockingoose from 'mockingoose';
...

    beforeEach(async () => {
      jest.resetAllMocks();
      jest.clearAllMocks();

      mockingoose(File).reset();
      console.log("mock response:" + JSON.stringify(fileMockResponse));
      mockingoose(File).toReturn(fileMockResponse, 'find');
      const filePostList = await File.find({
        _id: { $in: ['test'] },
      });
      console.log("mocking file post list:" + JSON.stringify(filePostList));

However, upon test execution, the following output is logged:

mock response:[{"data:" ... }]

  at Suite.<anonymous> (routes/file.test.ts:237:15)

console.log
mocking file post list:undefined

The appearance of undefined indicates that my attempt to mock a response from the find call was unsuccessful.

Here is a snippet of what my model/schema entails:

export interface IFile extends Document {
  author: string;
   ...
}

const FileSchema: Schema = new Schema(
  {
    author: { type: String, required: false },

    ...
  }

export default mongoose.model<IFile>('File', FileSchema);

Answer №1

If you're encountering issues, consider trying to create the model outside of the schema. Simply export the schema and then create the model separately outside (perhaps in your test scenario) where you import the schema.

This approach resolved a similar problem I encountered in my own project.

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

Is it possible to create a ASP.NET 5 (Core) Website using TypeScript and Node (or ESM) modules within Visual Studio 2019, excluding Visual Studio Code?

After following a helpful guide on setting up TypeScript in an ASP.NET 5 website project using Razor Pages, I decided to enhance my typings with Node modules instead of just importing as 'any'. My goal was to integrate a Node module like EthersJ ...

Refreshing the chosen input field within an Angular context

One of the components I have allows users to dynamically edit and add multiple addresses. Here's how the UI appears: https://i.sstatic.net/3v3ND.png Whenever I add or edit an address, the entire form field values get reset. This results in a new add ...

Gather Different Data Fields and Combine them into a Fresh Object from MongoDB

I have a simple question regarding my MongoDB structure that I hope can be answered easily. My structure looks like this: { ... a: [array elements], b: [array elements], c: [array elements], ... } Currently, I am using Mongoose and making 3 d ...

"Utilizing the same generic in two interface properties in Typescript necessitates the use of the

I have created an interface as follows: interface I<T>{ foo: T arr: T[] } After defining the interface, I have implemented an identity function using it: const fn = <T>({foo, arr}: I<T>) => ({foo, arr}) When calling this function l ...

Issue with MEAN app: unable to retrieve response from GET request

FETCH The fetch request is being made but no data is returned. There are no errors, just the fetch request repeating itself. app.get('/:shortUrl',async (req,res)=>{ try{ const shortUrl = await shorturl.findOne({ short: req.params.sh ...

What is the process of encapsulating a callback function within another callback function and invoking it from there?

Here is the code snippet I am working with: var me = this; gapi.auth.authorize({ client_id: client, scope: scope, immediate: true }, function (authResult: any) { if (authResult && !authResult.error) { me ...

Combine and search

I've encountered an issue with grouping a mongoose query and populating sub-documents using $lookup. However, the arrays in my result document are returning empty. Can anyone assist me in identifying the cause of this? var mongoose = require('mo ...

It appears that using dedicated objects such as HttpParams or UrlSearchParams do not seem to work when dealing with Angular 5 and HTTP GET query parameters

I'm facing a perplexing issue that I just can’t seem to figure out. Below is the code snippet making a call to a REST endpoint: this.http.get<AllApplicationType[]>(environment.SUDS_API_SERVICE_URL + environment.SUDS_ALL_APPLICATIONS_URL, this ...

Issue with Angular Swiper carousel: Error message pointing to node_modules/swiper/angular/angular/src/swiper-events.d.ts

I am attempting to implement a carousel in Angular using Swiper (). An error message is appearing: Error: node_modules/swiper/angular/angular/src/swiper-events.d.ts:3:50 - error TS2344: Type 'SwiperEvents[Property]' does not meet the constraint ...

How can I alter the appearance of HTML text when hovering over the enclosing div?

I want the text to change color and zoom when the cursor is near it (when the mouse enters the area of the div containing the text). Currently, I am able to change the text color only when hovering directly over it. Below is a snippet of the code. HTML: & ...

Exploring the distinction between "() => void" and "() => {}" in programming

Exploring TS types, I defined the following: type type1 = () => {} type type2 = () => void Then, I created variables using these types: const customType1: type1 = () => { } const customType2: type2 = () => { } The issue surfaced as "Type ...

Only JSON objects with a boolean value of true will be returned

I am working on returning JSON objects in JavaScript/TypeScript that have a true boolean value for the "team" property. For example, the JSON data I am using is as follows: { "state": "Texas", "stateId": 1, "team": true }, { "state": "Cali ...

Pagination problem arises when sorting through items

I am facing an issue with filtering items on different pages of my React website. The problem I encounter is that the filtering functionality only works on the initial page where the data is loaded. Code: CustomersEpolicyPage.tsx import React, {useEffect ...

The typing library for Angular does not properly identify the JQueryStatic object

Encountered an issue with the Angular declaration file: Error TS2304: Cannot locate identifier 'JQueryStatic'. The typings for jQuery are installed and properly declare JQueryStatic as an interface. Looking for solutions to resolve this error. ...

Exploring the most effective strategies for creating a brand-new type in TypeScript?

In the execution environment I'm working with, there are several global constants that represent different directions: TOP = 1 TOP_RIGHT = 2 RIGHT = 3 BOTTOM_RIGHT = 4 BOTTOM = 5 BOTTOM_LEFT = 6 LEFT = 7 TOP_LEFT = 8 These constants are not just ran ...

The shared service is malfunctioning and displaying inconsistent behavior

app.component.ts import { Component } from '@angular/core'; import { HeroService } from './hero.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.compon ...

Retrieve all entries and merge a field with aggregated information in Mongoose (MongoDB)

I am faced with the challenge of working with two Mongo collections, Users and Activities. The Activities collection consists of fields such as createdAt (type Date), hoursWorked (type Number), and a reference to the user through the user field. On the oth ...

Mongooses do not clutter the array with unnecessary lines

I need help generating a sorted list from the database. Here is my current code: const subs = await Sub.find({}, {userName: 1, score: 1, _id: 0}).sort({ score: 'desc' }); The output I am getting looks like this: { userName: 'test1', ...

Establish a connection between MongoDB and the built-in API in Next.js

I've been working on integrating a MongoDB database with the Next.js built-in API by using the code snippet below, which I found online. /api/blogs/[slug].ts import type { NextApiRequest, NextApiResponse } from 'next' import { connectToData ...

Is it possible to deduce the output type of a function based on its input?

In a web development project, the function getFormData() plays a crucial role in validating and sanitising a FormData object based on a specified schema. If the validation process goes smoothly without any errors, the function will return the cleansed Form ...