title: How to properly stub and test a function using sinon
body: <p>I have this basic method which accepts a cookie and returns a valid user</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){
              initialState = {userDetails:{username:result.username,isAuthenticated:true}}
              resolve(initialState)
            })
            .catch(function(err){
              console.log('There was something wrong with the token')
              reject('There was an error parsing the token')
            })
      }
    })
  }
  </code></pre>
  
  <p>Since this is a promise - i'm using a chaiAspromised.</p>
  
  <p>Im able to successfully test the first condition (cookie is not preset) with the below</p>
  
  <pre><code>  it('should return anonymous user if id_token isnt preset',function(){
      let id_token = null
      return expect(getInitialState(id_token)).to.eventually.have.deep.property('userDetails.username','Anonymous')
    })
  </code></pre>
  
  <p>however , i'm unable / not too sure how to test the second part since it relies both on jwt and an external db call ( which itself is another promise object)</p>
  
  <p>I've tried this so far. Stubbing the db call returns this error which im finding really vague</p>
  
  <pre><code> 1) GetInitialState should return a valid user if id_token is valid:
       TypeError: Cannot redefine property: connect
        at Function.defineProperty (native)
        at Object.wrapMethod (node_modules/sinon/lib/sinon/util/core.js:128:24)
        at stub (node_modules/sinon/lib/sinon/stub.js:67:26)
        at node_modules/sinon/lib/sinon/stub.js:60:25
        at node_modules/sinon/lib/sinon/walk.js:28:30
        at Array.forEach (native)
        at walkInternal (node_modules/sinon/lib/sinon/walk.js:23:45)
        at Object.walk (node_modules/sinon/lib/sinon/walk.js:49:20)
        at Object.stub (node_modules/sinon/lib/sinon/stub.js:52:23)
        at Context.&lt;anonymous&gt; (getInitialState.spec.js:27:11)
  </code></pre>
  
  <p>I guess it isnt allowing me to stub the entire db object. How else can i approach this? I just want both jwt and the db call not throw any error. I'm just testing if a proper object is sent back if the cookie is valie</p>
  
  <pre><code>  it('should return a valid user if id_token is valid',function(){
      sinon.stub(jwt,'verify').returns({username:foo});
      sinon.stub(db).resolves() // unsure of what to do here
      id_token = ' Foo----bar '
      return expect(getInitialState(id_token)).to.eventually.be.true
    })
  </code></pre>