1

I'm using mockingoose 2.13.2 and mongoose 5.12.2 with Typescript and jest. In my test, I'm trying to mock a call to my schema's find method, so I tried the below

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 when the test executes, the following gets logged:

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

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

console.log
mocking file post list:undefined

The undefined tells me my attempt to mock a response from the call to find failed.

My model/schema looks like the following:

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

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

    ...
  }

export default mongoose.model<IFile>('File', FileSchema);
Dave
  • 15,639
  • 133
  • 442
  • 830

1 Answers1

0

Have you tried to instantiate the model outside the schema? Export just the schema and then instantiate the model outside (which is in your test case) where you import the schema.

That's how I made that work in my case when I had a similar issue.

Bruno da Silva
  • 131
  • 2
  • 4