【问题标题】:stub an object without requiring a method存根对象而不需要方法
【发布时间】:2018-01-23 22:24:46
【问题描述】:

我有类似的东西:

sandbox.stub(rp, 'get').resolves(successResponse)

当它遇到此代码时返回我的自定义响应:

return await rp.get(url, options)

但是我该怎么做这样的事情:

    sandbox.stub(rp).resolves(successResponse)

点击此代码时,哪个可以返回自定义响应?

    return await rp(url, options)

当我尝试“存根”整个对象时,我在运行测试时收到此错误:

TypeError: Attempted to wrap undefined property undefined as function
      at wrapMethod (node_modules\sinon\lib\sinon\util\core\wrap-method.js:70:21)
      at stub (node_modules\sinon\lib\sinon\stub.js:58:44)
      at Object.stub (node_modules\sinon\lib\sinon\collection.js:93:33)

rprequest-promise-native,它包裹了request

【问题讨论】:

  • 不是答案,但为什么不自己制作存根。代码会更简单:rp.get = () => Promise.resolve(stubresponse)
  • @Troopers 抱歉,这个问题与我的情况不同。该问题遵循(class, method) 模式,但我对rp 的调用不符合该模式。
  • @Houseman : 向我们展示您如何在第二种情况下定义 rp

标签: node.js typescript sinon stub request-promise


【解决方案1】:

从上面 cmets 中的@Troopers 链接来看,这似乎是不可能的:Doing this is not technically possible without faking the entire module loading system.

所以我遵循了这里的建议:https://github.com/request/request/issues/2181 并使用 mock-require 存根 rp。我还修改了我以前调用rp.get() 的代码,使它只调用rp(),因为我也不知道如何存根rp()rp.get()

【讨论】:

    【解决方案2】:

    您可能会发现有关 Link Seams 的 Sinon HowTo 很有帮助:http://sinonjs.org/how-to/link-seams-commonjs/

    【讨论】:

      猜你喜欢
      • 2016-04-18
      • 1970-01-01
      • 2014-10-26
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2015-07-29
      • 2020-09-02
      相关资源
      最近更新 更多