【问题标题】:How to spy inside stub returns with sinon如何用 sinon 窥探存根返回
【发布时间】:2016-09-13 05:10:07
【问题描述】:

你好我想窥探下面的函数,因为函数返回一个promise,所以我需要返回promise让其他代码继续运行。

但它从来没有通过测试,我做错了吗?我怎样才能正确地做到这一点?提前谢谢你。

对不起,我可能没有把问题描述清楚,another_fn 会调用object.method.origin_fn,而orgin_fn 返回一个promise;我想监视origin_fn 被调用。我该怎么做?

let spy_fn = sinon.spy();
sinon.stub(object, 'method').returns({              
    origin_fn(args) {
       spy_fn(args);
       return Promise.resolve();
    }
});

another_fn('test_args');
spy_fn.should.have.been.calledWith('test_args');

【问题讨论】:

    标签: javascript unit-testing sinon stub spy


    【解决方案1】:

    如果您只想确保使用正确的参数调用 origin_fn,您可以使用以下内容:

    let spy = sinon.stub(object, 'method').returns({
      origin_fn(arg) {
        arg.should.equal('test_args');
      }
    })
    
    let fn = function() { another_fn('test_args'); };
    fn.should.not.throw();
    

    【讨论】:

    • 您好,我的问题可能描述的不是很清楚,我已经更新了描述,您可以看看吗?谢谢。 :)
    猜你喜欢
    • 1970-01-01
    • 2018-10-26
    • 2016-10-08
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 1970-01-01
    相关资源
    最近更新 更多