sinon:存根一个没有附加到对象的函数

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

我正在尝试使用 sinon to stub some functionality of simplegit。问题是 simplegit 的行为非常烦人:require('simple-git') returns 一个函数,您需要调用它才能获得实际有用的对象。这样做的结果是你每次都得到一个不同的对象,不可能用 sinon(正常方式)进行存根。

所以我需要存根 require('sinon') 返回的函数,这样我就可以完全覆盖 simplegit 的行为。基本上,我想像这样做一些事情(但这不起作用):

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

这会产生一个具有我需要的功能但什么都不做的对象。它完全避免了实际的 simplegit 实现。

这可以吗?

由于您使用的是 Jest,这很容易,甚至不需要 Sinon。您可以简单地使用 jest.mock,例如:

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}
  }
})

→ 见Jest documentation

当我学习如何使用 Jest 时,我创建了一个包含一些代码示例的 GitHub 存储库,也许它们对您有用:

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