Using sinon how do I stub or fake the property of a callback

Tags: , , ,



Using sinon how do I stub/fake a return value for this.lastID in the db.run function.

module.exports.insert = async(request) => {
    //unimportant code
    return new Promise((resolve, reject) => {
        db.run(sql, params, function(err) {
            if (err)
                reject(err)
            else
                resolve(this.lastID)
        })
    })
}

I can fake the callback using this code:

describe('insert', () => {
    beforeEach(() => {
        this.insert = sinon.stub(db, 'run')
            .callsArgWith(2, null)
    })

    afterEach(() => {
        this.insert.restore()
    })

    test('add product to the database', async(done) => {
        expect.assertions(1)
        const id = await productDb.insert(testProductAlt)
        expect(isNaN(id)).toBe(false)
        expect(id).toBe('1')
        done()
    })
})

But it will fail as this.lastID is undefined. How do I overcome this?

Thanks!

Answer

You can use stub.callsArgOn() to pass in a context value that will used as this in the callback. You would stub it with something like:

let insert_stubb = sinon.stub(db, 'run')
    .callsArgOn(2, {lastID: 'testVal'})

Here’s an example with some made up functions:

let db ={
  run(sql, params, cb){cb()}
}

let insert = async(request) => {
  let sql, params
  return new Promise((resolve, reject) => {
      db.run(sql, params, function(err) {
          if (err)
              reject(err)
          else
              resolve(this.lastID)
      })
  })
}


let insert_stubb = sinon.stub(db, 'run')
            .callsArgOn(2,{lastID: 'testVal'})

// should log our test value
insert()
.then(console.log)
.catch((e) =>console.log("error", "error: ", e))
<script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/7.1.1/sinon.min.js"></script>


Source: stackoverflow