Sinon Stub to mock multiple returns is not working

32 Views Asked by At

this is my db.js // I have isDBconnected which will check the database connection and sets the value for getDbStatus.

     const isDBConnected= async function (){
     try{
     sequelize.authenticate()
     .then( function(result){
     dbConnected = true;
    
    })
    .catch(function(result){
    dbConnected = false;
    console.error('Unable to connect to the database:');
    setTimeout(isDBConnected, 10000);
  
     })
   }
   catch(err) {
   console.error(err.message)
   reject('Database engine not found')
  }
}
const getdbStatus = () =\> {
return dbConnected
};

this is my readdb.js // perform db operation if the database is connected

const readdetails = async function() {
 if(getdbStatus () == false)
 {
   return response("error", 'Database not connected', null)
 }
 else{
   return response("Success", 'Means Connected', null)
 }
}

this is my unit test case. I want to mock getdbStatus and test readdetails function

 const mockRequire = require('mock-require');
 const sinon = require('sinon');

 const dbModuleOriginal = require('../db.js');

 describe("DB connection", function() {
 let dbModule;

 afterEach(() =\> {
 mockRequire.stopAll();
 sinon.restore();
 });

  it('when db server not available', async function(){
   // Set the database as connected
   sinon.stub(dbModuleOriginal, 'getdbStatus ')
    .onFirstCall().returns(false)
    .onSecondCall().returns(true);
   let result = await dbModuleOriginal.readdetails();
   assert.equal(result.message, "Database not connected");

   let anotherresult = await dbModuleOriginal.readdetails();
   assert.equal(result.message, "Means Connected");
  })

 })

I have step the stub to return true on the first call and false on the second call. However, the first one sets but not the second one. I believe it is to with my readdetails function implementation with Promise. I am not sure though. Any help would be much appriciated.Thanks

0

There are 0 best solutions below