gpt4 book ai didi

javascript - 诗乃JS : Is there a way to stub a method on object argument's key value in sinon js

转载 作者:数据小太阳 更新时间:2023-10-29 05:14:55 24 4
gpt4 key购买 nike

我想在以下响应中模拟对 obj.key3 值的不同响应。就像 if obj.key3=true 然后返回与 obj.key3=false 不同的响应

function method (obj) {
return anotherMethod({key1: 'val1', key2: obj.key3});
}

最佳答案

您可以使用 .withArgs() 和对象匹配器根据调用它的参数使 stub 返回(或执行)某些操作。

例如:

var sinon = require('sinon');

// This is just an example, you can obviously stub existing methods too.
var anotherMethod = sinon.stub();

// Match the first argument against an object that has a property called `key2`,
// and based on its value, return a specific string.
anotherMethod.withArgs(sinon.match({ key2 : true })) .returns('key2 was true');
anotherMethod.withArgs(sinon.match({ key2 : false })) .returns('key2 was false');

// Your example that will now call the stub.
function method (obj) {
return anotherMethod({ key1 : 'val1', key2: obj.key3 });
}

// Demo
console.log( method({ key3 : true }) ); // logs: key2 was true
console.log( method({ key3 : false }) ); // logs: key2 was false

有关匹配器的更多信息 here .

关于javascript - 诗乃JS : Is there a way to stub a method on object argument's key value in sinon js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34350290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com