I am trying to raise an exception for an constructor method of EventHubBufferedProducerClient but its not working as expected. Am I missing something here.
My class method:
import { EventHubBufferedProducerClient } from '@azure/event-hubs';
import { logger } from '../logger';
this.producer = null;
async connect() {
if (this.producer === null) {
try {
this.producer = new EventHubBufferedProducerClient(this.connStr, this.eHub);
} catch (e) {
logger.error(`Error while connecting to sEHub${this.eHub}`, e);
}
}
}
Below is my test case:
//In before each
sandbox = sinon.createSandbox();
eventHubProducer = EventBusProducer('mockEventHubName', 'mockconnectionString');
it('should log an error if connection fails', async () => {
const logSpy = sandbox.spy(logger, 'error');
// Force connection failure by throwing an error
sandbox.stub(EventHubBufferedProducerClient.prototype, 'constructor').throws(new Error('Connection failed'));
await eventHubProducer.connect();
expect(eventHubProducer.producer).to.be.null;
expect(logSpy.calledWith("Error while connecting to sEHub mockEventHubName")).to.be.true;
});
I am getting below error:
should log an error if connection fails:
AssertionError: expected EventHubBufferedProducerClient{ …(9) } to be null
at Context.<anonymous> (EventBusProducer.test.js)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
2
Answers
Finally found the answer after some struggle. In case if anyone encounter such in future the answer may help.
use the below line in the test case to throw error.
You are so stubbing the connect method of
EventHubBufferedProducerClient
, which is invoked when an instance is created. If the connection fails, an error will be thrown, and the catch block in the connect method should report the problem and change this.producer to null.