Mock Sql DB connection in Nodejs Unit test cases

158 Views Asked by At

In My NodeJS Application, Connecting to Sql-DB using tedious, I want to unit test the microservices related to DB. During the unit test I don't want connect real database. But I am getting the error

Error: Unable to connect database: Error:'.connect cannot be called on a connection in SentLogin7WithStandardLogin state

Can you recommend any suggestions?

1

There are 1 best solutions below

0
On

I recommend using sinon to mock/stub database connection. It works if you use ORM library or native databas library. I usually use stub method like this:

const sinon = require(‘sinon’);
const chai = require(‘chai’);

it(‘sentence for expected test’, () => {
   let stubDbConnection = sinon.stub(dbLib, ‘connectionMethod’);
   testedFunction();

   chai.expect(stubDbConnection.calledOnce).to.be.true;
});

Hope it helps you. Regards