简体   繁体   中英

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.

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:

const spy = sinon.spy(myFunc);

To stub a single function you can use proxyquire as described in this issue :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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