How to properly stub a promise object which is part of another promise
<p>I have a promise function which performs an authentication based on the clients cookie</p>

<pre><code>const getInitialState = (id_token) =&gt; {
  let initialState;
  return new Promise((resolve,reject) =&gt; {
    if(id_token == null){
      initialState = {userDetails:{username: 'Anonymous',isAuthenticated: false}}
      resolve(initialState)
    }else{
        var decoded = jwt.verify(JSON.parse(id_token),'rush2112')
        db.one('SELECT  * FROM account WHERE account_id = $1',decoded.account_id)
          .then(function(result){
            console.log('result is : ',result)
            initialState = {userDetails:{username:result.username,isAuthenticated:true}}
            resolve(initialState)
          })
          .catch(function(err){
            console.log('There was something wrong with the token',e)
            reject('There was an error parsing the token')
          })
    }
  })
}
</code></pre>

<p>getInitialState is a promise object which calls a database function(another promise object) if the cookie is valid.</p>

<p>I want to stub the db call here to resolve to a username. But its not working no matter what i try</p>

<p>i tried two libraries <code>sinonStubPromise</code> and <code>sinon-as-promised</code>. But both seem to result in a timeout error which tells me that the <code>db</code> function isnt getting resolved</p>

<p>I believe i'm not stubbing the db function properly</p>

<p>these are the various ways i've tried</p>

<pre><code>stub2 = sinon.stub(db,'one')

stub2.returnsPromise().resolves({username:'Kannaj'})
</code></pre>

<p>or</p>

<pre><code>sinon.stub(db,'one').returns({username:'Kannaj'})
</code></pre>

<p>or</p>

<pre><code>sinon.stub(db,'one')
         .withArgs('SELECT  * FROM account WHERE account_id = $1',1)
         .returns({username:'Kannnaj'})
</code></pre>

<p>or</p>

<pre><code>let db = sinon.stub(db).withArgs('SELECT  * FROM account WHERE account_id = $1',1).returns({username:'Kannnaj'})
</code></pre>

<p>all lead to a timeout error from mocha</p>

<pre><code>Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
</code></pre>

<p>this is my entire test function</p>

<pre><code>  it('should return a valid user if id_token is valid',function(){
    id_token = '{"account_id":1}'
    console.log('stub1: ',stub1(), typeof(stub1))
    console.log('stub2 : ',stub2,typeof(stub2))

    // my attempts here
    return expect(getInitialState(id_token)).to.eventually.be.true
  })
</code></pre>

<p>For some reason , i believe mocha/sinon is loosing the pg-promise context as soon as it calls db.any . not sure why.</p>