ewok
ewok

Reputation: 21443

sinon: stub a function that is not attached to an object

I'm trying to use sinon to stub some functionality of simplegit. The problem is that simplegit behaves in a very annoying fashion: require('simple-git') returns a function, which you need to call in order to get the object that is actually useful. The result of this is that you get a different object each time, making stubbing with sinon (the normal way) impossible.

So I need to stub the function that gets returned by require('sinon'), so that I can override the bahavior of simplegit in its totality. Basically, I want to do something like this (but this doesn't work):

const sinon = require('sinon')
var simplegit = require('simple-git')

//I'm well aware that this isn't valid
sinon.stub(simplegit).callsFake(function() {
  return {
    silent: function() {return this},
    pull: function() {console.log('pulled repo'); return this},
    clone: function() {console.log('cloned repo'); return this}
  }
}

external_function() //this function calls simplegit

This would result in an object that has the functions that I need, but does nothing. It avoids the actual simplegit implementation altogether.

Is this possible to do?

Upvotes: 1

Views: 712

Answers (1)

Patrick Hund
Patrick Hund

Reputation: 20236

Since you are using Jest, this is easy and does not even require Sinon. You can simply use jest.mock, like this, for example:

jest.mock('simple-git', () => function() {
  return {
    silent: function() {return this},
    pull: function() {console.log('pulled repo'); return this},
    clone: function() {console.log('cloned repo'); return this}
  }
})

→ See Jest documentation

When I was learning how to use Jest, I've created a GitHub repo with some code example, perhaps they are useful to you:

https://github.com/pahund/hello-jest

Upvotes: 2

Related Questions