title: Mongoose: How do I avoid callback hell whilst allowing for stubbing of mongoose methods that do not return promises?
body: <p>In my express node application written in typescript, I'm using mongoose and am trying to avoid callback hell whist allowing for stubbing the mongoose functions in my mocha/sinon unit tests.</p>
  
  <p>Where mongoose does not return a promise (e.g. <a href="http://mongoosejs.com/docs/api.html#count_count" rel="nofollow noreferrer">Model.count()</a>) I'm wrapping the call in a new (awaited) promise which is resolved/rejected in the callback, like so:</p>
  
  <pre><code>const myModelCount = await new Promise((resolve, reject) =&gt; {
    MyModel.count({}, (err, count) =&gt; {
      if (err) {
        reject(err);
        return;
      }
  
      resolve(count);
    });
  });
  </code></pre>
  
  <p>This works great but I don't know how I can unit test the containing function and avoid a timeout error due to the unresolved promise. I want to stub <code>MyModel.count</code> so that it does not attempt to call the database, but how do I stub it so that the awaited promise is resolved and the program continues?</p>
  
  <p>Doing something like:</p>
  
  <pre><code>sinon.stub(MyModel, 'count').returns(Promise.resolve(1));
  </code></pre>
  
  <p>does not work as it does not resolve the promise that is being awaited, and since I don't have access to the <code>resolve</code>/<code>reject</code> parameters I don't know how to resolve the promise in the stub.</p>
  
  <p>Is there a way I can make the above work, or alternatively how I can refactor my code to both avoid callback hell and so that I can stub out the mongoose functions in unit tests?</p>