title: Stubbing pg-promise using sinon and mocha
body: <p>Suppose I have a the following module, as database.js</p>
  
  <pre><code>const initOptions = {}
  const pgp = require('pg-promise')(initOptions)
  const config = require('../../config')
  
  const db = pgp({
    host: config.database.host,
    port: config.database.port,
    database: config.database.database,
    user: config.database.user,
    password: config.database.password
  })
  
  module.exports = db
  </code></pre>
  
  <p>And the following module as create.js</p>
  
  <pre><code>const db = require('./database')
  
  function create (name) {
    return new Promise((resolve, reject) =&gt; {
        db.func('create', name)
        .then(data =&gt; {
          return resolve(data)
        })
        .catch(err =&gt; {
          return reject(err)
        })
    })
  }
  
  module.exports = create
  </code></pre>
  
  <p>I'm trying to run a unit test on create.js that will test that db.func is called with 'create' as first argument and 'name' as the second, but without actually needing to set up a database connection (So tests can run offline).</p>
  
  <p>From what I can gather, this is what libraries like sinon.JS can be used for, so I tried creating a test and stubbed the db object.</p>
  
  <pre><code>const chai = require('chai')
  const chaiAsPromised = require('chai-as-promised')
  
  chai.use(chaiAsPromised)
  
  const sinon = require('sinon')
  
  const expect = chai.expect
  
  const create = require('./create.js')
  
  describe('Test Module', () =&gt; {
    it('should test stuff', () =&gt; {
      const db = require('./database')
      const dbStub = sinon.stub(db, 'func').callsFake(Promise.resolve(null))
      expect(create('test').then).to.be.a('Function')
    })
  })
  </code></pre>
  
  <p>However, it fails with</p>
  
  <pre><code>TypeError: Cannot redefine property: func
  </code></pre>
  
  <p>Most likely due to my limited exposure to sinon...</p>
  
  <p>How do I go about stubbing (or maybe I need to mock?) the db function so that I can test it an ensure db.func was called?</p>