title: How to mock dynamical for mongoDB method?
body: <p>In my application code there are several places, where I have to connect to a DB and get some data.
  For my unit tests (I'm using JestJS), I need to mock this out.</p>
  
  <p>Let's assume this simple async function:</p>
  
  <p><strong>/getData.js</strong></p>
  
  <pre><code>import DB from './lib/db'
  
  export async function getData () {
    const db = DB.getDB()
    const Content = db.get('content')
    const doc = await Content.findOne({ _id: id })
    return doc
  }
  </code></pre>
  
  <p>The DB connection is in a separate file:</p>
  
  <p><strong>/lib/db.js</strong></p>
  
  <pre><code>import monk from 'monk'
  
  var state = {
    db: null
  }
  
  exports.connect = (options, done) =&gt; {
    if (state.db) return done()
    state.db = monk(
      'mongodb://localhost:27017/db',
      options
    )
    return state.db
  }
  
  exports.getDB = () =&gt; {
    return state.db
  }
  </code></pre>
  
  <p>You can see, I'll recieve the DB and get a collection. After this I will recieve the data.</p>
  
  <p>My attempt for the mock so far:</p>
  
  <p><strong>/tests/getData.test.js</strong></p>
  
  <pre><code>import { getData } from '../getData'
  import DB from './lib/db'
  
  describe('getData()', () =&gt; {
    beforeEach(() =&gt; {
      DB.getDB = jest.fn()
        .mockImplementation(
          () =&gt; ({
            get: jest.fn(
              () =&gt; ({
                findOne: jest.fn(() =&gt; null)
              })
            )
          })
        )
    })
  
    test('should return null', () =&gt; {
      const result = getData()
      expect(result).toBeNull()
    })
  })
  </code></pre>
  
  <p>Maybe this is not the best way to do it...? I'm very happy for every improvement.</p>
  
  <p>My question is where to put the DB mock as there are multiple tests and every test needs a different mock result for the <code>findOne()</code> call.</p>
  
  <p>Maybe it is possible to create a function, which gets called with the needed parameter or something like that.</p>