title: How to mock Mongoose 'find()' function in Jest?
body: <p>I have a <strong>service</strong>: </p>
  
  <pre class="lang-js prettyprint-override"><code>export default class WorldService {
  
  constructor(worldModel) {
      this.worldModel = worldModel;
    }
  
    async getWorlds() {
      let resData = {};
      await this.worldModel.find({}, (err, worlds) =&gt; {
        resData = worlds;
      });
      return resData;
    }
  }
  </code></pre>
  
  <p>I have a <strong>Mongoose model</strong>:</p>
  
  <pre class="lang-js prettyprint-override"><code>import mongoose from 'mongoose';
  
  const worldSchema = mongoose.Schema({
    name: {
      type: String,
      required: true,
    },
  });
  
  export default mongoose.model('World', worldSchema);
  </code></pre>
  
  <p>I want to mock the Mongoose model and test the service function called <code>getWorlds()</code>. I am using <strong>Jest</strong> as a Testing Framework in my project.</p>
  
  <p>I tried to write an <strong>unit test</strong> in Jest:</p>
  
  <pre class="lang-js prettyprint-override"><code>import WorldModel from '../../../src/models/world';
  import WorldService from '../../../src/services/world';
  
  describe('When data is valid', () =&gt; {
    beforeAll(() =&gt; {
      jest.spyOn(WorldModel, 'find').mockReturnValue(Promise.resolve([
        { _id: '5dbff32e367a343830cd2f49', name: 'Earth', __v: 0 },
        { _id: '5dbff89209dee20b18091ec3', name: 'Mars', __v: 0 },
      ]));
    });
  
    it('Should return entries', async () =&gt; {
      const worldService = new WorldService(WorldModel);
  
      const expected = [
        { _id: '5dbff32e367a343830cd2f49', name: 'Earth', __v: 0 },
        { _id: '5dbff89209dee20b18091ec3', name: 'Mars', __v: 0 },
      ];
      await expect(worldService.getWorlds()).resolves.toEqual(expected);
    });
  });
  </code></pre>
  
  <p>I get a failing answer:</p>
  
  <pre><code> FAIL  test/unit/services/world.test.js
    When data is valid
      × Should return entries (9ms)
  
    ● When data is valid › Should return entries
  
      expect(received).resolves.toEqual(expected) // deep equality
  
      Expected: [{"__v": 0, "_id": "5dbff32e367a343830cd2f49", "name": "Earth"}, {"__v": 0, "_id": "5dbff89209dee20b18091ec3", "name": "Mars"}]
      Received: {}
  </code></pre>
  
  <h2>How to mock <strong>Mongoose</strong> <code>find()</code> function in Jest?</h2>
  
  <p>P.s. I prefer not to use any higher level test framework for <em>MongoDB</em>, e.g., <em>mockgoose</em>.</p>