当前位置:  开发笔记 > 编程语言 > 正文

Sinon JS:有没有办法在sinon js中对对象参数的键值存根方法

如何解决《SinonJS:有没有办法在sinonjs中对对象参数的键值存根方法》经验,为你挑选了1个好方法。

我想在以下响应中模拟对obj.key3值的不同响应.就像obj.key3 = true一样,返回与obj.key3 = false不同的响应

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

robertklep.. 7

你可以根据使用它.withArgs()和对象匹配器调用的参数来返回(或做)某些东西.

例如:

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

在匹配器的更多信息这里.



1> robertklep..:

你可以根据使用它.withArgs()和对象匹配器调用的参数来返回(或做)某些东西.

例如:

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

在匹配器的更多信息这里.

推荐阅读
ar_wen2402851455
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有