简体   繁体   English

与Sinon一起在单例中进行存根/间谍

[英]Stub/spy on singleton with Sinon

I have a need to write some unit tests where I check on calls to singleton functions. 我需要编写一些单元测试,以检查对单例函数的调用。 Basically, if I have this: 基本上,如果我有这个:

const somePackage = require('some-package');

And am calling it with: 并用以下方式调用它:

somePackage();

I want to be able to spy/stub on this singleton call to prove that it was called. 我希望能够监视/单打此调用以证明它已被调用。 I know how to do this with methods using sinon.stub(somePackage, 'someMethod') but not for just a singleton. 我知道如何使用使用sinon.stub(somePackage, 'someMethod')方法来做到这sinon.stub(somePackage, 'someMethod')但不仅限于单例。

Right now I actually have to write integration tests by executing the code when in reality I want to write unit tests and show that these external methods were called. 现在,我实际上必须通过执行代码来编写集成测试,而实际上我想编写单元测试并显示这些外部方法已被调用。 I'm trusting that the developer of those packages did their own testing for the functionality. 我相信这些程序包的开发人员会对功能进行自己的测试。

You can spy on any function with sinon: 您可以使用sinon监视任何功能:

const spy = sinon.spy(myFunc);

To stub a single function you can use proxyquire as described in this issue : 存根您可以使用一个功能proxyquire的描述,在此问题

const proxyquire = require('proxyquire')
const sinon = require('sinon')
const sum = sinon.stub()

const ModuleWithDependency = proxyquire('module', {
  'sum': sum
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM