Skip to content

Commit

Permalink
add unit test for _setupMongoClient
Browse files Browse the repository at this point in the history
  • Loading branch information
benzekrimaha committed Oct 10, 2024
1 parent f38515e commit 76eea13
Showing 1 changed file with 77 additions and 0 deletions.
77 changes: 77 additions & 0 deletions tests/unit/api/BackbeatAPI.spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const assert = require('assert');
const sinon = require('sinon');
const MongoClient = require('mongodb').MongoClient;

const BackbeatAPI = require('../../../lib/api/BackbeatAPI');
const BackbeatRequest = require('../../../lib/api/BackbeatRequest');
Expand Down Expand Up @@ -210,4 +212,79 @@ describe('BackbeatAPI', () => {
assert.deepStrictEqual(sites, params.expected);
});
});

describe('_setupMongoClient', () => {
let mongoClientStub;
let infoSpy;
let errorSpy;
let debugSpy;

beforeEach(() => {
mongoClientStub = sinon.stub(MongoClient, 'connect');
infoSpy = sinon.spy(fakeLogger, 'info');
errorSpy = sinon.spy(fakeLogger, 'error');
debugSpy = sinon.spy(fakeLogger, 'debug');
});

afterEach(() => {
mongoClientStub.restore();
infoSpy.restore();
errorSpy.restore();
debugSpy.restore();
});

it('should connect to MongoDB when configuration is present', done => {
const mockDb = { db: sinon.stub().returns({}) };
mongoClientStub.yields(null, mockDb);

bbapi._config.queuePopulator.mongo = {
url: 'mongodb://localhost:27017',
replicaSet: 'rs0',
database: 'testdb',
};

bbapi._setupMongoClient(err => {
assert.ifError(err);
assert(mongoClientStub.calledOnce);
assert(infoSpy.calledWith('Connected to MongoDB', {
method: 'BackbeatAPI._setupMongoClient',
}));
done();
});
});

it('should log an error when MongoDB connection fails', done => {
const mockError = new Error('Connection failed');
mongoClientStub.yields(mockError);

bbapi._config.queuePopulator.mongo = {
url: 'mongodb://localhost:27017',
replicaSet: 'rs0',
database: 'testdb',
};

bbapi._setupMongoClient(err => {
assert.strictEqual(err, mockError);
assert(mongoClientStub.calledOnce);
assert(errorSpy.calledWith('Could not connect to MongoDB', {
method: 'BackbeatAPI._setupMongoClient',
error: mockError.message,
}));
done();
});
});

it('should skip MongoDB client setup when configuration is not present', done => {
delete bbapi._config.queuePopulator.mongo;

bbapi._setupMongoClient(err => {
assert.ifError(err);
assert(mongoClientStub.notCalled);
assert(debugSpy.calledWith('MongoDB configuration not found, skipping MongoDB client setup', {
method: 'BackbeatAPI._setupMongoClient',
}));
done();
});
});
});
});

0 comments on commit 76eea13

Please sign in to comment.