title: Jest: global setup async with access to jest for mocking purposes
body: <p><strong>Scenario</strong>
  Running Jest to unit-test a nodejs API running a in-memory instance of mongodb (via <a href="https://github.com/nodkz/mongodb-memory-server" rel="nofollow noreferrer">mongodb-memory-server</a>)</p>
  
  <p><strong>My goal</strong>
  The in-memory db should start only once for ALL the test files.</p>
  
  <p><strong>Why</strong>
  While firing up 1 database PER FILE is not even a big deal (as long at is runs fast) the most important reason is that the plugin at first fetches the mongo binaries via an heavy download (if they are not already in the cache). So it makes sense to do this operation only once instead of ONCE PER FILE because the download acts in the exact same way (it takes files form the web and places them into a folder).</p>
  
  <p><strong>The problem</strong>
  Beside firing up the in-memory mongo I need also to mock my <code>dbService.js</code> file so that every file depending on it will use the mocked version (and thus the in-memory server). So I cannot really use the <code>globalSetup</code> option of Jest because in that file <code>jest</code> is <code>undefined</code>. I cannot even use <code>setupFiles</code> because they run PER FILE and they are synchronous while by nature of mongodb connect I need an async function. I tried also using <code>beforeAll</code> in every file passing a common utility module but since the tests files run in parallel even the utility module is run one time per file.</p>
  
  <p><strong>Also</strong>
  I would like to avoid to have 1 unique test file. I get that is a workaround but I was wondering if there is a simple and clean solution. The perfect scenario is "Do something first asynch, then do the tests in parallel". Shouldn't be that hard no?</p>