Badi8beach
Badi8beach

Reputation: 556

Stubbing PouchDB with Sinon failing

Im trying to stub a pouchDB 'put' function but in an invoked function but it is failing.

my DB function-

var PouchDB = require('pouchDB')
var PendingDB = new PouchDB("")
module.exports.addPendingRequest = function(doc, callback){

  PendingDB.put(doc, function(err, result){
      if(err) {
          console.log("Error in PendingDB: addPendingRequest");
          console.log(err);
          callback(err, null);
      } 
      callback(null, result); 
  });
console.log("after put: inside addPendingRequest");
}

My Test Function:

var expect = require("chai").expect;
var PendingDB = require("../../lib/administration/PendingDB");
var PouchDB = require('pouchDB');
var sinon = require('sinon');

describe('Testing adding a request', function(){
    it('should save the request with email', function(done){
        var req = {
                _id : "[email protected]",
                first_name: "firstTest",
                last_name: "test",
                id: "[email protected]",
                justif: "Testing Purposes",
        }
        var res = {};
        var next = null;
        console.log("after req, res, next");

        var testOutput = {
        success : "success"
        };

        console.log("after testOutput is set");

        var PendingDBTest = sinon.stub(PouchDB.prototype, 'put', function(err, result){
        console.log("in stub addReq");
    });
        console.log("after sinon.stub");
        expect(function(){
            PendingDB.addPendingRequest(req, function(err, response){
                console.log("response");
                console.log(response);
            });
        }).to.not.throw(Error);

        expect(PendingDBTest.called).to.equal(true);

        PendingDBTest.restore();

        done();

    })
 })

Console: after req, res, next after testOutput is set after sinon.stub after put: inside addPendingRequest

Therefore PendingDB.put is never entered and my test PendingDBTest.called returns false, thus failing.

Upvotes: 0

Views: 275

Answers (2)

NickColley
NickColley

Reputation: 131

Instead of stubbing you could write your tests with the in-memory adapters avaliable for PouchDB:

http://pouchdb.com/adapters.html

In NodeJS:

var PouchDB = require('pouchdb');

var testDB = new PouchDB('testDb', {
  db: require('memdown')
});

Or in the Browser:

<script src="pouchdb.js"></script>
<script src="pouchdb.memory.js"></script>
<script>
    // this pouch is ephemeral; it only exists in memory
   var testDB = new PouchDB('testDB', {
       adapter: 'memory'
   });
</script>

For example of a project that tests in this way check out: https://github.com/hoodiehq/pouchdb-hoodie-api/tree/master/tests

Upvotes: 0

luboskrnac
luboskrnac

Reputation: 24591

Stub on actual object, not on its prototype.

    var PendingDBTest = sinon.stub(PouchDB, 'put', function(err, result){
          ...

Upvotes: 0

Related Questions