我们如何在sinon js中存根并响应特定的函数调用

时间:2017-09-21 13:35:31

标签: javascript sinon sinon-chai

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

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执行回调以检查函数调用后的状态。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

您可以通过使用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