My DB Class to test
I have a DB class where i encapsulate Mongodb methods to test
import mongodb from 'mongodb';
import dotenv from 'dotenv';
// Comfigure dotenv
dotenv.config();
// eslint-disable-next-line no-unused-vars
class DBClient {
/**
* Creates a new DBclient instance.
*/
constructor() {
const host = process.env.DB_HOST || 'localhost';
const port = process.env.DB_PORT || 27017;
const database = process.env.DB_DATABASE || 'files_manager';
const dbUri = `mongodb://${host}:${port}/${database}`;
this.client = new mongodb.MongoClient(dbUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
this.isClientConnected = false;
this.client.connect((err) => {
if (err) {
console.error('Error encounted while connecting to MongoDB', err);
} else {
this.isClientConnected = true;
console.log('Connected to MongoDB');
}
});
}
/**
* check the status of the connection to MongoDB
* @returns {boolean}
*/
isAlive() {
return this.isClientConnected;
}
}
const dbClient = new DBClient();
module.exports = dbClient;
My Test File
My intention is to mock the connection to db then test
const { expect } = require('chai');
const sinon = require('sinon');
const mongodb = require('mongodb');
const dbClient = require('../utils/db');
describe('DBClient', function() {
afterEach(function() {
// Automatically restore all stubs after each test
sinon.restore();
});
it('should initialize and connect successfully', function(done) {
const connectStub = sinon.stub(mongodb.MongoClient.prototype, 'connect').callsFake(function(cb) {
cb(null); // No Error
});
// Wait for the next tick to allow the callback to execute
process.nextTick(() => {
expect(dbClient.isAlive()).to.be.true;
expect(connectStub.calledOnce).to.be.true;
done();
});
});
it('should fail to connect and isAlive returns false', function(done) {
// Stub the connect method to simulate a connection failure
const connectStub = sinon.stub(mongodb.MongoClient.prototype, 'connect').callsFake(function(cb) {
cb(new Error('Failed to connect'));
});
process.nextTick(() => {
expect(dbClient.isAlive()).to.be.false;
expect(connectStub.calledOnce).to.be.true();
done();
});
});
});
When i run the test
The two test cases are falling with the following error.
DBClient
1) should initialize and connect successfully
2) should fail to connect and isAlive returns false
0 passing (20ms)
2 failing
1) DBClient
should initialize and connect successfully:
Uncaught AssertionError: expected false to be true
+ expected - actual
-false
+true
at /root/alx-files_manager/test/connectToMongoDb.test.js:18:39
at processTicksAndRejections (node:internal/process/task_queues:77:11)
2) DBClient
should fail to connect and isAlive returns false:
Uncaught AssertionError: expected false to be true
+ expected - actual
-false
+true
at /root/alx-files_manager/test/connectToMongoDb.test.js:32:43
at processTicksAndRejections (node:internal/process/task_queues:77:11)
I suspect my issue is starting when I stub the connection to the DB. Please assist