[英]sinon: how to mock a function that is returned from another function
我正在嘗試使用simple-git 。 我需要編寫一些單元測試,為此我需要使用sinon模擬一些函數。 我遇到的問題是我的模擬不會傳播到我測試的文件中。
例如,在測試的文件中,我有:
const git = require('simple-git/promise')
function func () {
var promise
if (repo_exists()) {
promise = git().silent(true).clone('http://github.com/me/my-repo.git')
} else {
promise = git('my-repo').silent(true).pull('origin','master')
}
promise.then(() => {
// do more stuff
})
}
在我的測試文件中,我試過這個:
const git = require('simple-git/promise')()
sinon.stub(git, 'silent').callsFake(() => {
return {
clone: () => {
console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~')
console.log('calling clone')
console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~')
return new Promise((resolve, reject) => {
console.log('clone')
resolve()
})
},
pull: () => {
console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~')
console.log('calling pull')
console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~')
return new Promise((resolve, reject) => {
console.log('pull')
resolve()
})
}
}
})
但是模擬的函數不會被調用。 我假設原因是require('simple-git/promise')
返回一個函數,該函數本身返回包含我想要模擬的函數的對象,但我不知道如何處理它。
你是對的,當調用git()
,它每次都返回一個新對象。 此對象的方法最終代理到Git
的實例( https://github.com/steveukx/git-js/blob/master/src/git.js )
作為一個選項,可以存根內部_run
的方法Git.prototype
(負責調度要執行的命令的方法):
const Git = require('simple-git/src/git');
sinon.stub(Git.prototype, '_run').callsFake(function (command, cb) {
console.log('called command', command)
// to indicate success (will resolve eventual promise)
cb.call(this, null, 'any message');
// OR to indicate failure (will reject eventual promise)
Git.fail(this, 'error message', cb);
return this;
});
注意, callsFake
下的非箭頭功能對於保留this
是必不可少的,並且需要return this
以符合原始行為( https://github.com/steveukx/git-js/blob/master/src/git.js#L1271 ) 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.