1

I have an api in index.js which does a post request. The method which does the channel subscription is subscribeToChannel. I would like to know some hint. I am new to nodejs and I am feeling a bit tough to mock/stub objects using sinon. Mockito for java was easier. I am using mocha, chai but none of them I feel is comfartable and feel very very trickey may be because of less exposure of Nodejs.

The below API doesnt even have a module.exports=server variable inorder to inject or call the method. How do I mock the methods of below file. Reply will be appreciated.

Sawyer
  • 423
  • 1
  • 7
  • 23
  • I think you forgot to include a link to the API. Can you please share your progress so far? Please see [How to Create a Minimum, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) for help. – sbolel Jan 23 '18 at 17:16

1 Answers1

2

To mock the response of an API call you use nock:

https://www.npmjs.com/package/nock

You use it inside your mocha chai unit tests.

Basically with nock you say ... when a POST is made to /my/endpoint THEN respond with ... your mock response

Hopefully this is what you need.

Alternatively, if you don't need to mock an HTTP request but a node JS library then you can wrap that library in your own code and then mock your wrapper methods.

danday74
  • 52,471
  • 49
  • 232
  • 283
  • Could you please let me know what you meant by " can wrap that library in your own code". – Sawyer Jan 08 '18 at 10:25
  • you could wrap it like this ... module.exports = () => { theirLib.theirFunc() } ... then use sinon's callsFake .. see https://stackoverflow.com/questions/21072016/stubbing-a-class-method-with-sinon-js - here you would prob wanna export a class instead of a function – danday74 Jan 08 '18 at 12:48
  • I don' t have the possibility for { theirLib.theirFunc() } as there is no module.exports for the index.js file where the above code is. I don't have any possibility to export or wrap the functions. If I do var index= require('./index.js') then next how should I call the above functionality. And if I wrap the code how can I achieve 100% code coverage as I am not even utilising the require of index.js and without an entry point to it – Sawyer Jan 10 '18 at 00:14