Proxyquire,rewire,SandboxedModule和Sinon:优点和优点缺点 [英] Proxyquire, rewire, SandboxedModule, and Sinon: pros & cons

查看:150
本文介绍了Proxyquire,rewire,SandboxedModule和Sinon:优点和优点缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在模拟Node依赖项时,我遇到了以下库:

When mocking Node dependencies, I've happened upon the following libraries:

  • Proxyquire
  • Rewire
  • SandboxedModule
  • Sinon

它们似乎或多或少都在做同一件事:允许您模拟require()调用(Sinn除外,它几乎模拟了所有内容).他们似乎都需要进行一些相当复杂的设置,注意传递给require的字符串的确切语法-在重构过程中效果不佳.

They all seem to do more-or-less the same thing: allow you to mock require() calls (with the exception of Sinon which mocks pretty much everything). They all seem to require some pretty elaborate setup, noting the exact syntax of the string passed to require -- not great during refactoring.

每个库的优缺点是什么?我什么时候可以选择一个?每个库都擅长的示例用例是什么?在这个领域中还有哪些其他更好的产品?

What are the pros and cons of each library? When would I choose one over the other? What are example use-cases where each library excels? What are other products in this space that are better?

推荐答案

完全感觉像是在作弊,但是由于没有其他人在回答这个问题,所以去了:

It totally feels like cheating, but since no one else is answering the question, here goes:

  • Proxyquire接管了require,并允许您在依赖项链中的任何位置注入伪造品.对于require,您不会接管,对于未定义require的方法,您会接管原始文件.可以使用noCallThru禁用它.因此,它仍然可以加载原始内容,只是用您定义的内容替换内容.与Rewire和SandboxedModule不同,您不能为require重载定义全局变量.

  • Proxyquire takes over require and lets you inject fakes anywhere in the dependency chain. For requires you don't take over and for methods you don't define for requires you do take over, it'll fall back to the original. This can be disabled with noCallThru. Thus it still loads the original, just replaces things with the things you define. Unlike Rewire and SandboxedModule, you can't define global variables for your require overloads.

Rewire接管require,并将__get____set__属性注入到每个模块中.如果知道私有变量名称,则可以替换它.考虑依赖注入.

Rewire takes over require and injects __get__ and __set__ properties into each module. If you know the private variable name, you can replace it. Think dependency injection.

SandboxedModule与Proxyquire几乎相同,除了它在新的V8虚拟机中运行整个过程. (此方法会降低每次测试的性能成本.)它在v 1.0中还存在一个令人讨厌的错误,当您不替换的内容引用了它不支持的本机模块时,该错误将使其失败.参见 https://github.com/robrich/sandboxed-module-graceful-fs.

SandboxedModule is nearly identical to Proxyquire except it runs the entire process in a new V8 vm. (There is a per-test performance cost to this approach.) It also has a nasty bug in v 1.0 that makes it fail when something you didn't replace references a native module it doesn't support. See https://github.com/robrich/sandboxed-module-graceful-fs.

Sinon不会像其他3个那样接管require.相反,它是一个更为传统的模拟框架.用伪造品替换指定的方法,或创建一个跟踪调用时间的模拟程序.

Sinon doesn't take over require like the other 3. Rather, it's a more traditional mocking framework. Replace specified methods with fakes, or create a mock that tracks when it was called.

这篇关于Proxyquire,rewire,SandboxedModule和Sinon:优点和优点缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆