You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mocha单元测试中EventHubBufferedProducerClient构造函数Mock失效问题

问题描述

在Mocha单元测试中尝试让EventHubBufferedProducerClient的构造函数抛出异常,但未达到预期效果,测试失败。

类方法代码

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);
      }
    }
  }

测试用例代码

// beforeEach 中
sandbox = sinon.createSandbox();
eventHubProducer = EventBusProducer('mockEventHubName', 'mockconnectionString');

it('should log an error if connection fails', async () => {
      const logSpy = sandbox.spy(logger, '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;
    });

测试报错信息

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)
解决方案

问题出在构造函数的Stub方式错误:直接StubEventHubBufferedProducerClient.prototype.constructor不会影响new操作符创建实例时的构造函数调用。正确的做法是直接Stub整个EventHubBufferedProducerClient类,让它在被实例化时抛出异常。

修正后的测试用例代码

it('should log an error if connection fails', async () => {
      const logSpy = sandbox.spy(logger, 'error');
      
      // 正确Stub类的构造函数,使其抛出异常
      sandbox.stub(EventHubBufferedProducerClient).throws(new Error('Connection failed'));

      await eventHubProducer.connect();

      expect(eventHubProducer.producer).to.be.null;
      // 注意:原日志字符串中sEHub和${this.eHub}之间无空格,需与代码格式匹配
      expect(logSpy.calledWith(`Error while connecting to sEHubmockEventHubName`)).to.be.true;
    });

额外注意点

  • 原测试中的日志断言字符串多了空格(sEHub mockEventHubName),但类代码中是sEHub${this.eHub}(无空格),这会导致断言失败,需修正为和实际日志输出一致的格式。
  • 使用Sinon Stub类时,直接对类本身调用.throws()即可覆盖其构造函数的行为,无需操作prototype。

内容的提问来源于stack exchange,提问作者Prabhakaran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 09:32:44