You need to enable JavaScript to run this app. 使用proxyquire mock nodemailer后 sinon打桩sendMail显示未被调用
优惠活动
大模型
产品
解决方案
定价
更多

使用proxyquire mock nodemailer后 sinon打桩sendMail显示未被调用

问题排查结论

核心触发断言失败的根因

  1. 异步方法未等待执行完成
    被测sendSuccessEmail为async函数,内部包含Vault凭证读取、SMTP客户端初始化、邮件发送等多层异步流程。测试代码中直接调用mailService.sendSuccessEmail未添加await,断言逻辑会在异步流程执行完成前触发,此时transporter.sendMail尚未被调用,因此sendMailMock.called取值为false。
  2. 打桩逻辑存在多余的函数嵌套
    proxyquire配置中createTransport返回的对象,对sendMail属性做了无意义的箭头函数包装:sendMail: () => sendMailMock()。该写法虽能最终调用到stub,但可读性差,且存在stub上下文绑定的隐性风险。

日志中输出的{ sendMail: [Function: sendMail] }是JSON.stringify的默认行为,函数类型字段只会被序列化为占位符文本,不代表mock打桩未生效。

修复方案

  1. 测试用例中对异步业务方法添加await:
    it('Should call success mail once ', async () => {
        await mailService.sendSuccessEmail(userEmail, fileModifiedDate);
        chaiAssert.equal(sendMailMock.called, true);
    });
    
  2. 简化nodemailer打桩逻辑,去除多余包装,直接将sinon stub挂载到transporter的sendMail属性上:
    mailService = proxyquire('../src/mailService', {
        'node-vault': () => { return { read: () => mockVaultData } },
        'nodemailer': {
            createTransport: () => ({
                sendMail: sendMailMock
            })
        }
    })
    
  3. 补充stub的返回值,避免未处理的Promise异常:
    初始化stub时指定resolve值,匹配sendMail的真实返回结构:
    sendMailMock = sinonSandbox.stub().resolves({ messageId: 'test' });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.22 04:15:00