首页 > 解决方案 > 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

解决方案


对的,这是可能的。

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

推荐阅读