简体   繁体   English

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

[英]How can we stub and respond to a particular function call in sinon js

Suppose we have a function test, that has been called multiple times with different values. 假设我们有一个功能测试,它以不同的值被多次调用。 How can we stub it for a particular parameter value. 我们如何将其存入特定的参数值。 Like in the following 像下面

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);});

I want to stub it for the call with 'two' only to verify if it is called once with 'two' and also execute callback with arg to check the state after function call. 我只想对它进行调用以“ two”调用,以验证是否用“ two”调用过一次,并且还用arg执行回调以检查函数调用后的状态。

Didn't find any api solution so used the following approach: 找不到任何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)

You can do this all with sinon by targeting the call with stub.withArgs() and letting the others pass through. 您可以使用sinon通过使用stub.withArgs()定位调用并让其他人通过来完成所有这些操作。 For example: 例如:

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

This results in: 结果是:

original function with:  one  
callback with:  one  
callback with:  two  
CALLED WITH STUB:  two  
original function with:  three  
callback with:  three  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM