0

假设我们有一个函数测试,它被多次调用,具有不同的值。我们如何为特定的参数值存根它。像下面这样

function test(key, cb) {
    // code
    cb();
}

test('one', function(arg){console.log(arg);});
test('two', function(arg){console.log(arg);});
test('three', function(arg){console.log(arg);});

我想用 'two' 为调用存根,只是为了验证它是否用 'two' 调用一次,并使用 arg 执行回调以检查函数调用后的状态。

4

2 回答 2

0

没有找到任何api解决方案,所以使用了以下方法:

test = sinon.stub();

var calls = test.getCalls().filter(function(call) {
    return call.args[0] === 'two';
});

expect(calls.length).to.be.equal(1);
// to execute callback calls[0].args[0](arg1, arg2)
于 2017-09-22T06:59:13.547 回答
0

你可以通过 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  
于 2017-09-22T21:50:34.057 回答