我尝试使用sinon来保留simplegit的某些功能。问题是simplegit以非常恼人的方式运行:require('simple-git')
返回一个函数,您需要调用该函数以获取实际有用的对象。这样做的结果是你每次都得到一个不同的对象,因此不可能用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实现。
这可能吗?
答案 0 :(得分:1)
由于你使用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时,我已经使用一些代码示例创建了一个GitHub仓库,也许它们对您有用: