title: Unit testing NodeJS Promise inside a function
body: <p>Im trying to unit test a function that calls a promise...</p>
  
  <p>Using Mocha, Sinon. I have a functional block like this:</p>
  
  <p>myfile.js:</p>
  
  <pre><code>    let OuterDependecy = require('mydep');
      function TestFunction(callback) {
          OuterDependency.PromiseFunction().then(response =&gt; {  
  
         //some logic here
       }).catch(err =&gt; {callback(err)});
  </code></pre>
  
  <p>inside my test i have used <a href="https://www.npmjs.com/package/proxyquire" rel="nofollow noreferrer">proxyquire</a> to mock the outerdependecy</p>
  
  <p>testfile.js</p>
  
  <pre><code>let proxyquire = require('proxyquire');
  let OuterDepStub = {};
  let testingFunc = proxyquire('myfile.js', {'mydep': OuterDepStub});
  </code></pre>
  
  <p>... then inside my testing block</p>
  
  <pre><code>    let stubCallback = function() {
                  console.log('Stub dubadub dub'); //note...i can use sinon.spy here instead
      };
  
     beforeEach(()=&gt;{
              OuterDependency.PromiseFunction = function(arg) {
                 return  new Promise((resolve, reject)=&gt;{
                     reject('BAD');
                 });
              };
  
  
              spy = sinon.spy(stubCallback);
         });
  </code></pre>
  
  <p>my actual test now calls the main "testfunction" </p>
  
  <pre><code>it('Catches Errors, and calls back using error', done =&gt; {
              TestFunction(stubCallback);
              expect(spy).to.have.been.called;
              done();
          });
  </code></pre>
  
  <p>I see the stub being called (the console log, hence why i didnt want to use sinon.spy)  but the spy is saying its not called. and unit test fails.</p>
  
  <p>I believe this is probably due to a race condition of sorts where the promise is resolving after my test is run... is there anyway to delay the test until my promise is resolve.</p>
  
  <p>i know in in angularjs promise testing, there was a way to "tick" the promise so it resolves when you want to. possible in nodejs?</p>