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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Could you please let me know what you meant by " can wrap that library in your own code".
you could wrap it like this ... module.exports = () => { theirLib.theirFunc() } ... then use sinon's callsFake .. see stackoverflow.com/questions/21072016/… - here you would prob wanna export a class instead of a function
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.