【问题标题】:Mock method and call through original callback通过原始回调模拟方法和调用
【发布时间】:2020-01-04 13:14:00
【问题描述】:

我有一个我正在尝试测试的方法,它通过如下回调调用:

sessionService.getSession(req, res, req.query.state, handleSessionResponse);


有没有办法使用 Sinon 模拟 getSession 方法 调用我的函数中的原始回调 (handleSessionResponse)?换句话说,我不关心getSession 的实现,但无论如何我想委托给handleSessionResponse 来测试它。

这是一个文件示例:

handleSessionResponse(err, data, response) {
    // get to this point and make assertions
}

sessionService.getSession(req, res, req.query.state, handleSessionResponse);

【问题讨论】:

    标签: node.js express sinon


    【解决方案1】:

    试试这个。

    const sinon = require('sinon')
    const { mockReq, mockRes } = require('sinon-express-mock')
    
    let request = {
       query:{
            state:{}
       }
    }
    const req = mockReq(request)
    const res = mockRes()
    
    sinon.stub(sessionService, 'getSession').callsFake((req, res, req.query.state, callback) => {
        callback(null, {}, {})
    });
    

    回调应该调用你原来的handleSessionResponse

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      • 1970-01-01
      • 1970-01-01
      • 2017-10-24
      • 2023-04-02
      • 1970-01-01
      • 2016-06-20
      相关资源
      最近更新 更多