title: Setting up an In memory mongoDB for testing with Jest
body: <p>I'm looking to set up a few tests with jest which requires me to have an in-memory MongoDB running for the tests to use. The way I'm looking at doing this is by creating a helper function that sets up my database connection normally outside of tests. But I can't seem to mock it and replace it with a mock implementation successfully. It keeps trying to use the actual database instead of the in-memory one I'm trying to use.</p>
  <p>This is what my support function looks like:</p>
  <pre><code>export const databaseConnection = async () =&gt; {
    const client = await connect();
    const database = process.env.DATABASE_NAME;
    const collection = client.db(database).collection('collectionName');
  
    return collection;
  };
  </code></pre>
  <p>I want to replace that to instead look like this:</p>
  <pre><code>export const databaseConnection = async () =&gt; {
    const client = await inMemoryConnect();
    const database = process.env.DATABASE_NAME;
    const collection = client.db(database).collection('collectionName');
  
    return collection;
  };
  </code></pre>
  <p>The way I have been trying to set it up to replace the implementation has been by doing this:</p>
  <pre><code>jest.fn(databaseConnection).mockImplementation(async () =&gt; {
    const client = await inMemoryConnect();
    const database = process.env.DATABASE_NAME;
    const clubhouseCollection = client.db(database).collection('clubhouse');
  
    return clubhouseCollection;
  });
  </code></pre>
  <p>But this mock in my test won't replace the one in the actual function I'm testing and instead keeps using the real database connection instead of my in-memory one. I can replace the inMemoryConnect in the non-mocked dataConnection and it'll use the in-memory database there. Just in my tests, it won't work. What could I be doing that is causing this to not correctly mock the function implementation?</p>