你可以通过 sinon 来完成这一切,方法是定位呼叫stub.withArgs()
并让其他人通过。例如:
const sinon = require('sinon')
let myObj = {
write: function(str, cb){
console.log("original function with: ", str)
cb(str)
}
}
// Catch only calls with 'two' argument
let stub = sinon.stub(myObj, 'write').withArgs("two")
stub.callsFake(arg => console.log("CALLED WITH STUB: ", arg))
// call the caught function's callback
stub.yields('two')
// let all others proceed normally
myObj.write.callThrough();
myObj.write("one", (str) => console.log("callback with: ", str))
myObj.write("two", (str) => console.log("callback with: ", str))
myObj.write("three", (str) => console.log("callback with: ", str))
// Make whatever assertions you want:
sinon.assert.calledOnce(stub) // passes
这导致:
original function with: one
callback with: one
callback with: two
CALLED WITH STUB: two
original function with: three
callback with: three