Search code examples
javascriptnode.jsunit-testingmocha.jsazure-eventhub

Constructor mock not working in mocha unit test in Javascript


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)

Solution

  • 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.

    import * as EventHubModule from '@azure/event-hubs';
    
     sandbox.stub(EventHubModule, 'EventHubBufferedProducerClient').throws(new Error('Connection failed'));