使用 proxyquire 进行存根

2024-04-25

我如何使用 proxyquire 和 sinon 存根以下模块:

var email = require("emailjs").server.connect.send();

我执行了以下操作,但它不起作用,因为当我尝试在内部触发错误时send()它仍然发送电子邮件。

sendMailStub = sinon.stub(email, "send");    
testedModule = proxyquire('../index.js', {
                'email': {
                    'server': {
                        'send': sendMailStub
                        }
                    }
            });

并且还尝试过:

testedModule = proxyquire('../index.js', {
            email: {send: sendMailStub}
        });

这是迄今为止的完整测试,但失败了:

var chai = require('chai');
var sinonChai = require("sinon-chai");
var sinon = require('sinon');
chai.use(sinonChai);
var proxyquire = require('proxyquire');
var testedModule;
var expect = chai.expect;



describe('invoicer', function () {

    var nock = require('nock');

    var ResponseOptions = {
        username: "Peter Pan",
        user_address_line_1: "Never Never Land",
        user_address_line_2: "Tree-house 99",
        user_post_code: "E4 9BY",
        delivery_address_line_1: "Hook's Boat",
        delivery_address_line_2: "Dock 69",
        delivery_post_code: "SE2 4C",
        order_number: "234234234",
        order_date: "20/12/2090",
        dispatch_date: "20/12/2090",
        items: [
            {
                product_name: "Fairy Dust",
                brand: "Airy fairy",
                quantity: 5,
                total: 2000
            },
            {
                product_name: "Pirate Sword",
                brand: "Pirate's Bay",
                quantity: 8,
                total: 2000
            }
        ],
        grand_total: 4000,
        user_email: "[email protected] /cdn-cgi/l/email-protection"
    }

    var mailOptions = {
        text: "Hello World"
    }

    var scope = nock("http://somewhere.com")
        .get("/orders")
        .reply(200, ResponseOptions);

    var sendStub, readFileStub, url, contextDoneSpy, obj, connectStub;

    before(function () {

        readFileStub = sinon.stub();
        sendStub = sinon.stub().withArgs(mailOptions).callsArgWith(1, null, contextDoneSpy);
        connectStub = sinon.stub().returns({
            send: sendStub
        });

        testedModule = proxyquire('../index', {
            'fs': {readFile: readFileStub},
            'emailjs': {
                'server': {
                    'connect': connectStub
                }
            }
        });

        url = "http://somewhere.com/orders";
        contextDoneSpy = sinon.spy();
        obj = {
            user: 'AKIAJMHSJRRYGKTE4TOQ',
            password: 'Ag3Nkpej8dxZ4DwYz2in/x8kUhN7Lh/BqXImB0+i+DWy',
            host: "email-smtp.eu-west-1.amazonaws.com",
            port: 587,
            tls: true,
            ssl: false
        }

        readFileStub.withArgs('./email.html').callsArgWith(1, null, 'file1');

        connectStub();
    });

    it("readFile and successful context.done were called", function (done) {
        testedModule.Invoicer(url, obj, { done: function () {
            contextDoneSpy.apply(null, arguments);
            expect(readFileStub).has.been.called;
            expect(contextDoneSpy).to.have.been.called;
            done();
        }});

    });
});

让我们首先修复您所描述的行emailjs使用其文档 https://github.com/eleith/emailjs#example-usage---text-only-emails

require("emailjs").server.connect({
  /* Required server options */
}).send(function (err, message) {
  // This a function with a callback node convention signature
});

connect是一个函数,应该接收一些参数,而且send不返回任何东西,基本上调用回调

Proxyquire 要求使用相同的模块名称,因此email应该emailjs,另一方面,你错误地将存根分配在proxiquire, 它应该是

connectStub = sinon.stub().returns(sendStub);
sendMailStub = sinon.stub(email, "send");    
testedModule = proxyquire('../index.js', {
            'emailjs': {
                'server': {
                    'connect': connectStub
                }
        });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 proxyquire 进行存根 的相关文章

随机推荐

  • mvc:注解驱动未绑定

    当我在 NetBeans 中运行某个 Spring Web 3 项目时 出现此错误 org xml sax SAXParseException 行号 11 列数 30 这 元素的前缀 mvc mvc annotation driven 没有
  • # Rails 5.1 的未定义方法“map”

    我正在将 Rails 应用程序从 3 2 2 升级到 5 1 4 我直接使用参数时在地图方法上遇到错误 错误 ActionController Parameters 的未定义方法 map 在下一行 assignments params as
  • 尝试在 R 中创建直方图时 x 必须是数字

    我是 R 新手 我需要生成一些图表 我导入了一个 Excel 文件 需要在一列上创建直方图 我的导入代码是 file read xlsx femalecommentcount xlsx 1 header FALSE col file 2 上
  • 如何根据条件分割字符串

    分割字符串时 如何确保如果分隔符位于两个字符之间 则不会被考虑 Input String string a b c d e String split string split Output split 0 a split 1 b split
  • SugarORM 中的持久化对象

    我有一个图书课 public class Book extends SugarRecord private String mBookName private String mAuthorName private List
  • Laravel 快速入门指南路线不起作用

    好吧 我是 Laravel 新手 所以直接查看文档开始 文档中存在大量漏洞 因此需要花费大量精力和谷歌搜索来填补空白才能完成 Laravel 设置 我现在已经设置完毕并继续执行快速入门指南中的下一步 我创建了我的路线 Route get u
  • 检查线程状态,同时使其处于等待状态

    我想知道是否可以检查线程的状态 该线程可能处于可等待状态 但不一定如此 如果它处于可等待状态 我想将其保留在该状态 基本上 如何在不更改线程 可等待 状态的情况下检查线程的状态 通过等待 我的意思是如果我调用 wait pid 它会正确返回
  • 缺少库 com.sun.tools.attach

    我尝试跟随本教程 http dhruba name 2010 02 07 creation dynamic loading and instrumentation with javaagents 但我在进口方面遇到问题 I got The
  • MVC 3 在 ValidationSummary 中显示 HTML

    我试图在验证摘要中显示一个强标签 但它对其进行了编码并且无法正确显示 Html ValidationSummary false strong ERROR strong The form is not valid 我怎样才能让它发挥作用 最简
  • 为什么访问令牌请求需要redirect_uri?

    我正在开发一个基于 oauth2 提供程序rfc6749 https www rfc editor org rfc rfc6749我想知道为什么需要redirect uri访问令牌请求 https www rfc editor org rf
  • 抽象 NHibernate 标准是否有价值?

    我对 NHibernate 相当陌生 我见过的大多数示例都在基础上添加了一些抽象层Criterion or DetachedCriterion类 在简单的情况下 它是某种Query类可能看起来像这样 public class Query
  • Angular 自定义错误处理程序未从 Promise 获取错误类型

    当从承诺中抛出每个错误时 我的自定义错误处理程序都会丢失其类型 import HttpErrorResponse from angular common http import ErrorHandler Injectable Injecto
  • XElement 迭代并将其添加到父级

    您好 我有以下问题 请帮忙 因为我对 C 编程非常陌生 以前没有编程经验 在我的代码中 我应该迭代 Xml 文件中的 XElement 然后将该 Xelement 添加到称为 Capability 的父级 这是我的代码 if xElem H
  • 如何在 iOS 故事板中使用自定义字体来支持动态类型辅助功能大小

    我怎样才能使用动态类型文本样式 https developer apple com library ios documentation StringsTextFonts Conceptual TextAndWebiPhoneOS Custo
  • 带有 EPPlus 2.9 的 Chrome 16 中出现“从服务器收到重复标头”错误

    我正在玩EPPlus 2 9 http epplus codeplex com 由于某种原因我得到Duplicate headers received from server当我尝试下载单曲时出现错误 xlsx使用 Chrome 16 的文
  • CSS 高度 80% 不起作用

    我想让我的表格占据屏幕的 80 但现在它只是表格内容的大小 ecom mainarea center margin left 10 position relative width 80 height 80 when this is 500p
  • Rails 4 中的多对多嵌套属性(具有强参数)

    几天来我一直在努力解决这个问题 我正在使用 Rails 4 使用更新的批量分配技术 并尝试使用具有多对多关系的嵌套属性 我的记录正在保存到数据库 但一切都为零 并且我在日志中收到 未经允许的参数 学校 校友 前景 错误 这是我所拥有的 推荐
  • 视频广告未在 YouTube HTML5 播放器中展示

    我正在使用 IFrame Embed 尝试 YouTube HTMl5 视频播放器 我已经成功创建了一个用于加载 YouTube 视频的示例网页 如中所述https developers google com youtube iframe
  • Typescript 将“接口”键作为字符串的并集传播

    是否可以将函数参数类型检查为其中之一interface s keys export interface IUser id string email string password string const updateUserPropert
  • 使用 proxyquire 进行存根

    我如何使用 proxyquire 和 sinon 存根以下模块 var email require emailjs server connect send 我执行了以下操作 但它不起作用 因为当我尝试在内部触发错误时send 它仍然发送电子