Search code examples
firebasefirebase-realtime-databasesinonstubbing

Firebase stub transaction


I am trying to stub a transaction over real time database table.The transaction is inside a function called by a trigger (non HTTP). I can fire the trigger, but I'm not able to stub transaction like this:

var codeRef = admin.database().ref('last_code')
return codeRef.transaction(function (currentCode) {
    return currentCode + 1
})
    .then(result => {
        const {error, committed, snapshot} = result
        return snapshot.val()
    })

I am using stub Sinon with mocha Unit testing of Cloud Functions. This is the way I tried:

const test = require('firebase-functions-test')();
adminInitStub = sinon.stub(admin, 'initializeApp');
// Now we can require index.js and save the exports inside a namespace called myFunctions.
myFunctions = require('../index');
const refParam = 'last_code';
const databaseStub = sinon.stub();
const refStub = sinon.stub();
const transactionStub = sinon.stub();
Object.defineProperty(admin, 'database', { get: () => databaseStub });
databaseStub.returns({ ref: refStub });
refStub.withArgs(refParam).returns({transaction: function(code) => ({committed: true, snapshot: 999});

But stub transaction fails. I am sure that last line is incorrect, but don't see the solution.


Solution

  • Finally I resolve in this way:

     const obj = {
            a: (() => function(code){
              return 999
            })};
    
      let dbSnap = {
              val: function() {
                  return 999;
              }
           };
    var resolveStub = sinon.stub(obj,"a");
    const result = {"error": null, "committed" : true, "snapshot" : dbSnap};
    resolveStub.resolves(result);
    refStub.withArgs("last_booking_code").returns({transaction:  resolveStub});