0

I have something like:

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

which returns my custom response when it hits this code:

return await rp.get(url, options)

But how can I do something like this:

    sandbox.stub(rp).resolves(successResponse)

Which can return a custom response when it hits this code?

    return await rp(url, options)

When I attempt "stubbing" the entire object, I get this error when I run the test:

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)

rp is request-promise-native, which wraps request

  • 1
    Not an answer, but why not just make your own stub. The code will be simpler: `rp.get = () => Promise.resolve(stubresponse)` – Aluan Haddad Jan 23 '18 at 22:27
  • [Possible duplicate](https://stackoverflow.com/questions/21072016/stubbing-a-class-method-with-sinon-js) – Troopers Jan 24 '18 at 13:01
  • @Troopers sorry, that issue is different than my case. That problem follows the `(class, method)` pattern, but my call to `rp` doesn't fit that. –  Jan 24 '18 at 13:55
  • @Houseman : Show us how you define `rp` in the second case. – Troopers Jan 24 '18 at 14:07
  • [Similar question with es6](https://stackoverflow.com/questions/34575750/how-to-stub-exported-function-in-es6) – Troopers Jan 24 '18 at 14:15
  • @Troopers I've edited the question to show how I define `rp`. The similar es6 question doesn't quite fit, because that's still `foo.bar()`. For it to be equivalent, it would have to be just `foo()`. –  Jan 24 '18 at 14:21
  • [Third try](https://github.com/sinonjs/sinon/issues/664) – Troopers Jan 24 '18 at 15:08

2 Answers2

1

From @Troopers' link in the comments above, it seems like this isn't possible: Doing this is not technically possible without faking the entire module loading system.

So I followed the suggestion here: https://github.com/request/request/issues/2181 and used mock-require to stub rp. I also changed up my code that used to call rp.get(), so that it just calls rp(), since I couldn't also figure out how to stub both rp() and rp.get()

0

You might find the Sinon HowTo about Link Seams helpful: http://sinonjs.org/how-to/link-seams-commonjs/

mantoni
  • 1,612
  • 11
  • 10