sinon - Sinon stub argument return fake callback
问题描述
I just want to know if it is possible to fake a callback on a stub argument.
This is basically what I want to achieve and I found nothing on Sinon's documentation:
function A(arg1, arg2, next){
return [arg1, arg2, next];
};
function B(string){
return string;
};
function C(){
return 'Mocked next';
};
var obj = {
A: A,
test: 'test'
};
var result1 = obj.A(1, 2, B('Next')); // result1 = [1, 2, 'Next']
sandbox.stub(obj, 'A')//.Argument[2].Returns(C());
var result2 = obj.A(1, 2, B('Next')); // result2 = [1, 2, 'Mocked next']
Is it possible?
解决方案
对的,这是可能的。
sinon
没有提供直接模拟 a 参数的方法stub
,但它确实提供callsFake
了让您创建自己的实现的方法。
您可以创建一个stub
调用原始实现的方法,并将结果C()
作为第三个参数传递,如下所示:
const original = obj.A; // capture original obj.A
sandbox.stub(obj, 'A').callsFake((...args) => original(args[0], args[1], C()));
const result = obj.A(1, 2, B('Next'));
sinon.assert.match(result, [1, 2, 'Mocked next']); // SUCCESS
推荐阅读
- ssis - 具有行计数条件拆分的 SSIS 查询写入 0 行
- javascript - 禁用 WebRTC 跟踪会停止消耗带宽吗?
- reactjs - 如何在材料表中创建 onHover 动作?
- excel - 无法在 MacOS Catalina 中安装 Excel Desktop 的任何加载项(Microsoft Excel 无法访问该文件)
- javascript - 如何使用浏览器控制台将受保护的 Google Drive pdf 下载为 .jpg 图像?
- django - 如何刷新管理表单上的外键下拉列表
- java - 如何用ant删除配置文件内容?
- ckeditor - 如何将元素从容器移动到另一个容器
- php - 问:如何在 Laravel 7 中创建多认证用户配置文件
- php - 将斜杠添加到 URL 时,基本目录会发生变化